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

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

Introduction

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

Prototype

public Email setFrom(final String email) throws EmailException 

Source Link

Document

Set the FROM field of the email to use the specified address.

Usage

From source file:com.jnd.sonar.analysisreport.AnalysisReportHelper.java

private void sendEmail(String reportname, Map<String, String> reportDataMap2) {
    try {/*from   w  ww  .  java  2 s . co  m*/

        // Create the email message
        //MultiPartEmail email = new MultiPartEmail();   
        StringBuilder strHtmlContentSummary = new StringBuilder();
        System.out.println("Analysis -  Sonar Email Notification");
        from = settings.getString("sonar.jd.smptp.username");
        System.out.println("from=>" + from);
        to_email = settings.getString("sonar.jd.smptp.to");
        System.out.println("to_email=>" + to_email);

        to_email_name = settings.getString("sonar.jd.smptp.to_name");
        System.out.println("to_email_name=>" + to_email_name);

        username = settings.getString("sonar.jd.smptp.username");
        System.out.println("username=>" + username);
        password = settings.getString("sonar.jd.smptp.password");
        System.out.println("password=>" + password);
        hostname = settings.getString("sonar.jd.smptp.host");
        System.out.println("hostname=>" + hostname);
        portno = settings.getString("sonar.jd.smptp.sslport");
        System.out.println("portno=>" + portno);
        setSSLOnConnectFlag = settings.getBoolean("sonar.jd.smptp.set_ssl_on_connect");
        System.out.println("setSSLOnConnectFlag=>" + String.valueOf(setSSLOnConnectFlag));
        subject = settings.getString("sonar.jd.smptp.subject");
        System.out.println("subject=>" + subject);
        message = settings.getString("sonar.jd.smptp.message");
        System.out.println("message=>" + message);

        // Create the email message
        HtmlEmail email = new HtmlEmail();
        email.setHostName(hostname);
        email.setSslSmtpPort(portno);
        if (!StringUtils.isBlank(username) || !StringUtils.isBlank(password)) {
            email.setAuthentication(username, password);
        }
        //email.setSSLOnConnect(setSSLOnConnectFlag);
        email.setSSL(setSSLOnConnectFlag);
        String[] addrs = StringUtils.split(to_email, "\t\r\n;, ");
        for (String addr : addrs) {
            email.addTo(addr);
        }
        //email.addTo(to_email,to_email_name);
        email.setFrom(from);
        email.setSubject(subject);
        //email.setMsg(message);

        // embed the image and get the content id   
        URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
        String cid = email.embed(url, "Apache logo - 1");

        System.out.println("Print Entries from Analysis Data Map.");
        int i = 1;
        strHtmlContentSummary.append("<html><body>The apache logo - <img src=\"cid:" + cid
                + "\"><br><br><br><b><center>Metric Information:-</center></b><br><table border='2'>");
        for (Map.Entry<String, String> entry : reportDataMap.entrySet()) {
            strHtmlContentSummary
                    .append("<tr><td>" + entry.getKey() + ":</td><td>" + entry.getValue() + "</td></tr>");
            i++;
        }
        strHtmlContentSummary.append("</table></body></html>");
        System.out.println(strHtmlContentSummary.toString());
        // set the html message
        email.setHtmlMsg(strHtmlContentSummary.toString());
        // set the alternative message
        email.setTextMsg("Your email client does not support HTML messages");

        // Create the attachment
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath(reportname);

        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("Sonar Analysis Report" + reportname);
        attachment.setName(reportname);
        email.attach(attachment);
        // send the email
        System.out.println("Sending the Email");
        email.send();
    } catch (EmailException e) {
        throw new SonarException("Unable to send email", e);
    } catch (Exception ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

}

From source file:com.smi.travel.util.Mail.java

public String sendmailwithAttchfile(String sendTo, String subject, String content, String attachfile,
        String sendCc) throws EmailException {
    String result = "";
    boolean send = false;
    EmailAttachment attachment = new EmailAttachment();
    HtmlEmail email = new HtmlEmail();
    try {/*from w w w.  j  av a 2  s  .c o m*/
        if ((attachfile != null) && (!attachfile.equalsIgnoreCase(""))) {
            //attachment.setPath("C:\\Users\\Surachai\\Documents\\NetBeansProjects\\SMITravel\\test.txt");
            attachment.setPath(attachfile);
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setDescription("file attachment");
            attachment.setName("text.txt");
            email.attach(attachment);
        }
        send = true;
    } catch (EmailException ex) {
        System.out.println("Email Exception");
        ex.printStackTrace();
        result = "fail";
    }
    if (send) {
        System.out.println(mail.getUsername() + mail.getPassword());
        email.setHostName(mail.getHostname());
        email.setSmtpPort(mail.getPort());
        email.setAuthentication(mail.getUsername(), mail.getPassword());
        email.setSSLOnConnect(true);
        email.setFrom(mail.getUsername());
        email.setSubject(subject);
        email.setHtmlMsg(content);
        String[] toSplit = sendTo.split("\\,");
        for (int i = 0; i < toSplit.length; i++) {
            System.out.println("Print toSplit" + toSplit[i]);
            email.addTo(toSplit[i]);
        }
        if (!sendCc.isEmpty()) {
            String[] ccSplit = sendCc.split("\\,");
            for (int i = 0; i < ccSplit.length; i++) {
                System.out.println("Print ccSplit" + ccSplit[i]);
                email.addCc(ccSplit[i]);
            }
        }
        email.send();

        result = "success";

    }
    return result;
}

From source file:br.ufg.reqweb.components.MailBean.java

public void sendMailToDiscente(final Requerimento requerimento) {
    Thread sender = new Thread() {
        @Override//from   www .  j a v a  2 s . c om
        public void run() {
            try {
                Configuration templateConf = new Configuration();
                templateConf.setObjectWrapper(new DefaultObjectWrapper());
                templateConf.setDefaultEncoding("UTF-8");
                templateConf.setDirectoryForTemplateLoading(new File(context.getRealPath("/reports/mail")));
                Map objectRoot = new HashMap();
                objectRoot.put("TITULO", LocaleBean.getDefaultMessageBundle().getString("appTitle"));
                objectRoot.put("DISCENTE", LocaleBean.getDefaultMessageBundle().getString("discente"));
                objectRoot.put("REQUERIMENTO", LocaleBean.getDefaultMessageBundle().getString("requerimento"));
                objectRoot.put("STATUS", LocaleBean.getDefaultMessageBundle().getString("status"));
                objectRoot.put("ATENDENTE", LocaleBean.getDefaultMessageBundle().getString("atendente"));
                objectRoot.put("OBSERVACAO", LocaleBean.getDefaultMessageBundle().getString("observacao"));
                objectRoot.put("matricula", requerimento.getDiscente().getMatricula());
                objectRoot.put("discente", requerimento.getDiscente().getNome());
                objectRoot.put("tipoRequerimento", LocaleBean.getDefaultMessageBundle()
                        .getString(requerimento.getTipoRequerimento().getTipo()));
                objectRoot.put("status",
                        LocaleBean.getDefaultMessageBundle().getString(requerimento.getStatus().getStatus()));
                objectRoot.put("atendente", requerimento.getAtendimento().getAtendente().getNome());
                objectRoot.put("observacao", requerimento.getAtendimento().getObservacao());
                URL logo = new File(context.getRealPath("/resources/img/logo-mono-mini.png")).toURI().toURL();
                Template template = templateConf.getTemplate("notificacao_discente.ftl");
                Writer writer = new StringWriter();
                HtmlEmail email = new HtmlEmail();
                String logoId = email.embed(logo, "logo");
                objectRoot.put("logo", logoId);
                template.process(objectRoot, writer);
                email.setHostName(configDao.getValue("mail.mailHost"));
                email.setSmtpPort(Integer.parseInt(configDao.getValue("mail.smtpPort")));
                String mailSender = configDao.getValue("mail.mailSender");
                String user = configDao.getValue("mail.mailUser");
                String password = configDao.getValue("mail.mailPassword");
                boolean useSSL = Boolean.parseBoolean(configDao.getValue("mail.useSSL"));
                email.setAuthenticator(new DefaultAuthenticator(user, password));
                email.setSSLOnConnect(useSSL);
                email.setFrom(mailSender);
                email.addTo(requerimento.getDiscente().getEmail());
                email.setSubject(LocaleBean.getDefaultMessageBundle().getString("subjectMail"));
                email.setHtmlMsg(writer.toString());
                String alternativeMessage = String.format("%s\n%s: %s\n%s: %s\n%s: %s\n%s: %s",
                        LocaleBean.getDefaultMessageBundle().getString("messageMail"),
                        objectRoot.get("REQUERIMENTO"), objectRoot.get("tipoRequerimento"),
                        objectRoot.get("STATUS"), objectRoot.get("status"), objectRoot.get("ATENDENTE"),
                        objectRoot.get("atendente"), objectRoot.get("OBSERVACAO"),
                        objectRoot.get("observacao"));
                email.setTextMsg(alternativeMessage);
                email.send();
                System.out.println(String.format("message to discente:<%s: %s>",
                        requerimento.getDiscente().getNome(), requerimento.getDiscente().getEmail()));
            } catch (EmailException | IOException | TemplateException e) {
                System.out.println("erro ao enviar email");
                System.out.println(e);
            }
        }
    };
    sender.start();
}

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;/*w ww.  j  a 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:fr.gouv.culture.thesaurus.util.MailUtil.java

/**
 * /*from  w  w w  .  jav  a  2 s  .  c o m*/
 * Envoi l'email.
 * 
 * @throws EmailException
 *             Erreur lors de l'envoi de l'email.
 */
public void send() throws EmailException {

    if (hostProperty == null) {
        log.error("Session email non initialise : envoi des emails impossible.");
        return;
    }

    HtmlEmail email = new HtmlEmail();
    email.setHostName(hostProperty);

    // To
    if (to != null) {
        for (String adresse : to) {
            email.addTo(adresse);
        }
    }

    // Cc
    if (cc != null) {
        for (String adresse : cc) {
            email.addCc(adresse);
        }
    }

    // Cci
    if (cci != null) {
        for (String adresse : cci) {
            email.addBcc(adresse);
        }
    }

    // Subject
    email.setSubject(subjectPrefix != null ? subjectPrefix + subject : subject);

    // From
    email.setFrom(StringUtils.isNotEmpty(from) ? from : defaultFrom);

    // Message & Html
    if (message != null) {
        email.setTextMsg(message);
    }
    if (html != null) {
        email.setHtmlMsg(html);
    }

    if (StringUtils.isNotEmpty(this.charset)) {
        email.setCharset(this.charset);
    }

    email.buildMimeMessage();

    // Attachments
    for (AttachmentBean attachement : attachments) {
        email.attach(attachement.getDataSource(), attachement.getName(), attachement.getDescription());
    }

    email.sendMimeMessage();

}

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
 *///  w  ww . j a  v  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:gov.osti.services.Metadata.java

/**
 * Send a NOTIFICATION EMAIL (if configured) when a record is SUBMITTED or
 * ANNOUNCED.//from  w  w  w  . jav  a 2 s.c  o  m
 *
 * @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 va 2  s  .  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:net.wildpark.dswp.supports.MailService.java

public boolean sendEmail(String to, String textBody) {
    try {//from w  w w  .ja  v  a2s .  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:nl.b3p.kaartenbalie.struts.Mailer.java

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

    HtmlEmail email = new HtmlEmail();

    String[] ds = null;/*  w ww .jav  a 2 s. 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;
}