Debs
Debs

Reputation: 41

Sending email SMTP via GMAIL (OAUTH2 and JavaMail)

I'm using a web application through which I'm sending an email. The SMTP host is GMAIL. I'm using Java 1.8 and JavaMail 1.6.2.

Is there any alternative to the code written below? (credits: https://hellokoding.com/sending-email-through-gmail-smtp-server-with-java-mail-api-and-oauth-2-authorization/)

void sendMail(String smtpServerHost, String smtpServerPort,  String smtpUserName, String smtpUserAccessToken, String fromUserEmail, String fromUserFullName, String toEmail, String subject, String body) {
    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", smtpServerPort);
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props);
        session.setDebug(true);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromUserEmail, fromUserFullName));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        msg.setSubject(subject);
        msg.setContent(body, "text/html");

        SMTPTransport transport = new SMTPTransport(session, null);
        transport.connect(smtpServerHost, smtpUserName, null);
        transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", smtpUserName, smtpUserAccessToken).getBytes())), 235);
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
}

Specifically I'm very confused about these two issues:

  1. is the following line truly the only way to set the access token in the Transport?

transport.issueCommand("AUTH XOAUTH2 " + new String(BASE64EncoderStream.encode(String.format("user=%s\1auth=Bearer %s\1\1", smtpUserName, smtpUserAccessToken).getBytes())), 235);

I've been searching throughout the web but I don't seem to find an answer, basically because every other way I've attempted has resulted in NO success.

  1. Is it true that Google has not (yet) implemented a CLIENT credentials grant type? How else could I send emails through my web application without the user interaction (which I don't have)?

Thank you

Upvotes: 2

Views: 2508

Answers (1)

Lincoln Brown
Lincoln Brown

Reputation: 1

Try this:

//TLS and OAuth2

String address = "my.smtpserver.com";
Integer port = 587;
String user = "my_username";
String accesstoken = "my_accesstoken";
String sender = "me@mycompany.com";
String recipients = "you@yourcompany.com;someone@theircompany.com";
String subject = "Test";
String body = "This is a test.";

Properties properties = new Properties();
properties.put("mail.smtp.host", address);
properties.put("mail.smtp.port", port.toString());
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.auth.mechanisms", "XOAUTH2");
properties.put("mail.debug.auth", "true");

Session session = Session.getInstance(properties);
session.setDebug(true);

MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(sender));
String s = recipients.replace(';', ',');
mimeMessage.addRecipients(MimeMessage.RecipientType.TO, 
InternetAddress.parse(s));
mimeMessage.setSubject(subject);

MimeMultipart mimeMultipart = new MimeMultipart();

MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setText(body);
mimeMultipart.addBodyPart(mimeBodyPart);

mimeMessage.setContent(mimeMultipart);

Transport transport = session.getTransport();

transport.connect(user, accesstoken);       
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

transport.close();

session = null;

Upvotes: 0

Related Questions