首页 > 解决方案 > 我应该如何使用 JavaMail 和 AWS 发送邮件

问题描述

大家好,我正在尝试使用 JavaMail 和 Amazon SES 发送电子邮件,这是我编写的代码,

static Properties props = new Properties();

static {
    props.setProperty("mail.transport.protocol", "aws");
    props.setProperty("mail.aws.user", "userName");
    props.setProperty("mail.aws.password", "secretKey");
}

void doThis() throws AddressException, MessagingException {
    Session session = Session.getDefaultInstance(props);

    Message mimeMessage = new MimeMessage(session);
    mimeMessage.setFrom(new InternetAddress("support@xyz.com"));
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse("kaustubh@xyz.com"));
    mimeMessage.setSubject("Subject");
    mimeMessage.setContent("Message contenet", "text/html");

    Transport t = new AWSJavaMailTransport(session, null);
    t.connect();
    t.sendMessage(mimeMessage, null);
    t.close();
}

但我得到一个例外说,

线程“主”javax.mail.SendFailedException 中的异常:无法发送电子邮件;嵌套异常是:com.amazonaws.services.simpleemail.model.MessageRejectedException:电子邮件地址未验证。以下身份未通过区域 US-EAST-1 中的检查

而且我没有得到任何解决方案,stackOverflow 家族的任何建议都会有很大帮助。

标签: jakarta-mailamazon-sesaws-java-sdk

解决方案


这是发送电子邮件的 V2 SES 代码...

public class SendMessage {

    // This value is set as an input parameter
    private static String SENDER = "";

    // This value is set as an input parameter
    private static String RECIPIENT = "";

    // This value is set as an input parameter
    private static String SUBJECT = "";


    // The email body for recipients with non-HTML email clients
    private static String BODY_TEXT = "Hello,\r\n" + "Here is a list of customers to contact.";

    // The HTML body of the email
    private static String BODY_HTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>"
            + "<p>Here is a list of customers to contact.</p>" + "</body>" + "</html>";

    public static void main(String[] args) throws IOException {

        if (args.length < 3) {
            System.out.println("Please specify a sender email address, a recipient email address, and a subject line");
            System.exit(1);
        }

        // snippet-start:[ses.java2.sendmessage.main]
        SENDER = args[0];
        RECIPIENT = args[1];
        SUBJECT = args[2];

        try {
            send();

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

    public static void send() throws AddressException, MessagingException, IOException {

        Session session = Session.getDefaultInstance(new Properties());

        // Create a new MimeMessage object
        MimeMessage message = new MimeMessage(session);

        // Add subject, from and to lines
        message.setSubject(SUBJECT, "UTF-8");
        message.setFrom(new InternetAddress(SENDER));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));

        // Create a multipart/alternative child container
        MimeMultipart msgBody = new MimeMultipart("alternative");

        // Create a wrapper for the HTML and text parts
        MimeBodyPart wrap = new MimeBodyPart();

        // Define the text part
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");

        // Define the HTML part
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(BODY_HTML, "text/html; charset=UTF-8");

        // Add the text and HTML parts to the child container
        msgBody.addBodyPart(textPart);
        msgBody.addBodyPart(htmlPart);

        // Add the child container to the wrapper object
        wrap.setContent(msgBody);

        // Create a multipart/mixed parent container
        MimeMultipart msg = new MimeMultipart("mixed");

        // Add the parent container to the message
        message.setContent(msg);

        // Add the multipart/alternative part to the message
        msg.addBodyPart(wrap);


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

            Region region = Region.US_WEST_2;

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

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            message.writeTo(outputStream);

            ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());

            byte[] arr = new byte[buf.remaining()];
            buf.get(arr);

            SdkBytes data = SdkBytes.fromByteArray(arr);

            RawMessage rawMessage = RawMessage.builder()
                    .data(data)
                    .build();

            SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
                    .rawMessage(rawMessage)
                    .build();

            client.sendRawEmail(rawEmailRequest);

        } catch (SdkException e) {
            e.getStackTrace();
        }
        // snippet-end:[ses.java2.sendmessage.main]
    }
}
// snippet-end:[ses.java2.sendmessage.complete]

推荐阅读