Amazon SES 403 ошибка
Я пытаюсь использовать Amazon SES для отправки электронной почты на мой корпоративный аккаунт. Я скопировал ключи доступа aws в файл ~/.aws/credentials. Кажется, я постоянно получаю ошибку:
Сообщение об ошибке: рассчитанная нами подпись запроса не соответствует предоставленной вами подписи. Проверьте свой секретный ключ доступа AWS и метод подписи. Обратитесь к сервисной документации для деталей.
Каноническая строка для этого запроса должна была быть "POST /
amz-sdk-invocation-id: 638ed10a-22cd-12f5-c9a5-25a672a6c38d amz-sdk-retry: 3/136/485 хост:email.us-east-1.amazonaws.com пользовательский агент: aws-sdk-java /1.11.172 Mac_OS_X / 10.11.5 Java_HotSpot(TM) _64-Bit_Server_VM / 25.60-b23 / 1.8.0_60 x-amz-date: 20170808T040309Z
amz-sdk-invocation-id; amz-sdk-retry; хост; пользовательский агент;x-amz-date 1c21e3af09924eec311e370c8e6710c0bc3fa2027fe213db11f02b22d79b6c91'
Строка для подписи должна была быть 'AWS4-HMAC-SHA256 20170808T040309Z 20170808/us-east-1/ses/aws4_request 82a2179c0dda36b0a4f80c111a8119cc8a65d768a0ff65de4e: код ошибки: -11e7-a445-27be327c79a0) com.amazonaws.services.simpleemail.model.AmazonSimpleEmailServiceException: рассчитанная нами подпись запроса не соответствует предоставленной вами подписи. Проверьте свой секретный ключ доступа AWS и метод подписи. Обратитесь к сервисной документации для деталей.
Каноническая строка для этого запроса должна была быть "POST /
amz-sdk-invocation-id: 638ed10a-22cd-12f5-c9a5-25a672a6c38d amz-sdk-retry: 3/136/485 хост:email.us-east-1.amazonaws.com пользовательский агент: aws-sdk-java /1.11.172 Mac_OS_X / 10.11.5 Java_HotSpot(TM) _64-Bit_Server_VM / 25.60-b23 / 1.8.0_60 x-amz-date: 20170808T040309Z
amz-sdk-invocation-id; amz-sdk-retry; хост; пользовательский агент;x-amz-date 1c21e3af09924eec311e370c8e6710c0bc3fa2027fe213db11f02b22d79b6c91'
Строка для подписи должна была быть 'AWS4-HMAC-SHA256 20170808T040309Z 20170808/us-east-1/ses/aws4_request 82a2179c0dda36b0a4f80c111a8119cc8a65d768a0ff65de4e: код ошибки: -11e7-a445-27be327c79a0) по адресу com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1587) по адресу com.amazonaws.http.AmazonHttpClient $ RequestExectt.ligent(hH)
Кодовая база:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.util.Properties;
import java.util.UUID;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient;
import com.amazonaws.services.simpleemail.model.RawMessage;
import com.amazonaws.services.simpleemail.model.SendRawEmailRequest;
public class SESClient {
private static String EMAIL_FROM = "@@@@@@@@@@";
private static String EMAIL_REPLY_TO = "@@@@@@@@@@";
private static String EMAIL_RECIPIENT = "@@@@@@@@@@";
// Remember to use two slashes in place of each slash.
private static Regions AWS_REGION = Regions.US_EAST_1;
private static String EMAIL_SUBJECT = "Amazon SES email test";
private static String EMAIL_BODY_TEXT = "This MIME email was sent through Amazon SES using SendRawEmail.";
public static void main(String[] args) throws AddressException, MessagingException, IOException {
Session session = Session.getDefaultInstance(new Properties());
MimeMessage message = new MimeMessage(session);
message.setSubject(EMAIL_SUBJECT, "UTF-8");
message.setFrom(new InternetAddress(EMAIL_FROM));
message.setReplyTo(new Address[]{new InternetAddress(EMAIL_REPLY_TO)});
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_RECIPIENT));
// Cover wrap
MimeBodyPart wrap = new MimeBodyPart();
// Alternative TEXT/HTML content
MimeMultipart cover = new MimeMultipart("alternative");
MimeBodyPart html = new MimeBodyPart();
cover.addBodyPart(html);
wrap.setContent(cover);
MimeMultipart content = new MimeMultipart("related");
message.setContent(content);
content.addBodyPart(wrap);
String[] attachmentsFiles = new String[]{
//EMAIL_ATTACHMENTS
};
StringBuilder sb = new StringBuilder();
for (String attachmentFileName : attachmentsFiles) {
String id = UUID.randomUUID().toString();
sb.append("<img src=\"cid:");
sb.append(id);
sb.append("\" alt=\"ATTACHMENT\"/>\n");
MimeBodyPart attachment = new MimeBodyPart();
DataSource fds = new FileDataSource(attachmentFileName);
attachment.setDataHandler(new DataHandler(fds));
attachment.setHeader("Content-ID", "<" + id + ">");
attachment.setFileName(fds.getName());
content.addBodyPart(attachment);
}
html.setContent("<html><body><h1>HTML</h1>\n" + EMAIL_BODY_TEXT + "</body></html>", "text/html");
try {
System.out.println("Attempting to send an email through Amazon SES by using the AWS SDK for Java...");
/*
* The ProfileCredentialsProvider will return your [default]
* credential profile by reading from the credentials file
* located at
* (~/.aws/credentials).
*
* TransferManager manages a pool of threads, so we create a
* single instance and share it throughout our application.
*/
AWSCredentials credentials = null;
try {
credentials = new ProfileCredentialsProvider().getCredentials();
} catch (Exception e) {
throw new AmazonClientException(
"Cannot load the credentials from the credential profiles file. " +
"Please make sure that your credentials file is at the correct " +
"location (~/.aws/credentials), and is in valid format.",
e);
}
AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials);
Region REGION = Region.getRegion(AWS_REGION);
client.setRegion(REGION);
// Print the raw email content on the console
PrintStream out = System.out;
message.writeTo(out);
// Send the email.
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
client.sendRawEmail(rawEmailRequest);
System.out.println("Email sent!");
} catch (Exception ex) {
System.out.println("Email Failed");
System.err.println("Error message: " + ex.getMessage());
ex.printStackTrace();
}
}
}