@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); } }
@Test public void testSendMultipleMailsWithException() throws Exception { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService); MimeMessage failureMail = createMimeMessage(); when(emailService.sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class))). thenReturn(new SendRawEmailResult()). thenThrow(new AmazonClientException("error")). thenReturn(new SendRawEmailResult()); try { mailSender.send(createMimeMessage(), failureMail, createMimeMessage()); fail("Exception expected due to error while sending mail"); } catch (MailSendException e) { assertEquals(1, e.getFailedMessages().size()); assertTrue(e.getFailedMessages().containsKey(failureMail)); } }
private void sendMimeMessage(final MailMessageDTO mailMessage) { if (mailMessage.getTo().toLowerCase().endsWith("invalid")) { LOG.warn("Not sending mail to invalid email: '{}' with subject: '{}' and body:\n{}", mailMessage.getTo(), mailMessage.getSubject(), mailMessage.getBody()); return; } LOG.info("Attempting delivery using for outgoing email: {}", mailMessage); final MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties())); mailMessage.prepareMimeMessage(mimeMessage); this.amazonSimpleEmailService.sendRawEmail(new SendRawEmailRequest(createRawMessage(mimeMessage))); }
private SendRawEmailRequest createRawMailRequest(Exchange exchange) throws Exception { SendRawEmailRequest request = new SendRawEmailRequest(); request.setSource(determineFrom(exchange)); request.setDestinations(determineRawTo(exchange)); request.setRawMessage(createRawMessage(exchange)); return request; }
@Override public SendRawEmailResult sendRawEmail(SendRawEmailRequest sendRawEmailRequest) throws AmazonServiceException, AmazonClientException { this.sendRawEmailRequest = sendRawEmailRequest; SendRawEmailResult result = new SendRawEmailResult(); result.setMessageId("1"); return result; }
@Test public void testSendMimeMessage() throws MessagingException, IOException { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService); ArgumentCaptor<SendRawEmailRequest> request = ArgumentCaptor.forClass(SendRawEmailRequest.class); when(emailService.sendRawEmail(request.capture())).thenReturn(new SendRawEmailResult().withMessageId("123")); MimeMessage mimeMessage = createMimeMessage(); mailSender.send(mimeMessage); SendRawEmailRequest rawEmailRequest = request.getValue(); assertTrue(Arrays.equals(getMimeMessageAsByteArray(mimeMessage), rawEmailRequest.getRawMessage().getData().array())); }
@Test public void testSendMultipleMimeMessages() throws Exception { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService); when(emailService.sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class))).thenReturn(new SendRawEmailResult().withMessageId("123")); mailSender.send(createMimeMessage(), createMimeMessage()); verify(emailService, times(2)).sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class)); }
@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; }
public SendRawEmailRequest getSendRawEmailRequest() { return sendRawEmailRequest; }
private List<String> getTo(SendRawEmailRequest sendEmailRequest) { return sendEmailRequest.getDestinations(); }