After going through post provided for the same problem, I have written the following code. But I am getting the following exception :
javax.mail.MessagingException:
Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is: java.net.ConnectException: Connection timed out: connect
public static void main(String[] args) {
String to = "[email protected]" // valid gmail address.
String from = "[email protected]"; // valid gmail address
String host = "smtp.gmail.com";
String password = "****"; // password of the gmaill acc used in from
int port = 587;
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host",host );
properties.setProperty("mail.smtp.user", from);
properties.setProperty("mail.smtp.password", password);
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,null);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Test Mail");
message.setText("This is just a test mail generated");
Transport transport = session.getTransport("smtp");
transport.connect(host,from,password);
InternetAddress[] addresses = new InternetAddress[1];
addresses[0] = new InternetAddress(to);
transport.sendMessage(message,addresses);
System.out.println("Message Sent Successfully");
}catch(MessagingException excp){
System.out.println(excp);
}
}
Can somebody tell mistake that I am doing. Is there any setting in my gmail account which needs to be set to use the gmail smtp server?
Try the following code. You will need to download
javax.mail
package (A jar file), I assumed that you would have already that jar file because you have tried this code and consequently, I don't provide the link to download that jar file. Set the class path properly and import the necessary packages. Take care with the firewall and the host port you selected.