Example of sending an email with attachment via Amazon in Java
Maybe a little bit late too. Alternative to send mail using Java Mail and Amazon Raw Mail Sender
public static void sendMail(String subject, String message, byte[] attachement, String fileName, String contentType, String from, String[] to) {
try {
// JavaMail representation of the message
Session s = Session.getInstance(new Properties(), null);
MimeMessage mimeMessage = new MimeMessage(s);
// Sender and recipient
mimeMessage.setFrom(new InternetAddress(from));
for (String toMail : to) {
mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toMail));
}
// Subject
mimeMessage.setSubject(subject);
// Add a MIME part to the message
MimeMultipart mimeBodyPart = new MimeMultipart();
BodyPart part = new MimeBodyPart();
part.setContent(message, MediaType.TEXT_HTML);
mimeBodyPart.addBodyPart(part);
// Add a attachement to the message
part = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(attachement, contentType);
part.setDataHandler(new DataHandler(source));
part.setFileName(fileName);
mimeBodyPart.addBodyPart(part);
mimeMessage.setContent(mimeBodyPart);
// Create Raw message
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
mimeMessage.writeTo(outputStream);
RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
// Credentials
String keyID = "";// <your key id>
String secretKey = "";// <your secret key>
AWSCredentials credentials = new BasicAWSCredentials(keyID, secretKey);
AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(credentials);
// Send Mail
SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
rawEmailRequest.setDestinations(Arrays.asList(to));
rawEmailRequest.setSource(from);
client.sendRawEmail(rawEmailRequest);
} catch (IOException | MessagingException e) {
// your Exception
e.printStackTrace();
}
}
Maybe a little bit late, but you can use this code (you also need Java Mail):
public class MailSender
{
private Transport AWSTransport;
...
//Initialize transport
private void initAWSTransport() throws MessagingException
{
String keyID = <your key id>
String secretKey = <your secret key>
MailAWSCredentials credentials = new MailAWSCredentials();
credentials.setCredentials(keyID, secretKey);
AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials);
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
props.setProperty("mail.aws.password", credentials.getAWSSecretKey());
AWSsession = Session.getInstance(props);
AWStransport = new AWSJavaMailTransport(AWSsession, null);
AWStransport.connect();
}
public void sendEmail(byte[] attachment)
{
//mail properties
String senderAddress = <Sender address>;
String recipientAddress = <Recipient address>;
String subject = <Mail subject>;
String text = <Your text>;
String mimeTypeOfText = <MIME type of text part>;
String fileMimeType = <MIME type of your attachment>;
String fileName = <Name of attached file>;
initAWSTransport();
try
{
// Create new message
Message msg = new MimeMessage(AWSsession);
msg.setFrom(new InternetAddress(senderAddress));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientAddress));
msg.setSubject(subject);
//Text part
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(text, mimeTypeOfText);
multipart.addBodyPart(messageBodyPart);
//Attachment part
if (attachment != null && attachment.length != 0)
{
messageBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(attachment,fileMimeType);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
}
msg.setContent(multipart);
//send message
msg.saveChanges();
AWSTransport.sendMessage(msg, null);
} catch (MessagingException e){...}
}
}
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html has an example that sends both html and text bodies (with an attachment, of course). FWIW, here is the conversion and reorganization of its Java code to Kotlin. The dependency is 'com.sun.mail:javax.mail:1.6.2'
.
data class Attachment(val fileName: String, val contentType: String, val data: ByteArray)
fun sendEmailWithAttachment(from: String, to: List<String>, subject: String, htmlBody: String, textBody: String,
attachment: Attachment) {
try {
val textPart = MimeBodyPart().apply {
setContent(textBody, "text/plain; charset=UTF-8")
}
val htmlPart = MimeBodyPart().apply {
setContent(htmlBody, "text/html; charset=UTF-8")
}
// Create a multipart/alternative child container.
val childPart = MimeMultipart("alternative").apply {
// Add the text and HTML parts to the child container.
addBodyPart(textPart)
addBodyPart(htmlPart)
}
// Create a wrapper for the HTML and text parts.
val childWrapper = MimeBodyPart().apply {
setContent(childPart)
}
// Define the attachment
val dataSource = ByteArrayDataSource(attachment.data, attachment.contentType)
// val dataSource = FileDataSource(filePath) // if using file directly
val attPart = MimeBodyPart().apply {
dataHandler = DataHandler(dataSource)
fileName = attachment.fileName
}
// Create a multipart/mixed parent container.
val parentPart = MimeMultipart("mixed").apply {
// Add the multipart/alternative part to the message.
addBodyPart(childWrapper)
addBodyPart(attPart) // Add the attachment to the message.
}
// JavaMail representation of the message
val s = Session.getDefaultInstance(Properties())
val mimeMessage = MimeMessage(s).apply {
// Add subject, from and to lines
this.subject = subject
setFrom(InternetAddress(from))
to.forEach() {
addRecipient(javax.mail.Message.RecipientType.TO, InternetAddress(it))
}
// Add the parent container to the message.
setContent(parentPart)
}
// Create Raw message
val rawMessage = with(ByteArrayOutputStream()) {
mimeMessage.writeTo(this)
RawMessage(ByteBuffer.wrap(this.toByteArray()))
}
val rawEmailRequest = SendRawEmailRequest(rawMessage).apply {
source = from
setDestinations(to)
}
// Send Mail
val client = AmazonSimpleEmailServiceClientBuilder.standard()
.withRegion(Regions.US_EAST_1).build()
client.sendRawEmail(rawEmailRequest)
println("Email with attachment sent to $to")
} catch (e: Exception) {
println(e)
}
}