Example usage for org.apache.commons.mail MultiPartEmail setFrom

List of usage examples for org.apache.commons.mail MultiPartEmail setFrom

Introduction

In this page you can find the example usage for org.apache.commons.mail MultiPartEmail setFrom.

Prototype

public Email setFrom(final String email, final String name, final String charset) throws EmailException 

Source Link

Document

Set the FROM field of the email to use the specified address, personal name, and charset encoding for the name.

Usage

From source file:com.pushinginertia.commons.net.email.EmailUtils.java

/**
 * Populates a newly instantiated {@link MultiPartEmail} with the given arguments.
 * @param email email instance to populate
 * @param smtpHost SMTP host that the message will be sent to
 * @param msg container object for the email's headers and contents
 * @throws IllegalArgumentException if the inputs are not valid
 * @throws EmailException if a problem occurs constructing the email
 *///from   ww  w. j a  va2s .  c  o m
public static void populateMultiPartEmail(final MultiPartEmail email, final String smtpHost,
        final EmailMessage msg) throws IllegalArgumentException, EmailException {
    ValidateAs.notNull(email, "email");
    ValidateAs.notNull(smtpHost, "smtpHost");
    ValidateAs.notNull(msg, "msg");

    email.setHostName(smtpHost);
    email.setCharset(UTF_8);
    email.setFrom(msg.getSender().getEmail(), msg.getSender().getName(), UTF_8);
    email.addTo(msg.getRecipient().getEmail(), msg.getRecipient().getName(), UTF_8);

    final NameEmail replyTo = msg.getReplyTo();
    if (replyTo != null) {
        email.addReplyTo(replyTo.getEmail(), replyTo.getName(), UTF_8);
    }

    final String bounceEmailAddress = msg.getBounceEmailAddress();
    if (bounceEmailAddress != null) {
        email.setBounceAddress(bounceEmailAddress);
    }

    email.setSubject(msg.getSubject());

    final String languageId = msg.getRecipient().getLanguage();
    if (languageId != null) {
        email.addHeader("Language", languageId);
        email.addHeader("Content-Language", languageId);
    }

    // add optional headers
    final EmailMessageHeaders headers = msg.getHeaders();
    if (headers != null) {
        for (final Map.Entry<String, String> header : headers.getHeaders().entrySet()) {
            email.addHeader(header.getKey(), header.getValue());
        }
    }

    // generate email body
    try {
        final MimeMultipart mm = new MimeMultipart("alternative; charset=UTF-8");

        final MimeBodyPart text = new MimeBodyPart();
        text.setContent(msg.getTextContent(), "text/plain; charset=UTF-8");
        mm.addBodyPart(text);

        final MimeBodyPart html = new MimeBodyPart();
        html.setContent(msg.getHtmlContent(), "text/html; charset=UTF-8");
        mm.addBodyPart(html);

        email.setContent(mm);
    } catch (MessagingException e) {
        throw new EmailException(e);
    }

}