What is the problem with this code? Somehow it is getting in to an infinity loop at the line Transport.send(message);
line, no error message, no exception, just maybe infinite loop (i don't know because i don't wait more than 5-10minute)
final String username = "<mail_name>";
final String password = "<password>";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("<mail_from>@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("<mail_to>@gmail.com"));
message.setSubject("Test Subject");
message.setText("Test");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
Ok. It is a little more complex than i tought for the first time... To summorize what i got:
session.setDebug(true);
. If you set this true, every important process will be debuged to the console. I recommend to use it.Transport transport = session.getTransport("smtps");
rather of the non secure smtp... The JavaMail API Transport object will also take care of the ports (respectively smtp: 587, smtps: 465)You can use also the static method of the Transport class for sending the message and (saving it before, non static sendMessage method will not save the message), but this time you need to use the javax.mail.Authenticator at the session creation, like this:
});
1.4.2 JavaMailApi has another Exception than 1.4.7 version for this issue...
If you don't use it, you can not authenticated with the static method. If you use the instance method, you can.
So pretty messed up, but there were some basic concept which should be focused...
I could reproduce the behaviour described in your question and fix it.
The
send
method gets stuck atThe connection does not succeed because you have the wrong port for the gmail smtp host:
465
change it to
587
and it will work.
Here I am giving some changes, that work fine for me:
You instantiate message object as you did. And finally:
Edit, would you please give me a favor and copy/paste and try this example and show what it displays:
Using Simple Java Mail it should be straightforward:
If you have two-factor login turned on, you need to generate an application specific password from your Google account.