Reputation: 1163
I am creating an application where I want to send an email to my clients.When i compiled the below code its ok but when i run it gives me error as follows
java code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEmail
{
public static void main(String [] args)
{
String to = "[email protected]";
String from = "[email protected]";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("smtp.gmail.com", host);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
error:
Please guide me.
Upvotes: 0
Views: 2033
Reputation: 29646
Have you read the Fundamentals of the JavaMail API?
Anyways, from what I can tell the issue is that you're using invalid configuration.
properties.setProperty("smtp.gmail.com", host);
As you can see in the JavaMail API documentation, JavaMail does not support a property named smtp.gmail.com
. What you probably intended was actually...
properties.setProperty("mail.smtps.host", host);
I suspect you wish to use Gmail's SMTPS server, not one hosted on localhost
as you have it now, so I'd advise changing your code such that...
final String host = "smtp.gmail.com";
You also wish to use authnetication, which JavaMail
suggests you can do in their FAQ on Gmail as follows:
properties.setProperty("mail.smtps.auth", "true");
Note that Gmail requires authenticating to send mail as such. It appears another answer suggested you can configure the username/password using the session properties; unfortunately, this is incorrect.
What you want to do is use an Authenticator
.
final Session session = Session.getInstance(properties, new Authenticator() {
static final PasswordAuthentication AUTH = new PasswordAuthentication(USER, PASS);
protected PasswordAuthentication getPasswordAuthentication() {
return AUTH;
}
});
Upvotes: 0
Reputation: 2628
String host = "smtp.gmail.com";
Properties properties = new Properties();
set following properties
properties .put("mail.smtp.starttls.enable", "true");
properties .put("mail.smtp.host", host);
properties .put("mail.smtp.user", username);
properties .put("mail.smtp.password", password);
properties .put("mail.smtp.port", "587");
properties .put("mail.smtp.auth", "true");
Upvotes: 2