如何使用 AWS SDK 发送带有发件人姓名的电子邮件?

How to send email with sender name using AWS SDK?

我目前正在使用 AWS SDK 发送邮件:

  // from: noreply@domain.com
  public void sendMail(String from, String to, String subject, String htmlBody) {
    LOGGER.info(String.format("Sending Mail from: %s, to: %s, with subject: %s", from, to, subject));
    try {
      AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecret);
      AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard()
              .withRegion(Regions.AP_SOUTH_1).withCredentials(new AWSStaticCredentialsProvider(credentials))
              .build();

      SendEmailRequest request = new SendEmailRequest().withDestination(new Destination().withToAddresses(to))
              .withMessage(new Message()
                      .withBody(new Body().withHtml(new Content().withCharset("UTF-8").withData(htmlBody)))
                      .withSubject(new Content().withCharset("UTF-8").withData(subject)))
              .withSource(from);

      client.sendEmail(request);
    } catch (Exception e) {
      LOGGER.error(String.format("Error while sending email: %s", e.getMessage()));
      throw new IllegalArgumentException(MessageEnum.FAILED_TO_SEND_AN_EMAIL.name());
    }
  }

该方法工作正常,但电子邮件发送为:

但我希望发送的电子邮件带有发件人姓名,以便显示如下:

有没有人知道如何发送包含发件人姓名的电子邮件?感谢任何帮助。

如果您查看 SendEmailRequest 的文档,您会发现它支持在电子邮件中定义友好名称的标准方式:

source - The email address that is sending the email. This email address must be either individually verified with Amazon SES, or from a domain that has been verified with Amazon SES. For information about verifying identities, see the Amazon SES Developer Guide. If you are sending on behalf of another user and have been permitted to do so by a sending authorization policy, then you must also specify the SourceArn parameter. For more information about sending authorization, see the Amazon SES Developer Guide. Amazon SES does not support the SMTPUTF8 extension, as described in RFC6531. For this reason, the local part of a source email address (the part of the email address that precedes the @ sign) may only contain 7-bit ASCII characters. If the domain part of an address (the part after the @ sign) contains non-ASCII characters, they must be encoded using Punycode, as described in RFC3492. The sender name (also known as the friendly name) may contain non-ASCII characters. These characters must be encoded using MIME encoded-word syntax, as described in RFC 2047. MIME encoded-word syntax uses the following form: =?charset?encoding?encoded-text?= .

因此该字符串应如下所示: John Doe <johndoe@example.com>

InternetAddress可用于此,但您需要注意SendEmailRequestfrom参数

的编码限制
request.withSource((new InternetAddress("mail@example.com", "Your Name")).toString());

您使用的是旧版 Amazon Simple Email Service API (V1)。为获得最佳实践,请使用 SES Java V2 API。 V2 包总是以 software.amazon...

开头

Amazon SDK 团队强烈建议从 V1 迁移到 V2:

适用于 Java 2.x 的 AWS SDK 是对版本 1.x 代码库的重大重写。它建立在 Java 8+ 之上,并添加了几个经常请求的功能。其中包括对非阻塞 I/O 的支持以及在 运行 时间插入不同 HTTP 实现的能力。

您可以通过正确设置 SendEmailRequest 对象来设置此信息(发件人姓名)。

这里是 Java V2 SES example.

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.services.ses.model.*;
import software.amazon.awssdk.services.ses.model.Message;
import software.amazon.awssdk.services.ses.model.Body;
import javax.mail.MessagingException;

public class SendMessageEmailRequest {

    public static void main(String[] args) {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    <sender> <recipient> <subject> \n\n" +
                "Where:\n" +
                "    sender - an email address that represents the sender. \n"+
                "    recipient -  an email address that represents the recipient. \n"+
                "    subject - the  subject line. \n" ;

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

        String sender = "foo@testmail.com" ;//args[0];
        String recipient = "foo@testmail.com" ;//args[1];
        String subject = "Test Email"; //args[2];

        Region region = Region.US_EAST_1;
        SesClient client = SesClient.builder()
                .region(region)
                .build();

        // The email body for non-HTML email clients
        String bodyText = "Hello,\r\n" + "See the list of customers. ";

        // The HTML body of the email
        String bodyHTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>"
                + "<p> See the list of customers.</p>" + "</body>" + "</html>";

        try {
            send(client, sender, recipient, subject, bodyText, bodyHTML);
            client.close();
            System.out.println("Done");

        } catch (MessagingException e) {
            e.getStackTrace();
        }
    }

    public static void send(SesClient client,
                            String sender,
                            String recipient,
                            String subject,
                            String bodyText,
                            String bodyHTML
    ) throws MessagingException {

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

        Content content = Content.builder()
                .data(bodyHTML)
                .build();

        Content sub = Content.builder()
                .data(subject)
                .build();

        Body body = Body.builder()
                .html(content)
                .build();

        Message msg = Message.builder()
                .subject(sub)
                .body(body)
                .build();

        SendEmailRequest emailRequest = SendEmailRequest.builder()
                .destination(destination)
                .message(msg)
                .source(sender)
                .build();

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

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