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

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

Introduction

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

Prototype

public void setCharset(final String newCharset) 

Source Link

Document

Set the charset of the message.

Usage

From source file:com.duroty.application.chat.manager.ChatManager.java

/**
 * DOCUMENT ME!/*w  w w . j ava 2  s  .co  m*/
 *
 * @param hsession DOCUMENT ME!
 * @param userSender DOCUMENT ME!
 * @param userRecipient DOCUMENT ME!
 */
private void sendMail(Session hsession, javax.mail.Session msession, Users userSender, Users userRecipient,
        String message) {
    try {
        String sender = userSender.getUseUsername();
        String recipient = userRecipient.getUseUsername();

        Identity identitySender = getIdentity(hsession, userSender);
        Identity identityRecipient = getIdentity(hsession, userRecipient);

        HtmlEmail email = new HtmlEmail();
        InternetAddress _from = new InternetAddress(identitySender.getIdeEmail(), identitySender.getIdeName());
        InternetAddress _replyTo = new InternetAddress(identitySender.getIdeReplyTo(),
                identitySender.getIdeName());
        InternetAddress[] _to = MessageUtilities.encodeAddresses(identityRecipient.getIdeEmail(), null);

        if (_from != null) {
            email.setFrom(_from.getAddress(), _from.getPersonal());
        }

        if (_replyTo != null) {
            email.addReplyTo(_replyTo.getAddress(), _replyTo.getPersonal());
        }

        if ((_to != null) && (_to.length > 0)) {
            HashSet aux = new HashSet(_to.length);
            Collections.addAll(aux, _from);
            Collections.addAll(aux, _to);
            email.setTo(aux);
        }

        email.setCharset(charset);
        email.setSubject("Chat " + sender + " >> " + recipient);
        email.setHtmlMsg(message);

        calendar.setTime(new Date());

        String minute = "30";

        if (calendar.get(Calendar.MINUTE) >= 30) {
            minute = "60";
        }

        String value = String.valueOf(calendar.get(Calendar.YEAR))
                + String.valueOf(calendar.get(Calendar.MONTH)) + String.valueOf(calendar.get(Calendar.DATE))
                + String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)) + minute
                + String.valueOf(userSender.getUseIdint() + userRecipient.getUseIdint());
        String reference = "<" + value + ".JavaMail.duroty@duroty" + ">";
        email.addHeader(RFC2822Headers.IN_REPLY_TO, reference);
        email.addHeader(RFC2822Headers.REFERENCES, reference);

        email.addHeader("X-DBox", "CHAT");

        Date now = new Date();
        email.setSentDate(now);

        email.setMailSession(msession);
        email.buildMimeMessage();

        MimeMessage mime = email.getMimeMessage();

        int size = MessageUtilities.getMessageSize(mime);

        if (controlQuota(hsession, userSender, size)) {
            //messageable.saveSentMessage(null, mime, userSender);
            Thread thread = new Thread(new SendMessageThread(email));
            thread.start();
        }
    } catch (UnsupportedEncodingException e) {
    } catch (MessagingException e) {
    } catch (EmailException e) {
    } catch (Exception e) {
    }
}

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

/**
 * Send a NOTIFICATION EMAIL (if configured) when a record is SUBMITTED or
 * ANNOUNCED.// ww w  .  ja v  a 2  s . co  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   ww w .  j a  v a2 s .  co  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 w  ww  .ja  v  a  2s. 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:fr.gouv.culture.thesaurus.util.MailUtil.java

/**
 * /*w  w w . j a v a2s  .  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:net.wildpark.dswp.supports.MailService.java

public boolean sendEmail(String to, String textBody) {
    try {/*ww  w  .  java2  s.c om*/
        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:org.chenillekit.mail.services.impl.MailServiceImpl.java

/**
 * send a HTML message.// w w  w. j a va 2  s. com
 *
 * @param headers    the mail headers
 * @param htmlBody   the mail body (HTML based)
 * @param dataSources array of data sources to attach at this mail
 *
 * @return true if mail successfull send
 */
public boolean sendHtmlMail(MailMessageHeaders headers, String htmlBody, DataSource... dataSources) {
    try {
        HtmlEmail email = new HtmlEmail();

        setEmailStandardData(email);

        setMailMessageHeaders(email, headers);

        if (dataSources != null) {
            for (DataSource dataSource : dataSources)
                email.attach(dataSource, dataSource.getName(), dataSource.getName());
        }

        email.setCharset(headers.getCharset());
        email.setHtmlMsg(htmlBody);

        String msgId = email.send();

        return true;
    } catch (EmailException e) {
        // FIXME Handle gracefully
        throw new RuntimeException(e);
    }
}

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

/**
 *
 * @param from the sender of the email./*from   w  ww  .j  a  v  a 2  s  .  c  om*/
 * @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 {//from  w  ww . ja  v a  2 s . co  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.opencron.server.service.NoticeService.java

public void sendMessage(List<User> users, Long workId, String emailAddress, String mobiles, String content) {
    Log log = new Log();
    log.setIsread(false);//from   w w w  .j  a  va2s  .c om
    log.setAgentId(workId);
    log.setMessage(content);
    //???
    if (CommonUtils.isEmpty(emailAddress, mobiles)) {
        log.setType(Opencron.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
        return;
    }

    /**
     * ????
     */
    boolean emailSuccess = false;
    boolean mobileSuccess = false;

    Config config = configService.getSysConfig();
    try {
        log.setType(Opencron.MsgType.EMAIL.getValue());
        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("opencron");
        email.setHtmlMsg(msgToHtml(content));
        email.addTo(emailAddress.split(","));
        email.send();
        emailSuccess = true;
        /**
         * ??
         */
        log.setReceiver(emailAddress);
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ????
     */
    try {
        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.setResult(message);
            logger.info(message);
            mobileSuccess = true;
        }
        log.setReceiver(mobiles);
        log.setType(Opencron.MsgType.SMS.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ??,??
     */
    if (!mobileSuccess && !emailSuccess) {
        log.setType(Opencron.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        for (User user : users) {
            //??
            log.setUserId(user.getUserId());
            log.setReceiver(user.getUserName());
            homeService.saveLog(log);
        }
    }

}