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

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

Introduction

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

Prototype

public void setHostName(final String aHostName) 

Source Link

Document

Set the hostname of the outgoing mail server.

Usage

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 www. j av  a 2 s  .  c o  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 {/*from   w  w  w  . j  a v  a2s  .com*/
        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:nl.b3p.kaartenbalie.struts.Mailer.java

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

    HtmlEmail email = new HtmlEmail();

    String[] ds = null;/* w  w w. j  a  v a2 s  .co  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.unomi.plugins.mail.actions.SendMailAction.java

public int execute(Action action, Event event) {
    String from = (String) action.getParameterValues().get("from");
    String to = (String) action.getParameterValues().get("to");
    String cc = (String) action.getParameterValues().get("cc");
    String bcc = (String) action.getParameterValues().get("bcc");
    String subject = (String) action.getParameterValues().get("subject");
    String template = (String) action.getParameterValues().get("template");

    ST stringTemplate = new ST(template);
    stringTemplate.add("profile", event.getProfile());
    stringTemplate.add("event", event);
    // load your HTML email template
    String htmlEmailTemplate = stringTemplate.render();

    // define you base URL to resolve relative resource locations
    try {//  w  w  w . j a  va2 s  .c o  m
        new URL("http://www.apache.org");
    } catch (MalformedURLException e) {
        //
    }

    // create the email message
    HtmlEmail email = new ImageHtmlEmail();
    // email.setDataSourceResolver(new DataSourceResolverImpl(url));
    email.setHostName(mailServerHostName);
    email.setSmtpPort(mailServerPort);
    email.setAuthenticator(new DefaultAuthenticator(mailServerUsername, mailServerPassword));
    email.setSSLOnConnect(mailServerSSLOnConnect);
    try {
        email.addTo(to);
        email.setFrom(from);
        if (cc != null && cc.length() > 0) {
            email.addCc(cc);
        }
        if (bcc != null && bcc.length() > 0) {
            email.addBcc(bcc);
        }
        email.setSubject(subject);

        // set the html message
        email.setHtmlMsg(htmlEmailTemplate);

        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // send the email
        email.send();
    } catch (EmailException e) {
        logger.error("Cannot send mail", e);
    }

    return EventService.NO_CHANGE;
}

From source file:org.cerberus.service.email.impl.sendMail.java

public static void sendHtmlMail(String host, int port, String body, String subject, String from, String to,
        String cc) throws Exception {

    HtmlEmail email = new HtmlEmail();
    email.setSmtpPort(port);/*from w ww.  j  av a 2 s  . c  o m*/
    email.setDebug(false);
    email.setHostName(host);
    email.setFrom(from);
    email.setSubject(subject);
    email.setHtmlMsg(body);

    String[] destinataire = to.split(";");

    for (int i = 0; i < destinataire.length; i++) {
        String name;
        String emailaddress;
        if (destinataire[i].contains("<")) {
            String[] destinatairedata = destinataire[i].split("<");
            name = destinatairedata[0].trim();
            emailaddress = destinatairedata[1].replace(">", "").trim();
        } else {
            name = "";
            emailaddress = destinataire[i];
        }
        email.addTo(emailaddress, name);
    }

    String[] copy = cc.split(";");

    for (int i = 0; i < copy.length; i++) {
        String namecc;
        String emailaddresscc;
        if (copy[i].contains("<")) {
            String[] copydata = copy[i].split("<");
            namecc = copydata[0].trim();
            emailaddresscc = copydata[1].replace(">", "").trim();
        } else {
            namecc = "";
            emailaddresscc = copy[i];
        }
        email.addCc(emailaddresscc, namecc);
    }

    email.setTLS(true);

    email.send();

}

From source file:org.gravidence.gravifon.email.ApacheCommonsEmailSender.java

@Override
public boolean send(String toAddress, String toName, String subject, String htmlMessage, String textMessage) {
    HtmlEmail email = new HtmlEmail();

    email.setHostName(host);
    email.setSslSmtpPort(port);//  w w  w. java  2  s  .co  m
    email.setAuthenticator(new DefaultAuthenticator(username, password));
    email.setSSLOnConnect(true);

    try {
        if (StringUtils.isBlank(toName)) {
            email.addTo(toAddress);
        } else {
            email.addTo(toAddress, toName);
        }
        email.setFrom(fromAddress, fromName);

        email.setSubject(subject);

        if (htmlMessage != null) {
            email.setHtmlMsg(htmlMessage);
        }
        if (textMessage != null) {
            email.setTextMsg(textMessage);
        }

        email.send();
    } catch (EmailException ex) {
        // TODO think about throwing GravifonException
        LOGGER.warn(String.format("Failed to send an email to %s", toAddress), ex);

        return false;
    }

    return true;
}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 *
 * @param from the sender of the email.//from w w  w. j av a  2  s.c o  m
 * @param to the recipient of the email.
 * @param subject the subject of the email.
 * @param content the body of the email.
 * @throws SystemException if the email couldn't be sent due to some mail server exception.
 */
public void sendHTML(String from, String to, String cc, String bcc, String bounceAddress, String replyTo,
        String subject, String content, String encoding) throws SystemException {
    try {
        HtmlEmail email = new HtmlEmail();
        String mailServer = CmsPropertyHandler.getMailSmtpHost();
        String mailPort = CmsPropertyHandler.getMailSmtpPort();
        String systemEmailSender = CmsPropertyHandler.getSystemEmailSender();

        email.setHostName(mailServer);
        if (mailPort != null && !mailPort.equals(""))
            email.setSmtpPort(Integer.parseInt(mailPort));

        boolean needsAuthentication = false;
        try {
            needsAuthentication = new Boolean(CmsPropertyHandler.getMailSmtpAuth()).booleanValue();
        } catch (Exception ex) {
            needsAuthentication = false;
        }

        if (needsAuthentication) {
            final String userName = CmsPropertyHandler.getMailSmtpUser();
            final String password = CmsPropertyHandler.getMailSmtpPassword();

            email.setAuthentication(userName, password);
        }

        email.setBounceAddress(systemEmailSender);
        email.setCharset(encoding);

        if (logger.isInfoEnabled()) {
            logger.info("systemEmailSender:" + systemEmailSender);
            logger.info("to:" + to);
            logger.info("from:" + from);
            logger.info("mailServer:" + mailServer);
            logger.info("mailPort:" + mailPort);
            logger.info("cc:" + cc);
            logger.info("bcc:" + bcc);
            logger.info("replyTo:" + replyTo);
            logger.info("subject:" + subject);
        }

        if (to.indexOf(";") > -1) {
            cc = to;
            to = from;
        }

        String limitString = CmsPropertyHandler.getEmailRecipientLimit();
        if (limitString != null && !limitString.equals("-1")) {
            try {
                Integer limit = new Integer(limitString);
                int count = 0;
                if (cc != null)
                    count = count + cc.split(";").length;
                if (bcc != null)
                    count = count + bcc.split(";").length;

                logger.info("limit: " + limit + ", count: " + count);
                if (count > limit)
                    throw new Exception("You are not allowed to send mail to more than " + limit
                            + " recipients at a time. This is specified in app settings.");
            } catch (NumberFormatException e) {
                logger.error("Exception validating number of recipients in mailservice:" + e.getMessage(), e);
            }
        }

        email.addTo(to, to);
        email.setFrom(from, from);
        if (cc != null)
            email.setCc(createInternetAddressesList(cc));
        if (bcc != null)
            email.setBcc(createInternetAddressesList(bcc));
        if (replyTo != null)
            email.setReplyTo(createInternetAddressesList(replyTo));

        email.setSubject(subject);

        email.setHtmlMsg(content);

        email.setTextMsg("Your email client does not support HTML messages");

        email.send();

        logger.info("Email sent!");
    } catch (Exception e) {
        logger.error("An error occurred when we tried to send this mail:" + e.getMessage(), e);
        throw new SystemException("An error occurred when we tried to send this mail:" + e.getMessage(), e);
    }
}

From source file:org.jcronjob.service.NoticeService.java

public void sendMessage(Long receiverId, Long workId, String emailAddress, String mobiles, String content) {
    try {/*  w  ww  .  j ava2 s  .  c o  m*/
        HtmlEmail email = new HtmlEmail();
        email.setCharset("UTF-8");
        email.setHostName(config.getSmtpHost());
        email.setSslSmtpPort(config.getSmtpPort().toString());
        email.setAuthentication(config.getSenderEmail(), config.getPassword());
        email.setFrom(config.getSenderEmail());
        email.setSubject("cronjob");
        email.setHtmlMsg(msgToHtml(receiverId, content));
        email.addTo(emailAddress.split(","));
        email.send();

        Log log = new Log();
        log.setType(0);
        log.setWorkerId(workId);
        log.setMessage(content);
        for (String receiver : emailAddress.split(",")) {
            log.setReceiver(receiver);
            log.setSendTime(new Date());
            homeService.saveLog(log);
        }
        log.setType(1);
        for (String mobile : mobiles.split(",")) {
            //??POST
            String sendUrl = String.format(config.getSendUrl(), mobile,
                    String.format(config.getTemplate(), content));

            String url = sendUrl.substring(0, sendUrl.indexOf("?"));
            String postData = sendUrl.substring(sendUrl.indexOf("?") + 1);

            String message = HttpUtils.doPost(url, postData, "UTF-8");
            log.setReceiver(mobile);
            log.setResult(message);
            log.setSendTime(new Date());
            homeService.saveLog(log);
            logger.info(message);

        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

}

From source file:org.jevis.jealarm.AlarmHandler.java

/**
 * Send the Alarm mail/*w  w w.  ja va  2  s  .co m*/
 *
 * @param conf
 * @param alarm
 * @param body
 */
public void sendAlarm(Config conf, Alarm alarm, String body) {
    try {
        HtmlEmail email = new HtmlEmail();

        //            Email email = new SimpleEmail();
        email.setHostName(conf.getSmtpServer());
        email.setSmtpPort(conf.getSmtpPort());
        email.setAuthenticator(new DefaultAuthenticator(conf.getSmtpUser(), conf.getSmtpPW()));
        email.setSSLOnConnect(conf.isSmtpSSL());
        email.setFrom(conf.smtpFrom);
        email.setSubject(alarm.getSubject());

        for (String recipient : alarm.getRecipient()) {
            email.addTo(recipient);
        }

        for (String bcc : alarm.getBcc()) {
            email.addBcc(bcc);
        }
        email.setHtmlMsg(body);

        email.send();
        System.out.println("Alarm send: " + alarm.getSubject());
    } catch (Exception ex) {
        System.out.println("cound not send Email");
        ex.printStackTrace();
    }

}

From source file:org.jkandasa.email.blaster.EmailUtils.java

public static HtmlEmail initializeEmail(AppProperties appProperties) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setHostName(appProperties.getSmtpHost());
    email.setSmtpPort(Integer.valueOf(appProperties.getSmtpPort()));
    if (appProperties.getUsername() != null && appProperties.getUsername().length() > 0) {
        email.setAuthenticator(//  ww  w. j  ava  2s  .  co m
                new DefaultAuthenticator(appProperties.getUsername(), appProperties.getPassword()));
    }
    email.setSSLOnConnect(appProperties.isEnableSSL());
    email.setFrom(appProperties.getFromAddress());
    return email;
}