After_Sunset
After_Sunset

Reputation: 714

How do you send an email using a template with AWS SES Java SDK sesv2

I'm trying to send an email using a template with the AWS Java SDK v2 2.17.235. I have created the template and read at least 2 dozen pages of documentation at this point. 6 hours in I have not been able to find a single example or a shred of anything helpful in regards to this check the documentation several times read every article.

I can send other emails just fine but I want to use templating moving forward. Again, I've created the template, I can get the template, etc. None of that is helpful, I need to use a template that I've created to send an email. Here's what my code looks like

        try (
            SesV2Client client = SesV2Client.builder()
                    .region(Region.US_EAST_1)
                    .build()) {
        

        Template template = Template.builder().templateName("SiteUpdateTemplate").templateData(TEMPLATE_DATA).build();

        EmailContent emailContent = EmailContent.builder().template(Template.builder().templateName("SiteUpdateTemplate").templateData(TEMPLATE_DATA).build()).build();
        GetEmailTemplateRequest getEmailTemplateRequest = GetEmailTemplateRequest.builder().templateName("SiteUpdateTemplate").build();
        GetEmailTemplateResponse getEmailTemplateResponse = client.getEmailTemplate(getEmailTemplateRequest);


        SendEmailRequest request = SendEmailRequest.builder()
                .configurationSetName(CONFIGSET)
                .fromEmailAddress(FROM)
                .listManagementOptions(ListManagementOptions.builder().contactListName(CONTACT_LIST).topicName(TOPIC_SITE_UPDATES).build())
                .fromEmailAddressIdentityArn(IDENTITYARN)
                .feedbackForwardingEmailAddress(FROM)
                .feedbackForwardingEmailAddressIdentityArn(IDENTITYARN)
                .destination(Destination.builder().toAddresses("[email protected]").build())
//

                .content(emailContent)

Is anyone able to give me an example or point to somewhere that has the information I need?

EDIT

To me it seems like the only way this would work is if I could somehow get the ARN of the template only theres no way to get the ARN of the template that I'm aware of. enter image description here

EDIT 2

I need to be more specific so I'm adding some additional details. I think that I may have jumped ahead to an incorrect conclusion based on what I was seeing. When I send the email using the template I

I honestly don't even know what to do at this point. No failures, the emails are never received and my sent emails go up by the amount I send in the AWS console. I have not received a single one of these 57 emails enter image description here

Upvotes: 0

Views: 4488

Answers (1)

smac2020
smac2020

Reputation: 10704

Here is your solution. First create a template by following this topic in the SES DEV Guide:

Create an email template

I followed that and created a template as shown here:

enter image description here

Here is your Java V2 code that uses this template to send an email. Notice that you only have to reference the template name when you create a Template object.

UPDATE

WHen sending an email with a template - you must specify all variables you use in the template. The example template you create in the SES DEV Guide uses 2 variables:

{
  "Template": {
    "TemplateName": "MyTemplate",
    "SubjectPart": "Greetings, {{name}}!",
    "HtmlPart": "<h1>Hello {{name}},</h1><p>Your favorite animal is {{favoriteanimal}}.</p>",
    "TextPart": "Dear {{name}},\r\nYour favorite animal is {{favoriteanimal}}."
  }
}

This means you need to specify both name and favoriteanimal in your code when defining the Template object. If you DO NOT specify all variables in the template - SES does not send the email, as discussed here.

https://aws.amazon.com/premiumsupport/knowledge-center/ses-resolve-emails-not-delivered/

Java Code:

package com.example.sesv2;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sesv2.model.Destination;
import software.amazon.awssdk.services.sesv2.model.EmailContent;
import software.amazon.awssdk.services.sesv2.model.SendEmailRequest;
import software.amazon.awssdk.services.sesv2.model.SesV2Exception;
import software.amazon.awssdk.services.sesv2.SesV2Client;
import software.amazon.awssdk.services.sesv2.model.Template;


/**
 * Before running this AWS SDK for Java (v2) example, set up your development environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class SendEmailTemplate {

        public static void main(String[] args) {

                final String usage = "\n" +
                        "Usage:\n" +
                        "    <sender> <recipient> <subject> \n\n" +
                        "Where:\n" +
                        "    template - the name of the email template" +
                        "    sender - An email address that represents the sender. \n"+
                        "    recipient - An email address that represents the recipient. \n" ;

                if (args.length != 3) {
                        System.out.println(usage);
                        System.exit(1);
                }

                String templateName = "MyTemplate";
                String sender = "<Enter sender>" ; //args[0];
                String recipient =  "<Enter recipient>" ; // ; args[1];
                Region region = Region.US_EAST_1;
                SesV2Client sesv2Client = SesV2Client.builder()
                        .region(region)
                        .credentialsProvider(ProfileCredentialsProvider.create())
                        .build();

                send(sesv2Client, sender, recipient, templateName);
        }

        // snippet-start:[ses.java2.sendmessage.sesv2.main]
        public static void send(SesV2Client client,
                                String sender,
                                String recipient,
                                String templateName

        ){

                Destination destination = Destination.builder()
                        .toAddresses(recipient)
                        .build();

                 Template myTemplate = Template.builder()
                    .templateName(templateName)
                    .templateData("{\n" +
                            "  \"name\": \"Jason\"\n," +
                            "  \"favoriteanimal\": \"Cat\"\n" +
                            "}")
                    .build();

                EmailContent emailContent = EmailContent.builder()
                        .template(myTemplate)
                         .build();

                SendEmailRequest emailRequest = SendEmailRequest.builder()
                        .destination(destination)
                          .content(emailContent)
                        .fromEmailAddress(sender)
                        .build();

                try {
                        System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
                        client.sendEmail(emailRequest);
                        System.out.println("email based on a template was sent");

                } catch (SesV2Exception e) {
                        System.err.println(e.awsErrorDetails().errorMessage());
                        System.exit(1);
                }
        }
    }

After i ran this code -- I got my email based on the template:

enter image description here

Upvotes: 3

Related Questions