I have tried to send a simple e-mail to any gmail account using Gmail SMTP. getting the below error.
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect
My code is
package common;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.smtp.SMTPMessage;
public class SimpleMail{
/**
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for SSL: 465
*/
public static void main(String[] args) {
String to="[email protected]";
String subject="New Mail";
String msg="test test";
final String user="gmailuser";
final String pass="gmailpassowd";
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587"); //this is optional
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props,new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,pass);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject(subject);
message.setText(msg);
Transport.send(message);
System.out.println("Mail sent..");
}catch(Exception e)
{
System.out.println(e);
}
}
}
Gmail security setting->Account permission->Access for less secure apps