HelloKoding

Practical coding guides

Sending Email Example with Java Mail API and Gmail SMTP Server

This tutorial will walk you through the steps of building a Sending Email Example with Gmail and Java Mail API.

Sending Email Example with Java Mail API and Gmail SMTP Server

What you’ll need

  • JDK 1.7+
  • Maven 3+
  • OAuth Access Token of your Google Account. Check out more details on How to get the access token at OAuth2DotPyRunThrough

Stack

  • Java
  • Java Mail API
  • OAuth 2 Authorization Flow
  • SMTP Server
  • Sending Email

Init project structure and dependencies

Project structure

├── src
│   └── main
│       └── java
│           └── com
│               └── hellokoding
│                   └── mail
│                       ├── Main.java
│                       └── SendingMailThroughGmailSMTPServer.java
└── pom.xml

Project dependencies

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.hellokoding.mail</groupId>
    <artifactId>sendingmail-gmailsmtpserver-javamailapi</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <exec.mainClass>com.hellokoding.mail.Main</exec.mainClass>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.0</version>
        </dependency>
    </dependencies>
</project>

Sending Mail with Java Mail API and Gmail SMTP Server

SendingMailThroughGmailSMTPServer.java

package com.hellokoding.mail;


import com.sun.mail.smtp.SMTPTransport;
import com.sun.mail.util.BASE64EncoderStream;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SendingMailThroughGmailSMTPServer {
    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);
        }
    }
}

Run

Main.java

package com.hellokoding.mail;

public class Main {
    private static final String SMTP_SERVER_HOST = "smtp.gmail.com";
    private static final String SMTP_SERVER_PORT = "587";
    private static final String SUBJECT = "Sending mail with Gmail SMTP and Java Mail";
    private static final String BODY = "Hi,<br><br>This is a programmatic email.";

    public static void main(String[] args) {
        final String FROM_USER_EMAIL = args[0];
        final String FROM_USER_FULLNAME = args[1];
        final String FROM_USER_ACCESSTOKEN = args[2];
        final String TO_USER_EMAIL = args[3];

        new SendingMailThroughGmailSMTPServer().sendMail(SMTP_SERVER_HOST, SMTP_SERVER_PORT, FROM_USER_EMAIL, FROM_USER_ACCESSTOKEN, FROM_USER_EMAIL, FROM_USER_FULLNAME, TO_USER_EMAIL, SUBJECT, BODY);
    }
}

Replace below macros with your respective values and run the command

mvn clean package exec:java -Dexec.args="{FROM_USER_NAME} {FROM_USER_FULLNAME} {FROM_USER_ACCESSTOKEN} {TO_USER_EMAIL}"
Sending Email Example with Java Mail API and Gmail SMTP Server

Source code

https://github.com/hellokoding/hellokoding-courses/tree/master/java-examples/javamail-gmail

Follow HelloKoding