@SuppressWarnings("OverloadedVarargsMethod") @Override public void send(MimeMessage... mimeMessages) throws MailException { Map<Object, Exception> failedMessages = new HashMap<>(); for (MimeMessage mimeMessage : mimeMessages) { try { RawMessage rm = createRawMessage(mimeMessage); SendRawEmailResult sendRawEmailResult = getEmailService().sendRawEmail(new SendRawEmailRequest(rm)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Message with id: {} successfully send", sendRawEmailResult.getMessageId()); } } catch (Exception e) { //Ignore Exception because we are collecting and throwing all if any //noinspection ThrowableResultOfMethodCallIgnored failedMessages.put(mimeMessage, e); } } if (!failedMessages.isEmpty()) { throw new MailSendException(failedMessages); } }
@Override public Parameters handleRequest(Parameters parameters, Context context) { context.getLogger().log("Input Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]"); try { // Create an empty Mime message and start populating it Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); message.setSubject(EMAIL_SUBJECT, "UTF-8"); message.setFrom(new InternetAddress(System.getenv("EMAIL_FROM"))); message.setReplyTo(new Address[] { new InternetAddress(System.getenv("EMAIL_FROM")) }); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(System.getenv("EMAIL_RECIPIENT"))); MimeBodyPart wrap = new MimeBodyPart(); 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); // Create an S3 URL reference to the snapshot that will be attached to this email URL attachmentURL = createSignedURL(parameters.getS3Bucket(), parameters.getS3Key()); StringBuilder sb = new StringBuilder(); String id = UUID.randomUUID().toString(); sb.append("<img src=\"cid:"); sb.append(id); sb.append("\" alt=\"ATTACHMENT\"/>\n"); // Add the attachment as a part of the message body MimeBodyPart attachment = new MimeBodyPart(); DataSource fds = new URLDataSource(attachmentURL); attachment.setDataHandler(new DataHandler(fds)); attachment.setContentID("<" + id + ">"); attachment.setDisposition(BodyPart.ATTACHMENT); attachment.setFileName(fds.getName()); content.addBodyPart(attachment); // Pretty print the Rekognition Labels as part of the Emails HTML content String prettyPrintLabels = parameters.getRekognitionLabels().toString(); prettyPrintLabels = prettyPrintLabels.replace("{", "").replace("}", ""); prettyPrintLabels = prettyPrintLabels.replace(",", "<br>"); html.setContent("<html><body><h2>Uploaded Filename : " + parameters.getS3Key().replace("upload/", "") + "</h2><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>"+sb+"</body></html>", "text/html"); // Convert the JavaMail message into a raw email request for sending via SES ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); // Send the email using the AWS SES Service AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient(); client.sendRawEmail(rawEmailRequest); } catch (MessagingException | IOException e) { // Convert Checked Exceptions to RuntimeExceptions to ensure that // they get picked up by the Step Function infrastructure throw new AmazonServiceException("Error in ["+context.getFunctionName()+"]", e); } context.getLogger().log("Output Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]"); return parameters; }
/** * Method to send a text email with attachments or HTML emails with * attachments (inline or not). * @param m email message to be sent. * @return id of message that has been sent. * @throws MailNotSentException if mail couldn't be sent. */ private String sendRawEmail(EmailMessage<MimeMessage> m) throws MailNotSentException { String messageId; long currentTimestamp = System.currentTimeMillis(); prepareClient(); if (!mEnabled) { //don't send message if not enabled return null; } try { synchronized (this) { //prevents throttling and excessive memory usage checkQuota(currentTimestamp); //if no subject, set to empty string to avoid errors if (m.getSubject() == null) { m.setSubject(""); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); //convert message into mime multi part and write it to output //stream into memory Session session = Session.getInstance(new Properties()); MimeMessage mimeMessage = new MimeMessage(session); if (m.getSubject() != null) { mimeMessage.setSubject(m.getSubject(), "utf-8"); } m.buildContent(mimeMessage); mimeMessage.writeTo(outputStream); //m.buildMultipart().writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap( outputStream.toByteArray())); SendRawEmailRequest rawRequest = new SendRawEmailRequest( rawMessage); rawRequest.setDestinations(m.getTo()); rawRequest.setSource(mMailFromAddress); SendRawEmailResult result = mClient.sendRawEmail(rawRequest); messageId = result.getMessageId(); //update timestamp of last sent email mLastSentMailTimestamp = System.currentTimeMillis(); //wait to avoid throwttling exceptions to avoid making any //further requests this.wait(mWaitIntervalMillis); } } catch (Throwable t) { throw new MailNotSentException(t); } return messageId; }