JavaMail - send authenticated oauth2 smtp mail
<p>I am trying to send an authenticated email via Gmail server with JavaMail API 1.5.5. </p>

<p>I followed the tutorial in <a href="https://java.net/projects/javamail/pages/OAuth2" rel="nofollow">javaMailAPI 1.5.5 site</a> and used <a href="https://github.com/google/gmail-oauth2-tools/blob/master/python/oauth2.py" rel="nofollow">this google tool</a> but did not succeed to send a mail.   </p>

<p>Here is what I did:</p>

<pre><code>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);

} 
</code></pre>

<p>I got the following execption: </p>

<pre><code>com.sun.mail.util.MailConnectException
Couldn't connect to host, port: localhost, 25; timeout -1
</code></pre>

<p>I also tried to switch the imap in the properties' names to smtp, but in that case the program was stuck on</p>

<pre><code>store.connect("imap.gmail.com", username, accessToken);
</code></pre>

<p>How can I solve it? I searched online for an answer but did not find one.</p>

<p><strong>Edit :</strong></p>

<p>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. </p>

<p>It says there is an authentication problem. In addition, I do not use username and password but username and access token given by google.</p>