use of software.amazon.awssdk.services.ses.model.SesException in project aws-doc-sdk-examples by awsdocs.
the class SendMessage method send.
// snippet-start:[ses.java2.sendmessage.main]
public static void send(SesClient client, String sender, String recipient, String subject, String bodyText, String bodyHTML) throws AddressException, MessagingException, IOException {
Session session = Session.getDefaultInstance(new Properties());
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(bodyText, "text/plain; charset=UTF-8");
// Define the HTML part
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(bodyHTML, "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...");
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 (SesException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
// snippet-end:[ses.java2.sendmessage.main]
}
Aggregations