0

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.

tenten
  • 1,276
  • 2
  • 26
  • 54
BK Tomer
  • 107
  • 2
  • 11
  • Possible duplicate of [MailConnectException while sending mail using java mail api](http://stackoverflow.com/questions/20766044/mailconnectexception-while-sending-mail-using-java-mail-api) – Linda Lawton - DaImTo Jul 14 '16 at 09:14
  • @DalmTo Not exactly. 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. – BK Tomer Jul 14 '16 at 09:17
  • I also connect with username and access token instead of username and password. – BK Tomer Jul 14 '16 at 09:18

1 Answers1

2

You're missing some basic understanding of the JavaMail API. Stores are for reading messages, Transports are for sending messages. The basic examples for Gmail are in the JavaMail FAQ. Try that code, and if it still doesn't work, update your question with the code you're using and post the JavaMail debug output.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40