Send email using Amazon SES SMTP in Java

When a member forgets his login password, he wants 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. Implemented the function.

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

I felt that AWS settings were more troublesome than programming.

1. Environment

VS Code Java Extension Pack Spring Boot Extension Pack

2. Acquisition of SMTP authentication information

Log in to the AWS console and perform steps 1-6 of "Getting Amazon SES SMTP Credentials Using the Amazon SES Console" to get your SMTP user name and SMTP password, as described in the URL below. ..

Once obtained, 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

In the VS Code command palette, select "Spring Initializr: Generate a Gradle Project"-> "Java"-> "Any GroupId"-> "Any ArtifactId"-> "Any version"-> "Dependenceies are blank" and select Gradle Project. Create. (It doesn't have to be Spring Boot ...)

4. Add dependencies

Add a dependency to your build.gradle file to get the javax.mail.jar needed to send 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' //← Add ★
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

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

5. Implementation

Use the code from the AWS site almost as it 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 = "Sender email address";
    static final String FROMNAME = "Source name";
	
    // 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 unnecessary ★
    
    // Amazon SES SMTP host name.This example uses the western United States(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 unnecessary ★
            
        // 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);
        	
            // 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 with AWS as a sender

Log in to the AWS console and perform steps 1-7 of "Verify your email address using the Amazon SES console" as described in the URL below 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 an email.

As with the sender, the recipient's email address must be verified in advance to see if it can be sent as the recipient, and it must be OK.

The situation is "in the sandbox".

You need to "go out of the sandbox" to freely choose the destination and send the email.

As described in the URL below, log in to the AWS console, perform steps 1 to 9 of "Going 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

With permission, pre-verification of the destination is not required.

8. Run

From the VS Code terminal, implement the following command to create a jar file.

.\gradlew build

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

that's all.

Recommended Posts

Send email using Amazon SES SMTP in Java
[Java] Send an email using Amazon SES
I want to send an email in Java.
Send push notifications using Notification Hubs in Java
Try using RocksDB in Java
Implement Email Sending in Java
I sent an email in Java
HTTPS connection using tls1.2 in Java 6
I tried using JWT in Java
Try using the Stream API in Java
Using JavaScript from Java in Rhino 2021 version
ERRORCODE = -4471 occurs in Java application using Db2.
Try using JSON format API in Java
Read Felica using RC-S380 (PaSoRi) in Java
Send an email using JavaMail on AWS
ChatWork4j for using the ChatWork API in Java
[Java] API creation using Jerjey (Jax-rs) in eclipse
Try using Sourcetrail (win version) in Java code
Try using GCP's Cloud Vision API in Java
Try using Sourcetrail (macOS version) in Java code
Match IP addresses using regular expressions in Java
Display "Hello World" in the browser using Java
Display "Hello World" in the browser using Java
Try using the COTOHA API parsing in Java
NLP4J [001b] Morphological analysis in Java (using kuromoji)
Changes in Java 11
Rock-paper-scissors in Java
Pi in Java
FizzBuzz in Java
Convert JSON and YAML in Java (using Jackson and SnakeYAML)
Write ABNF in Java and pass the email address
Call Amazon Product Advertising API 5.0 (PA-API v5) in Java
I tried using Google Cloud Vision API in Java
How to convert A to a and a to A using AND and OR in Java
I tried using an extended for statement in Java
Try global hooking in Java using the JNativeHook library
Differences in code when using the length system in Java