[Java] Sending an email using Amazon SES SMTP in Java

4 minute read

When the member forgets the login password, I wanted to send an email to the registered email address and press the link in it to reset the password, so send an email to the web application on AWS Implement the function.

The mail sending function is made into a jar file and made into a component.

I felt that setting AWS was troublesome than programming.

1. environment

VS Code Java Extension Pack Spring Boot Extension Pack

2. Acquisition of SMTP authentication information

As shown in the URL below, log in to the AWS console and perform steps 1 to 6 in “Using the Amazon SES Console to Obtain Amazon SES SMTP Credentials” to obtain the SMTP user name and SMTP password. ..

Once retrieved, the mail server name and port number will also be displayed.

https://docs.aws.amazon.com/ja_jp/ses/latest/DeveloperGuide/smtp-credentials.html

3. Create Gradle Project

Select “Spring Initializr: Generate a Gradle Project” -> “Java” -> “Arbitrary GroupId” -> “Arbitrary ArtifactId” -> “Arbitrary Version” -> “dependenceies is blank” in the VS Code command palette and select Gradle Project. Create (Although it doesn’t have to be Spring Boot separately…)

4. Add dependency

Add a dependency to the build.gradle file to get the javax.mail.jar needed to send the email using Amazon SES SMTP.

build.gradle


dependencies {
implementation'org.springframework.boot:spring-boot-starter-web'
compileOnly'com.sun.mail:javax.mail:1.6.2' //← Added ★
testImplementation('org.springframework.boot:spring-boot-starter-test') (
exclude group:'org.junit.vintage', module:'junit-vintage-engine'
}
}

//↓ Add this incidentally★
bootJar {
    enabled = false
}
jar {
    enabled = true
baseName ='aws-ses-send'
version =''
from configurations.compileClasspath.collect {it.isDirectory() ?it :zipTree(it)}
}

5.implementation

I use the code on the AWS site almost as is.

AmazonSES.java


package com.xxx.aws;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class AmazonSES {

    // Replace [email protected] with your "From" address.
    // This address must be verified.
    static final String FROM = "source email address";
    static final String FROMNAME = "source name";
It's a sequel.
    // Replace [email protected] with a "To" address. If your account
    // is still in the sandbox, this address must be verified.
    // static final String TO = "[email protected]";
    
    // Replace smtp_username with your Amazon SES SMTP user name.
    static final String SMTP_USERNAME = "SMTP user name";
    
    // Replace smtp_password with your Amazon SES SMTP password.
    static final String SMTP_PASSWORD = "SMTP password";
    
    // The name of the Configuration Set to use for this message.
    // If you comment out or remove this variable, you will also need to
    // comment out or remove the header below.
    // static final String CONFIGSET = "ConfigSet"; // ←Comment out if not needed★
    
    // Amazon SES SMTP host name.This example uses the US West (Oregon) region.
    // See https://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html#region-endpoints
    // for more information.
    static final String HOST = "mail server name";
    
    // The port you will connect to on the Amazon SES SMTP endpoint.
    static final int PORT = port number;
    
    // static final String SUBJECT = "Amazon SES test (SMTP interface accessed using Java)";
    
    // static final String BODY = String.join(
    // System.getProperty("line.separator"),
    // "<h1>Amazon SES SMTP Email Test</h1>",
    // "<p>This email was sent with Amazon SES using the ",
    // "<a href='https://github.com/javaee/javamail'>Javamail Package</a>",
    // "for <a href='https://www.java.com'>Java</a>."
    // );

public void send(String to,
String subject,
String body) throws Exception (

        // Create a Properties object to contain connection configuration information.
    Properties props = System.getProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.port", PORT);
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.auth", "true");

        // Create a Session object to represent a mail session with the specified properties.
    Session session = Session.getDefaultInstance(props);

        // Create a message with the specified information.
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(FROM,FROMNAME));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        msg.setSubject(subject);
        msg.setContent(body,"text/html");
        
        // Add a configuration set header. Comment or delete the
        // next line if you are not using a configuration set
        // msg.setHeader("X-SES-CONFIGURATION-SET", CONFIGSET); //← Comment out if not needed★
            
        // Create a transport.
        Transport transport = session.getTransport();
                    
        // Send the message.
        try
        {
            System.out.println("Sending...");
            
            // Connect to Amazon SES using the SMTP username and password you specified above.
            transport.connect(HOST, SMTP_USERNAME, SMTP_PASSWORD);
        It's a sequel.
            // Send the email.
            transport.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Email sent!");
        }catch (Exception ex) {
            System.out.println("The email was not sent.");
            System.out.println("Error message: "+ ex.getMessage());
        }
        finally
        {
            // Close and terminate the connection.
            transport.close();
        }
    }
}

https://docs.aws.amazon.com/ja_jp/ses/latest/DeveloperGuide/send-using-smtp-java.html

6. Register a valid email address as a sender in AWS

As shown in the URL below, log in to the AWS console and perform steps 1 to 7 of “Verify your email address using the Amazon SES console” to register a valid email address as the sender. ..

Only the email address after this procedure can be used as the sender email address.

https://docs.aws.amazon.com/ja_jp/ses/latest/DeveloperGuide/verify-email-addresses-procedure.html

7. Remove destination restrictions

In this state, you cannot freely select the destination and send the email.

As with the sender, the recipient’s email address must be verified beforehand to see if it can send email as a recipient, and it has become OK.

I’m in the sandbox.

You have to “go out of the sandbox” to choose the destination and send the email.

As shown in the URL below, log in to the AWS console, perform steps 1 to 9 of “Moving out of the Amazon SES sandbox”, and get permission from the support center.

https://docs.aws.amazon.com/ja_jp/ses/latest/DeveloperGuide/request-production-access.html

Prior approval of the destination is not required if permission is obtained.

8.run

Implement the following command from the VS Code terminal to create a jar file.

.\gradlew build

You can send the email by placing the created jar file in the calling project and calling the implemented send method.

that’s all.