I am trying to send an authenticated email via Gmail server with JavaMail API 1.5.5.
I followed the tutorial in javaMailAPI 1.5.5 site and used this google tool but did not succeed to send a mail.
Here is what I did:
private static void sendEmail(String _emailBody){
//used oauth2.py in order to retrieve the access token
String accessToken = getAccessToken(refresh_token,username,client_id,client_secret);
// Setup mail server
Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true"); // required for Gmail
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", username, accessToken);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(username));
msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(_email));
msg.setSubject("some subject");
msg.setText(_emailBody);
Transport.send(msg);
}
I got the following execption:
com.sun.mail.util.MailConnectException
Couldn't connect to host, port: localhost, 25; timeout -1
I also tried to switch the imap in the properties' names to smtp, but in that case the program was stuck on
store.connect("imap.gmail.com", username, accessToken);
How can I solve it? I searched online for an answer but did not find one.
Edit :
Not exactly the same question as suggested. I use oauth2 authentication on JavaMailAPI 1.5.5, which was released in 2016. The connection method is different. The old one does not work.
It says there is an authentication problem. In addition, I do not use username and password but username and access token given by google.