Created
February 24, 2014 14:05
-
-
Save christianoguedes/9188999 to your computer and use it in GitHub Desktop.
Send Mail (Amazon SimpleMail) with Attachement
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment