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

The following examples show how to use com.amazonaws.services.simpleemail.model.SendEmailRequest. 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: Handler.java    From Building-Serverless-Architectures with MIT License 6 votes vote down vote up
private void sendEmail(final String emailAddress) {
  Destination destination = new Destination().withToAddresses(emailAddress);

  Message message = new Message()
      .withBody(new Body().withText(new Content("Welcome to our forum!")))
      .withSubject(new Content("Welcome!"));

  try {
    LOGGER.debug("Sending welcome mail to " + emailAddress);
    simpleEmailServiceClient.sendEmail(new SendEmailRequest()
        .withDestination(destination)
        .withSource(System.getenv("SenderEmail"))
        .withMessage(message)
    );
    LOGGER.debug("Sending welcome mail to " + emailAddress + " succeeded");
  } catch (Exception anyException) {
    LOGGER.error("Sending welcome mail to " + emailAddress + " failed: ", anyException);
  }

}
 
Example #2
Source File: EmailService.java    From oneops with Apache License 2.0 6 votes vote down vote up
/**
 * Send email.
 *
 * @param eMsg the e msg
 * @return true, if successful
 */
public boolean sendEmail(EmailMessage eMsg) {

    SendEmailRequest request = new SendEmailRequest().withSource(eMsg.getFromAddress());
    Destination dest = new Destination().withToAddresses(eMsg.getToAddresses());
    dest.setCcAddresses(eMsg.getToCcAddresses());
    request.setDestination(dest);
    Content subjContent = new Content().withData(eMsg.getSubject());
    Message msg = new Message().withSubject(subjContent);
    Content textContent = new Content().withData(eMsg.getTxtMessage());
    Body body = new Body().withText(textContent);
    if (eMsg.getHtmlMessage() != null) {
        Content htmlContent = new Content().withData(eMsg.getHtmlMessage());
        body.setHtml(htmlContent);
    }
    msg.setBody(body);
    request.setMessage(msg);
    try {
        emailClient.sendEmail(request);
        logger.debug(msg);
    } catch (AmazonClientException e) {
        logger.error(e.getMessage());
        return false;
    }
    return true;
}
 
Example #3
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 #4
Source File: SesDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares a {@link SendEmailRequest} with information harvested from emailSendRequest
 *
 * @param emailSendRequest the specified email information.
 *
 * @return the prepared send email request.
 */
private SendEmailRequest prepareSendEmailRequest(EmailSendRequest emailSendRequest)
{
    // Collect all required information and prepare individual email components required for the desired send email request.
    // Initialize a new aws send email request.
    SendEmailRequest sendEmailRequest = new SendEmailRequest();

    // Set 'from' address to the configured 'send-from' email address.
    sendEmailRequest.setSource(emailSendRequest.getSource());

    // Get destination information and add to send email request
    Destination destination = prepareDestination(emailSendRequest);
    sendEmailRequest.setDestination(destination);

    // Get message information and add to send email request
    Message message = prepareMessage(emailSendRequest);
    sendEmailRequest.setMessage(message);

    // Get config set name and add to send email request
    ConfigurationSet configurationSet = new ConfigurationSet().withName(configurationHelper.getProperty(ConfigurationValue.SES_CONFIGURATION_SET_NAME));

    sendEmailRequest.setConfigurationSetName(configurationSet.getName());

    return sendEmailRequest;
}
 
Example #5
Source File: SimpleEmailServiceMailSender.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
private SendEmailRequest prepareMessage(SimpleMailMessage simpleMailMessage) {
	Destination destination = new Destination();
	destination.withToAddresses(simpleMailMessage.getTo());

	if (simpleMailMessage.getCc() != null) {
		destination.withCcAddresses(simpleMailMessage.getCc());
	}

	if (simpleMailMessage.getBcc() != null) {
		destination.withBccAddresses(simpleMailMessage.getBcc());
	}

	Content subject = new Content(simpleMailMessage.getSubject());
	Body body = new Body(new Content(simpleMailMessage.getText()));

	SendEmailRequest emailRequest = new SendEmailRequest(simpleMailMessage.getFrom(),
			destination, new Message(subject, body));

	if (StringUtils.hasText(simpleMailMessage.getReplyTo())) {
		emailRequest.withReplyToAddresses(simpleMailMessage.getReplyTo());
	}

	return emailRequest;
}
 
Example #6
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 #7
Source File: SesDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public void sendEmail(final AwsParamsDto awsParamsDto, EmailSendRequest emailSendRequest)
{
    // Prepare and fetch a send email request from the provided information
    SendEmailRequest awsSendEmailRequest = prepareSendEmailRequest(emailSendRequest);

    // Send the prepared email
    sesOperations.sendEmail(awsSendEmailRequest, awsClientFactory.getSesClient(awsParamsDto));
}
 
Example #8
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 #9
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 #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: 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 #12
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 #13
Source File: AwsSesMailAgent.java    From kaif with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Boolean> send(Mail mailMessage) throws MailException {
  Message message = new Message();
  message.setSubject(new Content(mailMessage.getSubject()).withCharset(Charsets.UTF_8.toString()));
  message.setBody(new Body(new Content(mailMessage.getText()).withCharset(Charsets.UTF_8.toString())));

  Destination destination = new Destination(asList(mailMessage.getTo()));

  Optional.ofNullable(mailMessage.getCc())
      .filter(cc -> cc.length > 0)
      .ifPresent(cc -> destination.setCcAddresses(asList(cc)));

  Optional.ofNullable(mailMessage.getBcc())
      .filter(cc -> cc.length > 0)
      .ifPresent(cc -> destination.setBccAddresses(asList(cc)));

  SendEmailRequest sendEmailRequest = new SendEmailRequest(composeSource(mailMessage).toString(),
      destination,
      message);

  Optional.ofNullable(mailMessage.getReplyTo())
      .ifPresent(r -> sendEmailRequest.setReplyToAddresses(asList(r)));

  return CompletableFuture.supplyAsync(() -> {
    double totalWait = rateLimiter.acquire();
    if (totalWait > 5) {
      logger.warn("rate limit wait too long: " + totalWait + " seconds");
    }
    SendEmailResult emailResult = client.sendEmail(sendEmailRequest);
    if (logger.isDebugEnabled()) {
      logger.debug("sent mail messageId:{}, body:\n{}", emailResult.getMessageId(), mailMessage);
    } else {
      logger.info("sent mail to {}, messageId:{}", destination, emailResult.getMessageId());
    }
    return true;
  }, executor).handle((result, e) -> {
    if (e != null) {
      logger.warn("fail send mail to " + destination + ", error:" + e.getMessage());
      return false;
    }
    return true;
  });
}
 
Example #14
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);