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

The following examples show how to use com.amazonaws.services.simpleemail.model.RawMessage. 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: 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 #3
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 #4
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;
}