I try to create some auto send mail using java But there's some error when buliding the projects. Here's the code.
package sendmail2;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage;
public class SendMail2 {
public static void main(String[] args) {
try{
String host ="smtp.gmail.com" ;
String user = "[email protected]";
String pass = "mypassword";
String to = "my reciever";
String from = "[email protected]";
String subject = "Test App";
String messageText = "Congrats";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject); msg.setSentDate(new Date());
msg.setText(messageText);
Transport transport=mailSession.getTransport("smtp");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("message send successfully");
}
catch(Exception ex)
{
System.out.println(ex);
}
}
}
The error is
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587; nested exception is: java.net.ConnectException: Connection timed out: connect BUILD SUCCESSFUL (total time: 21 seconds)
I already add activation.jar and also mail.jar in the library. and Turn on less secure app access in gmail account.
The question is I don't know if my code or something wrong and the solutions to make it works
This is my first time using stack overflow so If my question is not clear or hard to read. just let me know and sorry for the inconvinience.
The JavaMail FAQ has tips for debugging connection problems.
Most likely there's a firewall preventing you from connecting directly. The JavaMAil FAQ also describes how to connect through a proxy server.