com.amazonaws.services.simpleemail.AmazonSimpleEmailService Java Examples

The following examples show how to use com.amazonaws.services.simpleemail.AmazonSimpleEmailService. 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: SimpleEmailServiceJavaMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void testCreateMimeMessageWithExceptionInInputStream() throws Exception {
	InputStream inputStream = mock(InputStream.class);

	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);

	JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService);

	IOException ioException = new IOException("error");
	when(inputStream.read(ArgumentMatchers.any(byte[].class),
			ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()))
					.thenThrow(ioException);

	try {
		mailSender.createMimeMessage(inputStream);
		fail("MailPreparationException expected due to error while creating mail");
	}
	catch (MailParseException e) {
		assertThat(e.getMessage().startsWith("Could not parse raw MIME content"))
				.isTrue();
		assertThat(e.getCause().getCause()).isSameAs(ioException);
	}
}
 
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: SimpleEmailServiceMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void testSendMultipleMailsWithExceptionWhileSending() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);
	SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(
			emailService);

	SimpleMailMessage firstMessage = createSimpleMailMessage();
	firstMessage.setBcc("[email protected]");

	SimpleMailMessage failureMail = createSimpleMailMessage();
	when(emailService.sendEmail(ArgumentMatchers.isA(SendEmailRequest.class)))
			.thenReturn(new SendEmailResult())
			.thenThrow(new AmazonClientException("error"))
			.thenReturn(new SendEmailResult());

	SimpleMailMessage thirdMessage = createSimpleMailMessage();

	try {
		mailSender.send(firstMessage, failureMail, thirdMessage);
		fail("Exception expected due to error while sending mail");
	}
	catch (MailSendException e) {
		assertThat(e.getFailedMessages().size()).isEqualTo(1);
		assertThat(e.getFailedMessages().containsKey(failureMail)).isTrue();
	}
}
 
Example #4
Source File: AWSEmailProviderTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendEmailError() {

    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_to", "example.com");
    System.setProperty("athenz.notification_email_domain_from", "from.example.com");
    System.setProperty("athenz.notification_email_from", "no-reply-athenz");

    AmazonSimpleEmailService ses = mock(AmazonSimpleEmailService.class);
    Mockito.when(ses.sendEmail(any(SendEmailRequest.class))).thenThrow(new RuntimeException());
    AWSEmailProvider awsEmailProvider = new AWSEmailProvider(ses);

    EmailNotificationService svc = new EmailNotificationService(awsEmailProvider);

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

    System.clearProperty("athenz.notification_email_domain_from");
    System.clearProperty("athenz.notification_email_domain_to");
    System.clearProperty("athenz.notification_email_from");
}
 
Example #5
Source File: AwsClientFactory.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a cacheable client for AWS SES service with pluggable aws client params.
 *
 * @param awsParamsDto the specified aws parameters
 *
 * @return the Amazon SES client
 */
@Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME)
public AmazonSimpleEmailService getSesClient(AwsParamsDto awsParamsDto)
{
    // Get client configuration
    ClientConfiguration clientConfiguration = awsHelper.getClientConfiguration(awsParamsDto);

    // If specified, use the AWS credentials passed in.
    if (StringUtils.isNotBlank(awsParamsDto.getAwsAccessKeyId()))
    {
        return AmazonSimpleEmailServiceClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(
            new BasicSessionCredentials(awsParamsDto.getAwsAccessKeyId(), awsParamsDto.getAwsSecretKey(), awsParamsDto.getSessionToken())))
            .withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName()).build();
    }
    // Otherwise, use the default AWS credentials provider chain.
    else
    {
        return AmazonSimpleEmailServiceClientBuilder.standard().withClientConfiguration(clientConfiguration).withRegion(awsParamsDto.getAwsRegionName())
            .build();
    }
}
 
Example #6
Source File: AmazonDockerClientsHolder.java    From spring-localstack with Apache License 2.0 5 votes vote down vote up
@Override
public AmazonSimpleEmailService amazonSimpleEmailService() {
    return decorateWithConfigsAndBuild(
        AmazonSimpleEmailServiceClientBuilder.standard(),
        LocalstackDocker::getEndpointSES
    );
}
 
Example #7
Source File: SimpleEmailServiceMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testSendSimpleMailWithMinimalProperties() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);
	SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(
			emailService);

	SimpleMailMessage simpleMailMessage = createSimpleMailMessage();

	ArgumentCaptor<SendEmailRequest> request = ArgumentCaptor
			.forClass(SendEmailRequest.class);
	when(emailService.sendEmail(request.capture()))
			.thenReturn(new SendEmailResult().withMessageId("123"));

	mailSender.send(simpleMailMessage);

	SendEmailRequest sendEmailRequest = request.getValue();
	assertThat(sendEmailRequest.getSource()).isEqualTo(simpleMailMessage.getFrom());
	assertThat(sendEmailRequest.getDestination().getToAddresses().get(0))
			.isEqualTo(simpleMailMessage.getTo()[0]);
	assertThat(sendEmailRequest.getMessage().getSubject().getData())
			.isEqualTo(simpleMailMessage.getSubject());
	assertThat(sendEmailRequest.getMessage().getBody().getText().getData())
			.isEqualTo(simpleMailMessage.getText());
	assertThat(sendEmailRequest.getDestination().getCcAddresses().size())
			.isEqualTo(0);
	assertThat(sendEmailRequest.getDestination().getBccAddresses().size())
			.isEqualTo(0);
}
 
Example #8
Source File: SimpleEmailServiceMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testSendSimpleMailWithCCandBCC() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);
	SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(
			emailService);

	SimpleMailMessage simpleMailMessage = createSimpleMailMessage();
	simpleMailMessage.setBcc("[email protected]");
	simpleMailMessage.setCc("[email protected]");

	ArgumentCaptor<SendEmailRequest> request = ArgumentCaptor
			.forClass(SendEmailRequest.class);
	when(emailService.sendEmail(request.capture()))
			.thenReturn(new SendEmailResult().withMessageId("123"));

	mailSender.send(simpleMailMessage);

	SendEmailRequest sendEmailRequest = request.getValue();
	assertThat(sendEmailRequest.getSource()).isEqualTo(simpleMailMessage.getFrom());
	assertThat(sendEmailRequest.getDestination().getToAddresses().get(0))
			.isEqualTo(simpleMailMessage.getTo()[0]);
	assertThat(sendEmailRequest.getMessage().getSubject().getData())
			.isEqualTo(simpleMailMessage.getSubject());
	assertThat(sendEmailRequest.getMessage().getBody().getText().getData())
			.isEqualTo(simpleMailMessage.getText());
	assertThat(sendEmailRequest.getDestination().getBccAddresses().get(0))
			.isEqualTo(simpleMailMessage.getBcc()[0]);
	assertThat(sendEmailRequest.getDestination().getCcAddresses().get(0))
			.isEqualTo(simpleMailMessage.getCc()[0]);
}
 
Example #9
Source File: MailSenderAutoConfiguration.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingAmazonClient(AmazonSimpleEmailService.class)
public AmazonWebserviceClientFactoryBean<AmazonSimpleEmailServiceClient> amazonSimpleEmailService(
		AWSCredentialsProvider credentialsProvider) {
	return new AmazonWebserviceClientFactoryBean<>(
			AmazonSimpleEmailServiceClient.class, credentialsProvider,
			this.regionProvider);
}
 
Example #10
Source File: SimpleEmailServiceMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testSendMultipleMails() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);
	SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(
			emailService);

	ArgumentCaptor<SendEmailRequest> request = ArgumentCaptor
			.forClass(SendEmailRequest.class);
	when(emailService.sendEmail(request.capture()))
			.thenReturn(new SendEmailResult().withMessageId("123"));

	mailSender.send(createSimpleMailMessage(), createSimpleMailMessage());
	verify(emailService, times(2))
			.sendEmail(ArgumentMatchers.any(SendEmailRequest.class));
}
 
Example #11
Source File: AwsClientFactoryTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSesClientCacheHitMiss()
{
    // Create an AWS parameters DTO that contains both AWS credentials and proxy information.
    AwsParamsDto awsParamsDto =
        new AwsParamsDto(AWS_ASSUMED_ROLE_ACCESS_KEY, AWS_ASSUMED_ROLE_SECRET_KEY, AWS_ASSUMED_ROLE_SESSION_TOKEN, HTTP_PROXY_HOST, HTTP_PROXY_PORT,
            AWS_REGION_NAME_US_EAST_1);

    // Get an Amazon SES client.
    AmazonSimpleEmailService amazonSimpleEmailService = awsClientFactory.getSesClient(awsParamsDto);

    // Confirm a cache hit.
    assertEquals(amazonSimpleEmailService, awsClientFactory.getSesClient(
        new AwsParamsDto(AWS_ASSUMED_ROLE_ACCESS_KEY, AWS_ASSUMED_ROLE_SECRET_KEY, AWS_ASSUMED_ROLE_SESSION_TOKEN, HTTP_PROXY_HOST, HTTP_PROXY_PORT,
            AWS_REGION_NAME_US_EAST_1)));

    // Confirm a cache miss due to AWS credentials.
    assertNotEquals(amazonSimpleEmailService, awsClientFactory.getSesClient(
        new AwsParamsDto(AWS_ASSUMED_ROLE_ACCESS_KEY_2, AWS_ASSUMED_ROLE_SECRET_KEY_2, AWS_ASSUMED_ROLE_SESSION_TOKEN_2, HTTP_PROXY_HOST, HTTP_PROXY_PORT,
            AWS_REGION_NAME_US_EAST_1)));

    // Confirm a cache miss due to http proxy information.
    assertNotEquals(amazonSimpleEmailService, awsClientFactory.getSesClient(
        new AwsParamsDto(AWS_ASSUMED_ROLE_ACCESS_KEY, AWS_ASSUMED_ROLE_SECRET_KEY, AWS_ASSUMED_ROLE_SESSION_TOKEN, HTTP_PROXY_HOST_2, HTTP_PROXY_PORT_2,
            AWS_REGION_NAME_US_EAST_1)));

    // Clear the cache.
    cacheManager.getCache(DaoSpringModuleConfig.HERD_CACHE_NAME).clear();

    // Confirm a cache miss due to cleared cache.
    assertNotEquals(amazonSimpleEmailService, awsClientFactory.getSesClient(awsParamsDto));
}
 
Example #12
Source File: SimpleEmailServiceMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Test
void testShutDownOfResources() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);
	SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(
			emailService);

	mailSender.destroy();
	verify(emailService, times(1)).shutdown();
}
 
Example #13
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 #14
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 #15
Source File: AWSEmailProvider.java    From athenz with Apache License 2.0 5 votes vote down vote up
private static AmazonSimpleEmailService initSES() {
    ///CLOVER:OFF
    Region region = Regions.getCurrentRegion();
    if (region == null) {
        region = Region.getRegion(Regions.US_EAST_1);
    }
    return AmazonSimpleEmailServiceClientBuilder.standard().withRegion(region.getName()).build();
    ///CLOVER:ON
}
 
Example #16
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 #17
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 #18
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 #19
Source File: MockSesOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public void sendEmail(SendEmailRequest sendEmailRequest, AmazonSimpleEmailService simpleEmailService)
{

}
 
Example #20
Source File: SimpleEmailServiceJavaMailSender.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
public SimpleEmailServiceJavaMailSender(
		AmazonSimpleEmailService amazonSimpleEmailService) {
	super(amazonSimpleEmailService);
}
 
Example #21
Source File: SimpleEmailServiceMailSender.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
protected AmazonSimpleEmailService getEmailService() {
	return this.emailService;
}
 
Example #22
Source File: SimpleEmailServiceMailSender.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
public SimpleEmailServiceMailSender(
		AmazonSimpleEmailService amazonSimpleEmailService) {
	this.emailService = amazonSimpleEmailService;
}
 
Example #23
Source File: MailSenderAutoConfiguration.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnClass(name = "javax.mail.Session")
public JavaMailSender javaMailSender(
		AmazonSimpleEmailService amazonSimpleEmailService) {
	return new SimpleEmailServiceJavaMailSender(amazonSimpleEmailService);
}
 
Example #24
Source File: MailSenderAutoConfiguration.java    From spring-cloud-aws with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingClass("org.springframework.cloud.aws.mail.simplemail.SimpleEmailServiceJavaMailSender")
public MailSender simpleMailSender(
		AmazonSimpleEmailService amazonSimpleEmailService) {
	return new SimpleEmailServiceMailSender(amazonSimpleEmailService);
}
 
Example #25
Source File: SesOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public void sendEmail(SendEmailRequest sendEmailRequest, AmazonSimpleEmailService simpleEmailService)
{
    simpleEmailService.sendEmail(sendEmailRequest);
}
 
Example #26
Source File: AWSEmailProvider.java    From athenz with Apache License 2.0 4 votes vote down vote up
AWSEmailProvider(AmazonSimpleEmailService ses) {
    this.ses = ses;
}
 
Example #27
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 #28
Source File: EveryAwsClientAutoConfiguration.java    From spring-localstack with Apache License 2.0 4 votes vote down vote up
@Bean
public AmazonSimpleEmailService amazonSimpleEmailService() {
    return amazonClientsHolder.amazonSimpleEmailService();
}
 
Example #29
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();
	}
}
 
Example #30
Source File: SesOperations.java    From herd with Apache License 2.0 2 votes vote down vote up
/**
 * Sends an email with all the options as specified in the emailSendRequest
 *
 * @param sendEmailRequest the specified information on the email to send
 * @param simpleEmailService the specified ses service object
 */
void sendEmail(SendEmailRequest sendEmailRequest, AmazonSimpleEmailService simpleEmailService);