簡體   English   中英

無法使用Java中的Amazon SES發送電子郵件

[英]Not able to send Email using Amazon SES in Java

我正在使用下面提到的代碼發送電子郵件。

public static void send(String email, String subject, String body) {
    try {
        fromEmail = "abc.@xyz.com";
        Content subjectContent = new Content(subject);

        Destination destination = new Destination().withToAddresses(new String[] { "cde@gmail.com" });

        Content htmlContent = new Content().withData("<h1>Hello - I hope you're having a good day.</h1>");
        Body msgBody = new Body().withHtml(htmlContent);

        // Create a message with the specified subject and body.
        Message message = new Message().withSubject(subjectContent).withBody(msgBody);

        SendEmailRequest request = new SendEmailRequest()
                                           .withSource(fromEmail)
                                           .withDestination(destination)
                                           .withMessage(message);

        SendRawEmailRequest sendRawEmailRequest = new SendRawEmailRequest()
                                                          .withSource(fromEmail)
                                                          .withDestinations(destination.getBccAddresses())
                                                          .withRawMessage(new RawMessage());
        AWSCredentials credentials = new BasicAWSCredentials(userName,password);

        AmazonSimpleEmailServiceClient sesClient = new AmazonSimpleEmailServiceClient(credentials);
        // ListVerifiedEmailAddressesResult verifiedEmails =
        // sesClient.listVerifiedEmailAddresses();
        SendRawEmailResult result = sesClient.sendRawEmail(sendRawEmailRequest);
        System.out.println(result + "Email sent");
    } catch (Exception e) {
        logger.error("Caught a MessagingException, which means that there was a "
                + "problem sending your message to Amazon's E-mail Service check the "
                + "stack trace for more information.{}" + e.getMessage());
        e.printStackTrace();
    }
}

我得到下面提到的錯誤。

com.amazonaws.AmazonServiceException:我們計算出的請求簽名與您提供的簽名不匹配。 檢查您的AWS Secret Access Key和簽名方法。 有關詳細信息,請查閱服務文檔。 此請求的規范字符串應為'POST /

主機:email.us-east-1.amazonaws.com用戶代理:aws-sdk-java / 1.9.0 Linux / 3.19.0-25-通用Java_HotSpot(TM)_64-Bit_Server_VM / 25.66-b17 / 1.8.0_66 X-AMZ-日期:20160223T062544Z

主機;用戶代理; x-amz日期4c1f25e3dcf887bd49756ddd01c5e923cf49f2affa73adfc7059d00140032edf'

(服務:AmazonSimpleEmailService;狀態代碼:403;錯誤代碼:SignatureDoesNotMatch;

您提供的憑據不正確。 您要提供IAM用戶名和密碼。 相反,您必須提供access_key_idaccess_key_id

AWSCredentials credentials = new BasicAWSCredentials(access_key_id, secret_access_key)

請參閱: 在適用於Java的AWS開發工具包中提供AWS憑證

這是使用Amazon SES發送電子郵件的示例代碼。 最初,當您創建Amazon SES帳戶時,該帳戶將處於沙盒模式,該模式僅允許您發送200封電子郵件。 要將其切換到生產模式,您需要“請求”以擴展電子郵件限制。 請仔細閱讀文檔。

前提條件:您需要激活Amazon SES帳戶。 如果您當前處於沙盒模式,請驗證電子郵件地址(去往和來自)或域。 在導航欄中的“ SMTP設置”下,您可以生成SMTP憑據。 這將包括smtp用戶名和密碼。 您也可以下載包含此詳細信息的csv文件。

生成SMTP憑證

使用Java發送電子郵件:

public class AmazonSESExample {


static final String FROM = "your from email address";
static final String FROMNAME = "From name";

// Replace recipient@example.com with a "To" address. If your account
// is still in the sandbox, this address must be verified.
static final String TO = "receiver email address";

// Replace smtp_username with your Amazon SES SMTP user name.
static final String SMTP_USERNAME = "username generated under smtp settings";

// Replace smtp_password with your Amazon SES SMTP password.
static final String SMTP_PASSWORD = "password generated under smtp settings";

// 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 = "email-smtp.us-east-1.amazonaws.com";

// The port you will connect to on the Amazon SES SMTP endpoint.
static final int PORT = 25;

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 static void main(String[] args) 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");


    // 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();
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM