I am trying to send an email in a java application calling this method:
public static void sendEmail() {
// Create object of Property file
Properties props = new Properties();
// this will set host of server- you can change based on your requirement
props.put("mail.smtp.host", "smtp.office365.com");
// set the port of socket factory
//props.put("mail.smtp.socketFactory.port", "587");
// set socket factory
//props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
// set the authentication to true
props.put("mail.smtp.auth", "true");
// set the port of SMTP server
props.put("mail.smtp.port", "587");
// This will handle the complete authentication
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xx#mail.com", "xx");
}
});
try {
// Create object of MimeMessage class
Message message = new MimeMessage(session);
// Set the from address
message.setFrom(new InternetAddress("xx#mail.com"));
// Set the recipient address
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("yy#mail.com"));
// Add the subject link
message.setSubject("Testing Subject");
// Create object to add multimedia type content
BodyPart messageBodyPart1 = new MimeBodyPart();
// Set the body of email
messageBodyPart1.setText("This is message body");
// Create object of MimeMultipart class
Multipart multipart = new MimeMultipart();
// add body part 2
multipart.addBodyPart(messageBodyPart1);
// set the content
message.setContent(multipart);
// finally send the email
Transport.send(message);
System.out.println("=====Email Sent=====");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
but for some reason when the debug hits Transport.send(), I got this exception:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [DB6PR0802CA0037.eurprd08.prod.outlook.com]
why is this happening even though I used the Authenticator()?
If you connect via port 587 you initially start a plain connection where you have to start TLS by explicitly sending the STARTTLS-command. You have to tell JavaMail to do that, otherwise it will try to proceed unsecured. The SMTP-server doesn't send any authentication-mechanism-informations unless the TLS-connection is established, so JavaMail is assuming that no authentication is needed and tries to send the mail without.
Add the following entry to the properties:
props.put("mail.smtp.starttls.enable", "true");
WIth that JavaMail should try to switch to TLS before trying to authenticate.
If that fails, you need to enable debugging by setting the property
props.put("mail.debug", "true");
and post the output here.
Related
I have a simple web application where different users can log into it. One of the important feature is user can access a document and send email of it's content to an outsider like third party. Below is just how the email looks like to give an idea:
It's pretty self explanatory and I can send to multiple user if I want like abc#example.com,efg#hotmail.com,... in the field box shown.With all this, I am using Java Mail API to make it work and after hitting the send button,it sends directly to the recipient.No issue at all.
Now, I want to modify this by doing this email feature as a service.What this means is when I send the email,the content and info filled in will be stored in a table in MYSQL and the service(running in background) will pick up from the table and do the sending.
This is my function:
public void sendEmail(String recipient, String subject, String content,
String host, String port, final String senderaddress,
final String password) {
try {
System.out.println("Please Wait, sending email...");
/*Setup mail server */
Properties props = new Properties();
props.put("mail.smtp.host", host); //SMTP Host
props.put("mail.smtp.port", port); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
//create Authenticator object to pass in Session.getInstance argument
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderaddress, password);
}
};
Session session = Session.getInstance(props, auth);
session.setDebug(true);
// Define message
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(senderaddress));
message.addRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipient));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(content);
try {
Transport.send(message);
} catch (AddressException addressException) {
addressException.printStackTrace();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Can this be done in the way I want because I am unsure how to make it work?
1 ) After hitting Sending mail button from UI, You need to call a method for saving data like recipient, subject, content in DB
2)Write an email sender Service which retrieves non_delivered / pending mail from DB table and send it through Java Mail API
3)Scheduled email sender service with the help of ScheduledExecutorService
I'm trying to send email using java API and i'm giving the right emailid and password but still i get AuthenticationFailedException.
I also tried giving host=mail.smtp.port and changing port to 587 still i end up getting the same error..
Please help me where i'm going wrong..?
public class SendEmail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "to#gmail.com";
// Sender's email ID needs to be mentioned
final String from = "from#gmail.com";
// Assuming you are sending email from localhost
final String host = "smtp.googlemail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.user", from);
//properties.setProperty("mail.smtp.password", "xyz");
properties.setProperty("mail.debug", "false");
properties.setProperty("mail.smtp.auth", "true");
// properties.setProperty("mail.smtp.port", "587");
// Get the default Session object.
// Session session = Session.getDefaultInstance(properties);
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "xyz");
}
});
session.setDebug(true);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("This is actual message");
// Send message
// Transport.send(message);
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
Error:
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at javax.mail.Service.connect(Service.java:105)
at javax.mail.Transport.send0(Transport.java:168)
at javax.mail.Transport.send(Transport.java:98)
Just check if you have enabled logging in from "Less Secure Apps" using this link. This setting needs to be enabled for the account from#gmail.com.
I need to send at least 200 messages from a stretch. When the program starts, send mail successfully to 15 or 17, then I get this error:
MESSAGE ERROR:
com.sun.mail.smtp.SMTPSendFailedException: 421 4.4.2 Message submission rate for this client has exceeded the configured limit
What I can do?
CODE JAVA
public void mandarEmail(String correos, String mensaje, String asunto) {
Message message;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.host", "pod51004.outlook.com");
props.put("mail.smtp.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("docemail#usmp.pe", "docpass");
}
});
try {
message = new MimeMessage(session);
message.setFrom(new InternetAddress("USMP - FN <documentos-fn#usmp.pe>"));
message.setSubject(asunto);
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(correos));
message.addRecipients(Message.RecipientType.BCC, new InternetAddress[]{new InternetAddress("ivan_pro_nice#hotmail.com")});
message.setContent(mensaje, "text/html; charset=utf-8");
Transport transport = session.getTransport("smtp");
transport.connect("docemail#usmp.pe", "docpass");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
throw new RuntimeException(e);
} finally {
props = null;
message = null;
}
}
That's the server you're connecting to, and not a client issue. Here's a doc on how to parse SMTP codes from the server.
A mail server will reply to every request a client (such as your email
program) makes with a return code. This code consists of three
numbers.
In your case, you're getting 421.
You probably need to pay for a "business" account from your mail server vendor so they'll let you send more email.
if you want to send single email to 200 clients. Than u can add an array of reciever's email addresses of size upto 50.
but i you want to send different msg for each email. Then you can create a new connection to email server with a counter that counts send emails as well as it counts 15 it should create a new connection.
to test your code use mailtrap.io
I am sending email using
public void sendEmail(String fromEmailAddr, String toEmailAddr,String subject, String emailBody) {
String host = "xxx";
final String user = "user";
final String password = "password";
// Get system properties
Properties properties = new Properties();
// Setup mail server
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "25");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(fromEmailAddr));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmailAddr));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(emailBody);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
When i try to send email using above code then it comes to message Sent message successfully.... but i got no email. On the other hand if i use authentication then i got the email
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
Why ? Is it necessary to provide userName and password for host ? Can i send email by just specifying host, no username and password provided ?
Thanks
I guess the port number might be the issue.
Try changing properties.put("mail.smtp.port", "25");
to properties.put("mail.smtp.port", "587");.
Further you can refer this.
It depends on the mail server you're using.
For example, some mail servers will let you send mail to anyone in the same company without authentication, but authentication is needed to send mail outside of the company. In the latter case, if you send the mail without authenticating, the mail server may accept the message and return a "mailer-daemon" failure message, or might just throw the message away.
Also, see this list of common JavaMail mistakes.
I am writing a simple Java program to send mail, but am getting errors. Here's the code:
package mypackage;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
// Send a simple, single part, text/plain e-mail
public class Sendmail {
public static void main(String[] args) {
// SUBSTITUTE YOUR EMAIL ADDRESSES HERE!!!
String to = "atul.krbhatia#gmail.com";
String from = "atul.krbhatia#gmail.com";
// SUBSTITUTE YOUR ISP'S MAIL SERVER HERE!!!
String host = "smtp.gmail.com";
// Create properties, get Session
Properties props = new Properties();
// If using static Transport.send(),
// need to specify which host to send it to
props.put("mail.smtp.host", host);
// To see what is going on behind the scene
props.put("mail.debug", "true");
Session session = Session.getInstance(props);
try {
// Instantiatee a message
Message msg = new MimeMessage(session);
System.out.println("in try blk");
//Set message attributes
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test E-Mail through Java");
msg.setSentDate(new Date());
// Set message content
msg.setText("This is a test of sending a " +
"plain text e-mail through Java.\n" +
"Here is line 2.");
//Send the message
Transport.send(msg);
}
catch (MessagingException mex) {
// Prints all nested (chained) exceptions as well
System.out.println("in catch block");
mex.printStackTrace();
}
}
}//End of class
Here's the errors:
221 2.0.0 closing connection d1sm3094152pbj.24
in catch block
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. d1sm3094152pbj.24
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1580)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1097)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at mypackage.Sendmail.main(Sendmail.java:48)
Gmail only supports SMTP over SSL/TLS.
Add
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
You also need to login to the server:
props.put("mail.smtp.host", "smtp.gmail.com");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
A simple google search for "javamail gmail" will yield many example of how to use JavaMail with GMail, like this one. Google also has a configuration page listing the connection configuration that you'll need so you can double check the settings.
This URL May help:
http://sbtourist.blogspot.com/2007/10/javamail-and-gmail-its-all-about.html
It looks like the server is expecting SSL. There are several other questions on here where people are also trying to send mail through Gmail using Java, I recommend taking a look at them.
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
Must issue a STARTTLS command first. Sending email with Java and Google Apps