Example usage for org.apache.commons.mail HtmlEmail HtmlEmail

List of usage examples for org.apache.commons.mail HtmlEmail HtmlEmail

Introduction

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

Prototype

HtmlEmail

Source Link

Usage

From source file:com.baasbox.service.user.UserService.java

public static void sendResetPwdMail(String appCode, ODocument user) throws Exception {
    final String errorString = "Cannot send mail to reset the password: ";

    //check method input
    if (!user.getSchemaClass().getName().equalsIgnoreCase(UserDao.MODEL_NAME))
        throw new PasswordRecoveryException(errorString + " invalid user object");

    //initialization
    String siteUrl = Application.NETWORK_HTTP_URL.getValueAsString();
    int sitePort = Application.NETWORK_HTTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(siteUrl))
        throw new PasswordRecoveryException(errorString + " invalid site url (is empty)");

    String textEmail = PasswordRecovery.EMAIL_TEMPLATE_TEXT.getValueAsString();
    String htmlEmail = PasswordRecovery.EMAIL_TEMPLATE_HTML.getValueAsString();
    if (StringUtils.isEmpty(htmlEmail))
        htmlEmail = textEmail;/*from   w ww . ja  v  a2s . c  o m*/
    if (StringUtils.isEmpty(htmlEmail))
        throw new PasswordRecoveryException(errorString + " text to send is not configured");

    boolean useSSL = PasswordRecovery.NETWORK_SMTP_SSL.getValueAsBoolean();
    boolean useTLS = PasswordRecovery.NETWORK_SMTP_TLS.getValueAsBoolean();
    String smtpHost = PasswordRecovery.NETWORK_SMTP_HOST.getValueAsString();
    int smtpPort = PasswordRecovery.NETWORK_SMTP_PORT.getValueAsInteger();
    if (StringUtils.isEmpty(smtpHost))
        throw new PasswordRecoveryException(errorString + " SMTP host is not configured");

    String username_smtp = null;
    String password_smtp = null;
    if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
        username_smtp = PasswordRecovery.NETWORK_SMTP_USER.getValueAsString();
        password_smtp = PasswordRecovery.NETWORK_SMTP_PASSWORD.getValueAsString();
        if (StringUtils.isEmpty(username_smtp))
            throw new PasswordRecoveryException(errorString + " SMTP username is not configured");
    }
    String emailFrom = PasswordRecovery.EMAIL_FROM.getValueAsString();
    String emailSubject = PasswordRecovery.EMAIL_SUBJECT.getValueAsString();
    if (StringUtils.isEmpty(emailFrom))
        throw new PasswordRecoveryException(errorString + " sender email is not configured");

    try {
        String userEmail = ((ODocument) user.field(UserDao.ATTRIBUTES_VISIBLE_ONLY_BY_THE_USER)).field("email")
                .toString();

        String username = (String) ((ODocument) user.field("user")).field("name");

        //Random
        String sRandom = appCode + "%%%%" + username + "%%%%" + UUID.randomUUID();
        String sBase64Random = new String(Base64.encodeBase64(sRandom.getBytes()));

        //Save on DB
        ResetPwdDao.getInstance().create(new Date(), sBase64Random, user);

        //Send mail
        HtmlEmail email = null;

        URL resetUrl = new URL(Application.NETWORK_HTTP_SSL.getValueAsBoolean() ? "https" : "http", siteUrl,
                sitePort, "/user/password/reset/" + sBase64Random);

        //HTML Email Text
        ST htmlMailTemplate = new ST(htmlEmail, '$', '$');
        htmlMailTemplate.add("link", resetUrl);
        htmlMailTemplate.add("user_name", username);
        htmlMailTemplate.add("token", sBase64Random);

        //Plain text Email Text
        ST textMailTemplate = new ST(textEmail, '$', '$');
        textMailTemplate.add("link", resetUrl);
        textMailTemplate.add("user_name", username);
        textMailTemplate.add("token", sBase64Random);

        email = new HtmlEmail();

        email.setHtmlMsg(htmlMailTemplate.render());
        email.setTextMsg(textMailTemplate.render());

        //Email Configuration
        email.setSSL(useSSL);
        email.setSSLOnConnect(useSSL);
        email.setTLS(useTLS);
        email.setStartTLSEnabled(useTLS);
        email.setStartTLSRequired(useTLS);
        email.setSSLCheckServerIdentity(false);
        email.setSslSmtpPort(String.valueOf(smtpPort));
        email.setHostName(smtpHost);
        email.setSmtpPort(smtpPort);
        email.setCharset("utf-8");

        if (PasswordRecovery.NETWORK_SMTP_AUTHENTICATION.getValueAsBoolean()) {
            email.setAuthenticator(new DefaultAuthenticator(username_smtp, password_smtp));
        }
        email.setFrom(emailFrom);
        email.addTo(userEmail);

        email.setSubject(emailSubject);
        if (BaasBoxLogger.isDebugEnabled()) {
            StringBuilder logEmail = new StringBuilder().append("HostName: ").append(email.getHostName())
                    .append("\n").append("SmtpPort: ").append(email.getSmtpPort()).append("\n")
                    .append("SslSmtpPort: ").append(email.getSslSmtpPort()).append("\n")

                    .append("SSL: ").append(email.isSSL()).append("\n").append("TLS: ").append(email.isTLS())
                    .append("\n").append("SSLCheckServerIdentity: ").append(email.isSSLCheckServerIdentity())
                    .append("\n").append("SSLOnConnect: ").append(email.isSSLOnConnect()).append("\n")
                    .append("StartTLSEnabled: ").append(email.isStartTLSEnabled()).append("\n")
                    .append("StartTLSRequired: ").append(email.isStartTLSRequired()).append("\n")

                    .append("SubType: ").append(email.getSubType()).append("\n")
                    .append("SocketConnectionTimeout: ").append(email.getSocketConnectionTimeout()).append("\n")
                    .append("SocketTimeout: ").append(email.getSocketTimeout()).append("\n")

                    .append("FromAddress: ").append(email.getFromAddress()).append("\n").append("ReplyTo: ")
                    .append(email.getReplyToAddresses()).append("\n").append("BCC: ")
                    .append(email.getBccAddresses()).append("\n").append("CC: ").append(email.getCcAddresses())
                    .append("\n")

                    .append("Subject: ").append(email.getSubject()).append("\n")

                    //the following line throws a NPE in debug mode
                    //.append("Message: ").append(email.getMimeMessage().getContent()).append("\n")

                    .append("SentDate: ").append(email.getSentDate()).append("\n");
            BaasBoxLogger.debug("Password Recovery is ready to send: \n" + logEmail.toString());
        }
        email.send();

    } catch (EmailException authEx) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(authEx));
        throw new PasswordRecoveryException(
                errorString + " Could not reach the mail server. Please contact the server administrator");
    } catch (Exception e) {
        BaasBoxLogger.error("ERROR SENDING MAIL:" + ExceptionUtils.getStackTrace(e));
        throw new Exception(errorString, e);
    }

}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*  ww  w.  j a  v a  2s.c  o m*/
 *
 * @param args DOCUMENT ME!
 *
 * @throws UnsupportedEncodingException DOCUMENT ME!
 * @throws EmailException DOCUMENT ME!
 * @throws MessagingException DOCUMENT ME!
 */
public static void main(String[] args) throws UnsupportedEncodingException, EmailException, MessagingException {
    InternetAddress[] aux1 = new InternetAddress[5];
    aux1[0] = new InternetAddress("duroty@iigov.net", "Jordi Marqus");
    aux1[1] = new InternetAddress("duroty@iigov.net", "Jordi Marqus");
    aux1[2] = new InternetAddress("duroty@iigov.net", "Jordi Marqus");
    aux1[3] = new InternetAddress("duroty@iigov.net", "Jordi Marqus");
    aux1[4] = new InternetAddress("duroty@iigov.net", "Jordi Marqus");

    System.out.println(MessageUtilities.decodeAddressesEmail(aux1));

    HtmlEmail email = new HtmlEmail();
    email.setHostName("10.0.0.68");
    email.setFrom("duroty@iigov.net");
    email.addReplyTo("duroty@iigov.net");

    email.addTo("cagao@ii.org");

    email.addCc("raul1@iigov.org");
    email.addCc("raul2@iigov.org");
    email.addCc("raul3@iigov.org");
    email.addCc("raul4@iigov.org");
    email.addCc("raul5@iigov.org");

    email.addBcc("caca1@iigov.org");

    email.setHtmlMsg("<html>la merda fa pudor</html>");

    email.buildMimeMessage();

    MimeMessage mime = email.getMimeMessage();

    System.out.println(MessageUtilities.decodeAddressesEmail(mime.getAllRecipients()));
}

From source file:gov.osti.services.Metadata.java

/**
 * Send a NOTIFICATION EMAIL (if configured) when a record is SUBMITTED or
 * ANNOUNCED.//from  w  w  w.  j ava  2  s  .c  om
 *
 * @param md the METADATA in question
 */
private static void sendStatusNotification(DOECodeMetadata md) {
    HtmlEmail email = new HtmlEmail();
    email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8);
    email.setHostName(EMAIL_HOST);

    // if EMAIL or DESTINATION ADDRESS are not set, abort
    if (StringUtils.isEmpty(EMAIL_HOST) || StringUtils.isEmpty(EMAIL_SUBMISSION))
        return;

    // only applicable to SUBMITTED or ANNOUNCED records
    if (!Status.Announced.equals(md.getWorkflowStatus()) && !Status.Submitted.equals(md.getWorkflowStatus()))
        return;

    // get the SITE information
    String siteCode = md.getSiteOwnershipCode();
    Site site = SiteServices.findSiteBySiteCode(siteCode);
    if (null == site) {
        log.warn("Unable to locate SITE information for SITE CODE: " + siteCode);
        return;
    }
    String lab = site.getLab();
    lab = lab.isEmpty() ? siteCode : lab;

    try {
        email.setFrom(EMAIL_FROM);
        email.setSubject("DOE CODE Record " + md.getWorkflowStatus().toString());
        email.addTo(EMAIL_SUBMISSION);

        String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", "");

        StringBuilder msg = new StringBuilder();
        msg.append("<html>");
        msg.append("A new DOE CODE record has been ").append(md.getWorkflowStatus()).append(" for ").append(lab)
                .append(" and is awaiting approval:");

        msg.append("<P>Code ID: ").append(md.getCodeId());
        msg.append("<BR>Software Title: ").append(softwareTitle);
        msg.append("</html>");

        email.setHtmlMsg(msg.toString());

        email.send();
    } catch (EmailException e) {
        log.error("Failed to send submission/announcement notification message for #" + md.getCodeId());
        log.error("Message: " + e.getMessage());
    }
}

From source file:gov.osti.services.Metadata.java

/**
 * Send an email notification on APPROVAL of DOE CODE records.
 *
 * @param md the METADATA to send notification for
 *///from  w w w .  j a  v a2s . c  o  m
private static void sendApprovalNotification(DOECodeMetadata md) {
    HtmlEmail email = new HtmlEmail();
    email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8);
    email.setHostName(EMAIL_HOST);

    // if HOST or record OWNER or PROJECT MANAGER NAME isn't set, cannot send
    if (StringUtils.isEmpty(EMAIL_HOST) || null == md || StringUtils.isEmpty(md.getOwner())
            || StringUtils.isEmpty(PM_NAME))
        return;
    // only has meaning for APPROVED records
    if (!Status.Approved.equals(md.getWorkflowStatus()))
        return;

    try {
        // get the OWNER information
        User owner = UserServices.findUserByEmail(md.getOwner());
        if (null == owner) {
            log.warn("Unable to locate USER information for Code ID: " + md.getCodeId());
            return;
        }

        Long codeId = md.getCodeId();

        // lookup previous Snapshot status info for item
        EntityManager em = DoeServletContextListener.createEntityManager();
        TypedQuery<MetadataSnapshot> querySnapshot = em
                .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class)
                .setParameter("status", DOECodeMetadata.Status.Approved).setParameter("codeId", codeId);

        String lastApprovalFor = "submitted/announced";
        List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();
        for (MetadataSnapshot ms : results) {
            lastApprovalFor = ms.getSnapshotKey().getSnapshotStatus().toString().toLowerCase();
        }

        String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", "");

        email.setFrom(EMAIL_FROM);
        email.setSubject("Approved -- DOE CODE ID: " + codeId + ", " + softwareTitle);
        email.addTo(md.getOwner());

        // if email is provided, BCC the Project Manager
        if (!StringUtils.isEmpty(PM_EMAIL))
            email.addBcc(PM_EMAIL, PM_NAME);

        StringBuilder msg = new StringBuilder();

        msg.append("<html>");
        msg.append("Dear ").append(owner.getFirstName()).append(" ").append(owner.getLastName()).append(":");

        msg.append("<P>Thank you -- your ").append(lastApprovalFor).append(" project, DOE CODE ID: <a href=\"")
                .append(SITE_URL).append("/biblio/").append(codeId).append("\">").append(codeId)
                .append("</a>, has been approved.  It is now <a href=\"").append(SITE_URL)
                .append("\">searchable</a> in DOE CODE by, for example, title or CODE ID #.</P>");

        // OMIT the following for BUSINESS TYPE software, or last ANNOUNCED software
        if (!DOECodeMetadata.Type.B.equals(md.getSoftwareType())
                && !lastApprovalFor.equalsIgnoreCase("announced")) {
            msg.append(
                    "<P>You may need to continue editing your project to announce it to the Department of Energy ")
                    .append("to ensure announcement and dissemination in accordance with DOE statutory responsibilities. For more information please see ")
                    .append("<a href=\"").append(SITE_URL)
                    .append("/faq#what-does-it-mean-to-announce\">What does it mean to announce scientific code to DOE CODE?</a></P>");
        }
        msg.append(
                "<P>If you have questions such as What are the benefits of getting a DOI for code or software?, see the ")
                .append("<a href=\"").append(SITE_URL).append("/faq\">DOE CODE FAQs</a>.</P>");
        msg.append(
                "<P>If we can be of assistance, please do not hesitate to <a href=\"mailto:doecode@osti.gov\">Contact Us</a>.</P>");
        msg.append("<P>Sincerely,</P>");
        msg.append("<P>").append(PM_NAME).append("<BR/>Product Manager for DOE CODE<BR/>USDOE/OSTI</P>");

        msg.append("</html>");

        email.setHtmlMsg(msg.toString());

        email.send();
    } catch (EmailException e) {
        log.error("Unable to send APPROVAL notification for #" + md.getCodeId());
        log.error("Message: " + e.getMessage());
    }
}

From source file:gov.osti.services.Metadata.java

/**
 * Send a POC email notification on SUBMISSION/APPROVAL of DOE CODE records.
 *
 * @param md the METADATA to send notification for
 *//*from   ww w .  jav  a2  s.  co  m*/
private static void sendPOCNotification(DOECodeMetadata md) {
    // if HOST or MD or PROJECT MANAGER NAME isn't set, cannot send
    if (StringUtils.isEmpty(EMAIL_HOST) || null == md || StringUtils.isEmpty(PM_NAME))
        return;

    Long codeId = md.getCodeId();
    String siteCode = md.getSiteOwnershipCode();
    Status workflowStatus = md.getWorkflowStatus();

    // if SITE OWNERSHIP isn't set, cannot send
    if (StringUtils.isEmpty(siteCode))
        return;

    // only applicable to APPROVED records
    if (!Status.Approved.equals(workflowStatus))
        return;

    // get the SITE information
    Site site = SiteServices.findSiteBySiteCode(siteCode);
    if (null == site) {
        log.warn("Unable to locate SITE information for SITE CODE: " + siteCode);
        return;
    }

    // lookup previous Snapshot status info for item
    EntityManager em = DoeServletContextListener.createEntityManager();
    TypedQuery<MetadataSnapshot> querySnapshot = em
            .createNamedQuery("MetadataSnapshot.findByCodeIdLastNotStatus", MetadataSnapshot.class)
            .setParameter("status", DOECodeMetadata.Status.Approved).setParameter("codeId", codeId);

    String lastApprovalFor = "submitted/announced";
    List<MetadataSnapshot> results = querySnapshot.setMaxResults(1).getResultList();
    for (MetadataSnapshot ms : results) {
        lastApprovalFor = ms.getSnapshotKey().getSnapshotStatus().toString().toLowerCase();
    }

    List<String> emails = site.getPocEmails();

    // if POC is setup
    if (emails != null && !emails.isEmpty()) {
        try {
            HtmlEmail email = new HtmlEmail();
            email.setCharset(org.apache.commons.mail.EmailConstants.UTF_8);
            email.setHostName(EMAIL_HOST);

            String lab = site.getLab();
            lab = lab.isEmpty() ? siteCode : lab;

            String softwareTitle = md.getSoftwareTitle().replaceAll("^\\h+|\\h+$", "");

            email.setFrom(EMAIL_FROM);
            email.setSubject("POC Notification -- " + workflowStatus + " -- DOE CODE ID: " + codeId + ", "
                    + softwareTitle);

            for (String pocEmail : emails)
                email.addTo(pocEmail);

            // if email is provided, BCC the Project Manager
            if (!StringUtils.isEmpty(PM_EMAIL))
                email.addBcc(PM_EMAIL, PM_NAME);

            StringBuilder msg = new StringBuilder();

            msg.append("<html>");
            msg.append("Dear Sir or Madam:");

            String biblioLink = SITE_URL + "/biblio/" + codeId;

            msg.append("<p>As a point of contact for ").append(lab)
                    .append(", we wanted to inform you that a software project, titled ").append(softwareTitle)
                    .append(", associated with your organization was ").append(lastApprovalFor)
                    .append(" to DOE CODE and assigned DOE CODE ID: ").append(codeId)
                    .append(".  This project record is discoverable in <a href=\"").append(SITE_URL)
                    .append("\">DOE CODE</a>, e.g. searching by the project title or DOE CODE ID #, and can be found here: <a href=\"")
                    .append(biblioLink).append("\">").append(biblioLink).append("</a></p>");

            msg.append(
                    "<p>If you have any questions, please do not hesitate to <a href=\"mailto:doecode@osti.gov\">Contact Us</a>.</p>");
            msg.append("<p>Sincerely,</p>");
            msg.append("<p>").append(PM_NAME).append("<br/>Product Manager for DOE CODE<br/>USDOE/OSTI</p>");

            msg.append("</html>");

            email.setHtmlMsg(msg.toString());

            email.send();
        } catch (EmailException e) {
            log.error("Unable to send POC notification to " + Arrays.toString(emails.toArray()) + " for #"
                    + md.getCodeId());
            log.error("Message: " + e.getMessage());
        }
    }
}

From source file:net.wildpark.dswp.supports.MailService.java

public boolean sendEmail(String to, String textBody) {
    try {//  w  w  w  . j  ava 2 s .c  o  m
        HtmlEmail email = new HtmlEmail();
        email.setCharset("utf-8");
        email.setHostName("mail.wildpark.net");
        email.setSmtpPort(25);
        email.setAuthenticator(new DefaultAuthenticator("informer@mksat.net", "22v5C728"));
        email.setFrom("informer@mksat.net");
        email.setSubject("Automatic message from darkside.wildpark.net");
        email.setHtmlMsg(textBody);
        email.addTo(to);
        email.send();
        logFacade.create(new Log("Sended mail " + to));
    } catch (EmailException ex) {
        logFacade.create(new Log("Error with mail sending", ex, LoggerLevel.ERROR));
        System.out.println(ex);
        return false;
    }
    return true;
}

From source file:ninja.postoffice.commonsmail.CommonsmailHelperImpl.java

/**
 * Creates a MultiPartEmail. Selects the correct implementation
 * regarding html (MultiPartEmail) and/or txt content or both.
 * //from   w  w w .  ja v  a 2  s  . com
 * Populates the mutlipart email accordingly with the txt / html content.
 */
@Override
public MultiPartEmail createMultiPartEmailWithContent(Mail mail) throws EmailException {

    MultiPartEmail multiPartEmail;

    // set if it is a txt or html mail:

    if (mail.getBodyHtml() == null || mail.getBodyHtml().equals("")) {

        multiPartEmail = new MultiPartEmail();
        multiPartEmail.setMsg(mail.getBodyText());

    } else if (mail.getBodyText() == null || mail.getBodyText().equals("")) {
        multiPartEmail = new HtmlEmail().setHtmlMsg(mail.getBodyHtml());
    } else {
        multiPartEmail = new HtmlEmail().setHtmlMsg(mail.getBodyHtml()).setTextMsg(mail.getBodyText());
    }

    // and return the nicely configured mail:
    return multiPartEmail;
}

From source file:nl.b3p.kaartenbalie.struts.Mailer.java

public ActionMessages send(ActionMessages errors)
        throws AddressException, MessagingException, IOException, Exception {

    HtmlEmail email = new HtmlEmail();

    String[] ds = null;//from   w w w  .  java 2s .c o  m
    if (mailTo != null && mailTo.trim().length() != 0) {
        ds = mailTo.split(",");
        for (int i = 0; i < ds.length; i++) {
            email.addTo(ds[i]);
        }
    }
    if (mailCc != null && mailCc.trim().length() != 0) {
        ds = mailCc.split(",");
        for (int i = 0; i < ds.length; i++) {
            email.addCc(ds[i]);
        }
    }
    if (mailBcc != null && mailBcc.trim().length() != 0) {
        ds = mailBcc.split(",");
        for (int i = 0; i < ds.length; i++) {
            email.addBcc(ds[i]);
        }
    }

    email.setFrom(mailFrom);
    email.setSubject(subject);
    email.setHostName(mailHost);

    if (isReturnReceipt()) {
        email.addHeader("Disposition-Notification-To", mailFrom);
    }

    if (attachmentName == null) {
        attachmentName = "attachment";
    }
    if (attachment != null) {
        URL attachUrl = null;
        try {
            attachUrl = new URL(attachment);
            email.attach(attachUrl, attachmentName, attachmentName);
        } catch (MalformedURLException mfue) {
        }
    }
    if (attachmentDataSource != null) {
        email.attach(attachmentDataSource, attachmentName, attachmentName);
    }

    email.setMsg(createHTML());

    // send the email
    email.send();

    return errors;
}

From source file:org.apache.kylin.common.util.MailService.java

/**
 * @param receivers// w  ww. j  av  a  2 s.c om
 * @param subject
 * @param content
 * @return true or false indicating whether the email was delivered successfully
 * @throws IOException
 */
public boolean sendMail(List<String> receivers, String subject, String content, boolean isHtmlMsg) {

    if (!enabled) {
        logger.info("Email service is disabled; this mail will not be delivered: " + subject);
        logger.info("To enable mail service, set 'kylin.job.notification-enabled=true' in kylin.properties");
        return false;
    }

    Email email = new HtmlEmail();
    email.setHostName(host);
    email.setStartTLSEnabled(starttlsEnabled);
    if (starttlsEnabled) {
        email.setSslSmtpPort(port);
    } else {
        email.setSmtpPort(Integer.valueOf(port));
    }

    if (username != null && username.trim().length() > 0) {
        email.setAuthentication(username, password);
    }

    //email.setDebug(true);
    try {
        for (String receiver : receivers) {
            email.addTo(receiver);
        }

        email.setFrom(sender);
        email.setSubject(subject);
        email.setCharset("UTF-8");
        if (isHtmlMsg) {
            ((HtmlEmail) email).setHtmlMsg(content);
        } else {
            ((HtmlEmail) email).setTextMsg(content);
        }
        email.send();
        email.getMailSession();

    } catch (EmailException e) {
        logger.error(e.getLocalizedMessage(), e);
        return false;
    }

    return true;
}

From source file:org.apache.nifi.processors.email.ConsumeEWS.java

public MimeMessage parseMessage(EmailMessage item) throws Exception {
    EmailMessage ewsMessage = item;//from  w ww .  ja v a  2  s .co  m
    final String bodyText = ewsMessage.getBody().toString();

    MultiPartEmail mm;

    if (ewsMessage.getBody().getBodyType() == BodyType.HTML) {
        mm = new HtmlEmail().setHtmlMsg(bodyText);
    } else {
        mm = new MultiPartEmail();
        mm.setMsg(bodyText);
    }
    mm.setHostName("NiFi-EWS");
    //from
    mm.setFrom(ewsMessage.getFrom().getAddress());
    //to recipients
    ewsMessage.getToRecipients().forEach(x -> {
        try {
            mm.addTo(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add TO recipient.", e);
        }
    });
    //cc recipients
    ewsMessage.getCcRecipients().forEach(x -> {
        try {
            mm.addCc(x.getAddress());
        } catch (EmailException e) {
            throw new ProcessException("Failed to add CC recipient.", e);
        }
    });
    //subject
    mm.setSubject(ewsMessage.getSubject());
    //sent date
    mm.setSentDate(ewsMessage.getDateTimeSent());
    //add message headers
    ewsMessage.getInternetMessageHeaders().forEach(x -> mm.addHeader(x.getName(), x.getValue()));

    //Any attachments
    if (ewsMessage.getHasAttachments()) {
        ewsMessage.getAttachments().forEach(x -> {
            try {
                FileAttachment file = (FileAttachment) x;
                file.load();

                ByteArrayDataSource bds = new ByteArrayDataSource(file.getContent(), file.getContentType());

                mm.attach(bds, file.getName(), "", EmailAttachment.ATTACHMENT);
            } catch (MessagingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    mm.buildMimeMessage();
    return mm.getMimeMessage();
}