Example usage for com.amazonaws.services.simpleemail.model Message Message

List of usage examples for com.amazonaws.services.simpleemail.model Message Message

Introduction

In this page you can find the example usage for com.amazonaws.services.simpleemail.model Message Message.

Prototype

public Message(Content subject, Body body) 

Source Link

Document

Constructs a new Message object.

Usage

From source file:com.amazon.aws.demo.SESManager.java

License:Open Source License

/** Send the feedback message based on data entered */
public static boolean sendFeedbackEmail(String comments, String name, float rating) {
    String subjectText = "Feedback from " + name;
    Content subjectContent = new Content(subjectText);

    String bodyText = "Rating: " + rating + "\nComments\n" + comments;
    Body messageBody = new Body(new Content(bodyText));

    Message feedbackMessage = new Message(subjectContent, messageBody);

    String email = PropertyLoader.getInstance().getVerifiedEmail();
    Destination destination = new Destination().withToAddresses(email);

    SendEmailRequest request = new SendEmailRequest(email, destination, feedbackMessage);
    try {//from w  w w . ja  v  a2  s.  c o  m
        SendEmailResult result = FeedbackFormDemoActivity.clientManager.ses().sendEmail(request);
    } catch (Throwable e) {
        Log.e(LOG_TAG, "Error sending mail" + e);
        return false;
    }

    return true;
}

From source file:com.github.trask.sandbox.mail.impl.AmazonMailService.java

License:Apache License

public Future<Void> sendMail(String from, String to, String subject, String htmlBody, String textBody) {

    logger.debug("sendMail(): from={}", from);
    logger.debug("sendMail(): to={}", to);
    logger.debug("sendMail(): subject={}", subject);
    logger.debug("sendMail(): htmlBody={}", htmlBody);
    logger.debug("sendMail(): textBody={}", textBody);

    Body body = new Body(new Content(textBody)).withHtml(new Content(htmlBody));
    Message message = new Message(new Content(subject), body);

    SendEmailRequest sendEmailRequest = new SendEmailRequest();
    sendEmailRequest.setSource(from);//from w  w w. jav a 2s .c  o m
    sendEmailRequest.setDestination(new Destination(Collections.singletonList(to)));
    sendEmailRequest.setMessage(message);
    Future<SendEmailResult> future = simpleEmailServiceAsync.sendEmailAsync(sendEmailRequest);
    return new VoidFutureWrapper(future);
}

From source file:com.netflix.ice.processor.BillingFileProcessor.java

License:Apache License

private void sendOndemandCostAlert() {

    if (ondemandThreshold == null || StringUtils.isEmpty(fromEmail) || StringUtils.isEmpty(alertEmails)
            || endMilli < lastAlertMillis() + AwsUtils.hourMillis * 24)
        return;//from  ww w .  ja v a 2s.c o m

    Map<Long, Map<Ec2InstanceReservationPrice.Key, Double>> ondemandCosts = getOndemandCosts(
            lastAlertMillis() + AwsUtils.hourMillis);
    Long maxHour = null;
    double maxTotal = ondemandThreshold;

    for (Long hour : ondemandCosts.keySet()) {
        double total = 0;
        for (Double value : ondemandCosts.get(hour).values())
            total += value;

        if (total > maxTotal) {
            maxHour = hour;
            maxTotal = total;
        }
    }

    if (maxHour != null) {
        NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
        String subject = String.format("Alert: Ondemand cost per hour reached $%s at %s",
                numberFormat.format(maxTotal), AwsUtils.dateFormatter.print(maxHour));
        StringBuilder body = new StringBuilder();
        body.append(String.format("Total ondemand cost $%s at %s:<br><br>", numberFormat.format(maxTotal),
                AwsUtils.dateFormatter.print(maxHour)));
        TreeMap<Double, String> costs = Maps.newTreeMap();
        for (Map.Entry<Ec2InstanceReservationPrice.Key, Double> entry : ondemandCosts.get(maxHour).entrySet()) {
            costs.put(entry.getValue(), entry.getKey().region + " " + entry.getKey().usageType + ": ");
        }
        for (Double cost : costs.descendingKeySet()) {
            if (cost > 0)
                body.append(costs.get(cost)).append("$" + numberFormat.format(cost)).append("<br>");
        }
        body.append("<br>Please go to <a href=\"" + urlPrefix
                + "dashboard/reservation#usage_cost=cost&groupBy=UsageType&product=ec2_instance&operation=OndemandInstances\">Ice</a> for details.");
        SendEmailRequest request = new SendEmailRequest();
        request.withSource(fromEmail);
        List<String> emails = Lists.newArrayList(alertEmails.split(","));
        request.withDestination(new Destination(emails));
        request.withMessage(
                new Message(new Content(subject), new Body().withHtml(new Content(body.toString()))));

        AmazonSimpleEmailServiceClient emailService = AwsUtils.getAmazonSimpleEmailServiceClient();
        try {
            emailService.sendEmail(request);
            updateLastAlertMillis(endMilli);
            logger.info("updateLastAlertMillis " + endMilli);
        } catch (Exception e) {
            logger.error("Error in sending alert emails", e);
        }
    }
}

From source file:com.netflix.simianarmy.aws.AWSEmailNotifier.java

License:Apache License

@Override
public void sendEmail(String to, String subject, String body) {
    if (!isValidEmail(to)) {
        LOGGER.error(String.format("The destination email address %s is not valid,  no email is sent.", to));
        return;//  w  w w . j  a  v  a2s . com
    }
    if (sesClient == null) {
        String msg = "The email client is not set.";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    }
    Destination destination = new Destination().withToAddresses(to).withCcAddresses(getCcAddresses(to));
    Content subjectContent = new Content(subject);
    Content bodyContent = new Content();
    Body msgBody = new Body(bodyContent);
    msgBody.setHtml(new Content(body));
    Message msg = new Message(subjectContent, msgBody);
    String sourceAddress = getSourceAddress(to);
    SendEmailRequest request = new SendEmailRequest(sourceAddress, destination, msg);
    request.setReturnPath(sourceAddress);
    LOGGER.debug(String.format("Sending email with subject '%s' to %s", subject, to));
    SendEmailResult result = null;
    try {
        result = sesClient.sendEmail(request);
    } catch (Exception e) {
        throw new RuntimeException(String.format("Failed to send email to %s", to), e);
    }
    LOGGER.info(
            String.format("Email to %s, result id is %s, subject is %s", to, result.getMessageId(), subject));
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

License:Apache License

/**
 * Send email with Amazon Simple Email Service.
 * <p/>//  ww w . j  a v  a2s .co  m
 * <p/>
 * Please note that the sender (ie 'from') must be a verified address (see
 * {@link AmazonSimpleEmailService#verifyEmailAddress(com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest)}
 * ).
 * <p/>
 * <p/>
 * Please note that the sender is a CC of the meail to ease support.
 * <p/>
 *
 * @param subject
 * @param body
 * @param from
 * @param toAddresses
 */

public void sendEmail(String subject, String body, String from, String... toAddresses) {

    SendEmailRequest sendEmailRequest = new SendEmailRequest( //
            from, //
            new Destination().withToAddresses(toAddresses).withCcAddresses(from), //
            new Message(new Content(subject), //
                    new Body(new Content(body))));
    SendEmailResult sendEmailResult = ses.sendEmail(sendEmailRequest);
    System.out.println(sendEmailResult);
}

From source file:jp.classmethod.aws.petrucci.Tasks.java

License:Apache License

@Scheduled(cron = "0 */2 * * * *")
public void reportS3AndEC2() {
    logger.info("report start");
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    StringBuilder sb = new StringBuilder();

    logger.info("check S3 buckets");
    sb.append("== S3 Buckets ==\n");
    try {//from  w  ww  . j a  va2s  .  co m
        for (Bucket bucket : s3.listBuckets()) {
            sb.append(
                    String.format("%s (created:%s)%n", bucket.getName(), df.format(bucket.getCreationDate())));
        }
    } catch (AmazonClientException e) {
        logger.error("unexpected exception", e);
    }

    sb.append("\n");

    logger.info("check EC2 instances");
    sb.append("== EC2 Instances ==").append("\n");
    try {
        DescribeInstancesResult result = ec2.describeInstances();
        for (Reservation reservation : result.getReservations()) {
            for (Instance instance : reservation.getInstances()) {
                sb.append(String.format("%s %s %s%n", instance.getInstanceId(), instance.getImageId(),
                        instance.getInstanceType(), instance.getInstanceLifecycle()));
            }
        }
    } catch (AmazonClientException e) {
        logger.error("unexpected exception", e);
    }

    if (logger.isInfoEnabled()) {
        Scanner scanner = null;
        try {
            scanner = new Scanner(sb.toString());
            while (scanner.hasNextLine()) {
                logger.info("{}", scanner.nextLine());
            }
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
    }

    logger.info("send report mail");
    ses.sendEmail(new SendEmailRequest(mailaddress, new Destination(Collections.singletonList(mailaddress)),
            new Message(new Content("S3 & EC2 Report"), new Body(new Content(sb.toString())))));

    logger.info("report end");
}

From source file:org.duracloud.mill.notification.SESNotificationManager.java

License:Apache License

@Override
public void sendEmail(String subject, String body) {
    if (ArrayUtils.isEmpty(this.recipientEmailAddresses)) {
        log.warn("No recipients configured - no one to notify: ignoring...");
        return;//  ww w .j  a  v a2  s  .c  om
    }

    SendEmailRequest email = new SendEmailRequest();
    try {
        Destination destination = new Destination();
        destination.setToAddresses(Arrays.asList(this.recipientEmailAddresses));
        email.setDestination(destination);
        email.setSource("notifications@duracloud.org");
        Message message = new Message(new Content(subject), new Body(new Content(body)));
        email.setMessage(message);
        client.sendEmail(email);
        log.info("email sent: {}", email);
    } catch (Exception e) {
        log.error("failed to send " + email + ": " + e.getMessage(), e);
    }

}

From source file:org.onebusaway.admin.service.impl.EmailServiceImpl.java

License:Apache License

@Override
public void sendAsync(String to, String from, String subject, StringBuffer messageBody) {
    List<String> toAddresses = new ArrayList<String>();
    for (String address : to.split(",")) {
        toAddresses.add(address);//from   w  w  w . j a v  a2 s.  c om
    }
    Destination destination = new Destination(toAddresses);
    Body body = new Body();
    body.setText(new Content(messageBody.toString()));
    Message message = new Message(new Content(subject), body);
    SendEmailRequest sendEmailRequest = new SendEmailRequest(from, destination, message);
    Future<SendEmailResult> result = _eClient.sendEmailAsync(sendEmailRequest);
    _log.info("sent email to " + to + " with finished=" + result.isDone());
}

From source file:org.onebusaway.admin.service.impl.EmailServiceImpl.java

License:Apache License

public void sendSES(String to, String from, String subject, StringBuffer messageBody) {
    List<String> toAddresses = new ArrayList<String>();
    for (String address : to.split(",")) {
        toAddresses.add(address);//  w ww  .  j a va 2  s .  c  om
    }
    Destination destination = new Destination(toAddresses);
    Body body = new Body();
    body.setText(new Content(messageBody.toString()));
    Message message = new Message(new Content(subject), body);
    SendEmailRequest sendEmailRequest = new SendEmailRequest(from, destination, message);
    SendEmailResult result = _eClient.sendEmail(sendEmailRequest);
    _log.info("sent email to " + to + " with result=" + result);
}

From source file:org.springframework.cloud.aws.mail.simplemail.SimpleEmailServiceMailSender.java

License:Apache License

private SendEmailRequest prepareMessage(SimpleMailMessage simpleMailMessage) {
    Destination destination = new Destination();
    destination.withToAddresses(simpleMailMessage.getTo());

    if (simpleMailMessage.getCc() != null) {
        destination.withCcAddresses(simpleMailMessage.getCc());
    }/*w  w w.ja  v  a2s  .c  o m*/

    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;
}