com.amazonaws.services.simpleemail.model.SendRawEmailRequest Java Examples

The following examples show how to use com.amazonaws.services.simpleemail.model.SendRawEmailRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AWSEmailProvider.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Override
public boolean sendEmail(Collection<String> recipients, String from, MimeMessage mimeMessage) {
    try {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            mimeMessage.writeTo(outputStream);
            RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
            SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
            SendRawEmailResult result = ses.sendRawEmail(rawEmailRequest);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Email with messageId={} sent successfully.", result.getMessageId());
            }
            return result != null;
        }
    } catch (Exception ex) {
        LOGGER.error("The email could not be sent. Error message: {}", ex.getMessage());
        return false;
    }
}
 
Example #2
Source File: AWSEmailProviderTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendEmail() {
    Set<String> recipients = new HashSet<>(Arrays.asList("user.user1", "user.user2", "user.user3"));
    String subject = "test email subject";
    String body = "test email body";
    System.setProperty("athenz.notification_email_domain_from", "from.example.com");
    System.setProperty("athenz.notification_email_domain_to", "example.com");
    System.setProperty("athenz.notification_email_from", "no-reply-athenz");

    AmazonSimpleEmailService ses = mock(AmazonSimpleEmailService.class);
    SendRawEmailResult result = mock(SendRawEmailResult.class);
    Mockito.when(ses.sendRawEmail(any(SendRawEmailRequest.class))).thenReturn(result);
    AWSEmailProvider awsEmailProvider = new AWSEmailProvider(ses);

    ArgumentCaptor<SendRawEmailRequest> captor = ArgumentCaptor.forClass(SendRawEmailRequest.class);

    EmailNotificationService svc = new EmailNotificationService(awsEmailProvider);

    svc.sendEmail(recipients, subject, body);

    Mockito.verify(ses, atLeastOnce()).sendRawEmail(captor.capture());

    System.clearProperty("athenz.notification_email_domain_from");
    System.clearProperty("athenz.notification_email_domain_to");
    System.clearProperty("athenz.notification_email_from");
}
 
Example #3
Source File: AwsSmtpRelay.java    From aws-smtp-relay with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void deliver(String from, String to, InputStream inputStream) throws IOException {
    AmazonSimpleEmailService client;
    if (cmd.hasOption("r")) {
        client = AmazonSimpleEmailServiceClientBuilder.standard().withRegion(cmd.getOptionValue("r")).build();
    } else {
        client = AmazonSimpleEmailServiceClientBuilder.standard().build();
    }
    byte[] msg = IOUtils.toByteArray(inputStream);
    RawMessage rawMessage =
            new RawMessage(ByteBuffer.wrap(msg));
    SendRawEmailRequest rawEmailRequest =
            new SendRawEmailRequest(rawMessage).withSource(from)
                                               .withDestinations(to);
    if (cmd.hasOption("a")) {
        rawEmailRequest = rawEmailRequest.withSourceArn(cmd.getOptionValue("a"));
    }
    if (cmd.hasOption("f")) {
        rawEmailRequest = rawEmailRequest.withFromArn(cmd.getOptionValue("f"));
    }
    if (cmd.hasOption("t")) {
        rawEmailRequest = rawEmailRequest.withReturnPathArn(cmd.getOptionValue("t"));
    }
    if (cmd.hasOption("c")) {
        rawEmailRequest = rawEmailRequest.withConfigurationSetName(cmd.getOptionValue("c"));
    }
    try {
        client.sendRawEmail(rawEmailRequest);
    } catch (AmazonSimpleEmailServiceException e) {
        if(e.getErrorType() == ErrorType.Client) {
            // If it's a client error, return a permanent error
            throw new RejectException(e.getMessage());
        } else {
            throw new RejectException(451, e.getMessage());
        }
    }
}
 
Example #4
Source File: AWSEmailProviderTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendEmailBatch() {
    Set<String> recipients = new HashSet<>();
    for (int i =0; i<60; i++) {
        recipients.add("user.user" + i);
    }
    String subject = "test email subject";
    String body = "test email body";
    System.setProperty("athenz.notification_email_domain_from", "example.com");
    System.setProperty("athenz.notification_email_domain_to", "example.com");
    System.setProperty("athenz.notification_email_from", "no-reply-athenz");

    AmazonSimpleEmailService ses = mock(AmazonSimpleEmailService.class);

    SendRawEmailResult result = mock(SendRawEmailResult.class);
    Mockito.when(ses.sendRawEmail(any(SendRawEmailRequest.class))).thenReturn(result);
    ArgumentCaptor<SendRawEmailRequest> captor = ArgumentCaptor.forClass(SendRawEmailRequest.class);

    AWSEmailProvider emailProvider = new AWSEmailProvider(ses);
    EmailNotificationService svc = new EmailNotificationService(emailProvider);

    boolean emailResult = svc.sendEmail(recipients, subject, body);

    assertTrue(emailResult);
    Mockito.verify(ses, times(2)).sendRawEmail(captor.capture());

    System.clearProperty("athenz.notification_email_domain_from");
    System.clearProperty("athenz.notification_email_domain_to");
    System.clearProperty("athenz.notification_email_from");
}
 
Example #5
Source File: AWSEmailProviderTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendEmailBatchError() {
    Set<String> recipients = new HashSet<>();
    for (int i =0; i<60; i++) {
        recipients.add("user.user" + i);
    }
    String subject = "test email subject";
    String body = "test email body";
    System.setProperty("athenz.notification_email_domain_from", "example.com");
    System.setProperty("athenz.notification_email_domain_to", "example.com");
    System.setProperty("athenz.notification_email_from", "no-reply-athenz");

    AmazonSimpleEmailService ses = mock(AmazonSimpleEmailService.class);

    SendRawEmailResult result = mock(SendRawEmailResult.class);
    Mockito.when(ses.sendRawEmail(any(SendRawEmailRequest.class)))
            .thenReturn(null)
            .thenReturn(result);
    ArgumentCaptor<SendRawEmailRequest> captor = ArgumentCaptor.forClass(SendRawEmailRequest.class);

    AWSEmailProvider emailProvider = new AWSEmailProvider(ses);
    EmailNotificationService svc = new EmailNotificationService(emailProvider);

    boolean emailResult = svc.sendEmail(recipients, subject, body);

    // First mail will fail so emailResult should be false
    assertFalse(emailResult);

    // Even though it failed, the second email was sent
    Mockito.verify(ses, times(2)).sendRawEmail(captor.capture());

    System.clearProperty("athenz.notification_email_domain_from");
    System.clearProperty("athenz.notification_email_domain_to");
    System.clearProperty("athenz.notification_email_from");
}
 
Example #6
Source File: SimpleEmailServiceJavaMailSender.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@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());
			}
			mimeMessage.setHeader("Message-ID", 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);
	}
}
 
Example #7
Source File: SimpleEmailServiceJavaMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testSendMimeMessage() throws MessagingException {
	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);
	assertThat(mimeMessage.getMessageID()).isEqualTo("123");
}
 
Example #8
Source File: SimpleEmailServiceJavaMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
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));
}
 
Example #9
Source File: SesSendNotificationHandler.java    From smart-security-camera with GNU General Public License v3.0 4 votes vote down vote up
public Parameters handleRequest(Parameters parameters, Context context) {
	context.getLogger().log("Input Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	try {
		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);

		URL attachmentURL = new URL(
				System.getenv("S3_URL_PREFIX") + 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");

		MimeBodyPart attachment = new MimeBodyPart();
		DataSource fds = new URLDataSource(attachmentURL);
		attachment.setDataHandler(new DataHandler(fds));

		attachment.setContentID("<" + id + ">");
		attachment.setDisposition("attachment");

		attachment.setFileName(fds.getName());
		content.addBodyPart(attachment);

		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><i>Step Function ID : " + parameters.getStepFunctionID()
				+ "</i></p><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>" + sb
				+ "</body></html>", "text/html");

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		message.writeTo(outputStream);
		RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
		SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);

		AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient();
		client.sendRawEmail(rawEmailRequest);

	// Convert Checked Exceptions to RuntimeExceptions to ensure that
	// they get picked up by the Step Function infrastructure
	} catch (MessagingException | IOException e) {
		throw new RuntimeException("Error in [" + context.getFunctionName() + "]", e);
	}

	context.getLogger().log("Output Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	return parameters;
}
 
Example #10
Source File: SimpleEmailServiceJavaMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 3 votes vote down vote up
@Test
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) {
		assertThat(e.getFailedMessages().size()).isEqualTo(1);
		assertThat(e.getFailedMessages().containsKey(failureMail)).isTrue();
	}
}