简体   繁体   English

无法使用Java中的Amazon SES发送电子邮件

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

I am using below mentioned code to send Email. 我正在使用下面提到的代码发送电子邮件。

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

I am getting below mentioned error. 我得到下面提到的错误。

com.amazonaws.AmazonServiceException: The request signature we calculated does not match the signature you provided. com.amazonaws.AmazonServiceException:我们计算出的请求签名与您提供的签名不匹配。 Check your AWS Secret Access Key and signing method. 检查您的AWS Secret Access Key和签名方法。 Consult the service documentation for details. 有关详细信息,请查阅服务文档。 The Canonical String for this request should have been 'POST / 此请求的规范字符串应为'POST /

host:email.us-east-1.amazonaws.com user-agent:aws-sdk-java/1.9.0 Linux/3.19.0-25-generic Java_HotSpot(TM)_64-Bit_Server_VM/25.66-b17/1.8.0_66 x-amz-date:20160223T062544Z 主机: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

host;user-agent;x-amz-date 4c1f25e3dcf887bd49756ddd01c5e923cf49f2affa73adfc7059d00140032edf' 主机;用户代理; x-amz日期4c1f25e3dcf887bd49756ddd01c5e923cf49f2affa73adfc7059d00140032edf'

(Service: AmazonSimpleEmailService; Status Code: 403; Error Code: SignatureDoesNotMatch; (服务:AmazonSimpleEmailService;状态代码:403;错误代码:SignatureDoesNotMatch;

The credentials you are providing is incorrect. 您提供的凭据不正确。 You are giving IAM username and password. 您要提供IAM用户名和密码。 Instead you have to provide the access_key_id and access_key_id . 相反,您必须提供access_key_idaccess_key_id

AWSCredentials credentials = new BasicAWSCredentials(access_key_id, secret_access_key)

See: Providing AWS Credentials in the AWS SDK for Java 请参阅: 在适用于Java的AWS开发工具包中提供AWS凭证

This is a Sample code to send Email using Amazon SES. 这是使用Amazon SES发送电子邮件的示例代码。 Initially when you create an Amazon SES account, the account will be in Sandbox mode which allows you to send only 200 emails. 最初,当您创建Amazon SES帐户时,该帐户将处于沙盒模式,该模式仅允许您发送200封电子邮件。 For Switching this to production mode, you need to "Request" for expanding email limit. 要将其切换到生产模式,您需要“请求”以扩展电子邮件限制。 Please go through the documentation. 请仔细阅读文档。

Pre requisites: You need to have Amazon SES account activated. 前提条件:您需要激活Amazon SES帐户。 verify email addressses (to and from) or domain if you are currently in Sandbox mode. 如果您当前处于沙盒模式,请验证电子邮件地址(去往和来自)或域。 Under "SMTP settings" in Navigation bar, you can generate your SMTP credentials. 在导航栏中的“ SMTP设置”下,您可以生成SMTP凭据。 This will include a smtp username and password. 这将包括smtp用户名和密码。 You can download a csv file containing this details as well. 您也可以下载包含此详细信息的csv文件。

生成SMTP凭证

sending email using Java : 使用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