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.ms.commons.message.impl.sender.AbstractEmailSender.java

private MultiPartEmail makeHtmlEmail(MsunMail mail, String charset) throws EmailException {
    HtmlEmail email = new HtmlEmail();
    email.setCharset(charset);
    if (!StringUtils.isEmpty(mail.getMessage())) {
        email.setTextMsg(mail.getMessage());
    }/*ww w  . ja va  2 s.c  o m*/
    email.setHtmlMsg(mail.getHtmlMessage());
    return email;
}

From source file:com.jredrain.service.NoticeService.java

public void sendMessage(Long receiverId, Long workId, String emailAddress, String mobiles, String content) {
    Log log = new Log();
    log.setIsread(0);/*from   ww w .jav a 2  s.  c  o  m*/
    log.setAgentId(workId);
    log.setMessage(content);
    //???
    if (CommonUtils.isEmpty(emailAddress, mobiles)) {
        log.setType(RedRain.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
        return;
    }

    /**
     * ????
     */
    boolean emailSuccess = false;
    boolean mobileSuccess = false;
    try {
        log.setType(RedRain.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("redrain");
        email.setHtmlMsg(msgToHtml(receiverId, 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(RedRain.MsgType.SMS.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    /**
     * ??,??
     */
    if (!mobileSuccess && !emailSuccess) {
        log.setType(RedRain.MsgType.WEBSITE.getValue());
        log.setSendTime(new Date());
        homeService.saveLog(log);
    }

}

From source file:com.esofthead.mycollab.module.mail.DefaultMailer.java

private HtmlEmail getBasicEmail(String fromEmail, String fromName, List<MailRecipientField> toEmail,
        List<MailRecipientField> ccEmail, List<MailRecipientField> bccEmail, String subject, String html) {
    try {/*from   ww w  .  ja va 2 s  .c om*/
        HtmlEmail email = new HtmlEmail();
        email.setHostName(host);
        email.setFrom(fromEmail, fromName);
        email.setCharset(EmailConstants.UTF_8);
        for (int i = 0; i < toEmail.size(); i++) {
            if (isValidate(toEmail.get(i).getEmail()) && isValidate(toEmail.get(i).getName())) {
                email.addTo(toEmail.get(i).getEmail(), toEmail.get(i).getName());
            } else {
                LOG.error("Invalid to email input: " + toEmail.get(i).getEmail() + "---"
                        + toEmail.get(i).getName());
            }
        }

        if (CollectionUtils.isNotEmpty(ccEmail)) {
            for (int i = 0; i < ccEmail.size(); i++) {
                if (isValidate(ccEmail.get(i).getEmail()) && isValidate(ccEmail.get(i).getName())) {
                    email.addCc(ccEmail.get(i).getEmail(), ccEmail.get(i).getName());
                } else {
                    LOG.error("Invalid cc email input: " + ccEmail.get(i).getEmail() + "---"
                            + ccEmail.get(i).getName());
                }
            }
        }

        if (CollectionUtils.isNotEmpty(bccEmail)) {
            for (int i = 0; i < bccEmail.size(); i++) {
                if (isValidate(bccEmail.get(i).getEmail()) && isValidate(bccEmail.get(i).getName())) {
                    email.addBcc(bccEmail.get(i).getEmail(), bccEmail.get(i).getName());
                } else {
                    LOG.error("Invalid bcc email input: " + bccEmail.get(i).getEmail() + "---"
                            + bccEmail.get(i).getName());
                }
            }
        }

        if (username != null) {
            email.setAuthentication(username, password);
        }
        email.setStartTLSEnabled(isTLS);
        email.setSubject(subject);

        if (StringUtils.isNotBlank(html)) {
            email.setHtmlMsg(html);
        }

        return email;
    } catch (EmailException e) {
        throw new MyCollabException(e);
    }
}

From source file:com.ipc.service.SignUpService.java

public String sendhtmlmail(int uid, String key, String email) throws IOException, EmailException {
    HtmlEmail sendemail = new HtmlEmail();
    sendemail.setCharset("euc-kr");
    sendemail.setHostName("smtp.worksmobile.com");
    sendemail.addTo(email);/*  w w  w  .  j  ava  2  s  . c om*/
    sendemail.setFrom("jinuk@ideaconcert.com", "");
    sendemail.setSubject("?  ?? ?.");
    sendemail.setAuthentication("jinuk@ideaconcert.com", "tpxmapsb1");
    sendemail.setSmtpPort(465);
    sendemail.setSSL(true); //?
    sendemail.setTLS(true);
    sendemail.setDebug(true);
    String htmlmsg = "<html><div style='width:1000px; float:left; border-bottom:2px solid #45d4fe; padding-bottom:5px;box-sizing:border-box;'></div><div style='width:1000px;float:left; box-sizing:border-box; padding:15px;'><h2>? ?  ? .</h2><div style='width:100%; float:left; box-sizing:border-box; border:5px solid #f9f9f9; text-align:center; padding:40px 0 40px 0;'><span>   ? .</span><br><a href='http://localhost:8088/signup/permit?uid="
            + uid + "&key=" + key
            + "'><button style='width:150px; height:40px; background:none; border:2px solid #45d4fe; font-size:1.1rem; text-decoration: none;font-weight:bold; margin-top:10px;'></button></a></div></div></html>";
    System.out.println(htmlmsg);
    sendemail.setHtmlMsg(htmlmsg);
    try {
        sendemail.send();
    } catch (Exception e) {
        System.out.println("NOTOK");
        return "NOTOK";
    }
    return "OK";
}

From source file:com.ipc.service.SignUpService.java

public String sendpwmail(int uid, String key, String email) throws IOException, EmailException {
    System.out.println("Email : " + email);
    HtmlEmail sendemail = new HtmlEmail();
    sendemail.setCharset("euc-kr");
    sendemail.setHostName("smtp.worksmobile.com");
    sendemail.addTo(email);//from  w w  w  .  ja v  a 2s  . co  m
    sendemail.setFrom("jinuk@ideaconcert.com", "");
    sendemail.setSubject("?  .");
    sendemail.setAuthentication("jinuk@ideaconcert.com", "tpxmapsb1");
    sendemail.setSmtpPort(465);
    sendemail.setSSL(true); //?
    sendemail.setTLS(true);
    sendemail.setDebug(true);
    String htmlmsg = "<html><div style='width:1000px; float:left; border-bottom:2px solid #45d4fe; padding-bottom:5px;box-sizing:border-box;'></div><div style='width:1000px;float:left; box-sizing:border-box; padding:15px;'><h2>?   .</h2><div style='width:100%; float:left; box-sizing:border-box; border:5px solid #f9f9f9; text-align:center; padding:40px 0 40px 0;'><span>  ?  <br> .<br>"
            + key + "</span></html>";
    System.out.println(htmlmsg);
    sendemail.setHtmlMsg(htmlmsg);
    try {
        sendemail.send();
    } catch (Exception e) {
        System.out.println("NOTOK");
        return "NOTOK";
    }
    return "OK";
}

From source file:io.mif.labanorodraugai.services.EmailService.java

private void setUpHtmlEmail(HtmlEmail email) throws EmailException {
    email.setHostName("smtp.googlemail.com");
    email.setSmtpPort(465);/*w  w w. j a  va 2s . c  o m*/
    email.setAuthenticator(new DefaultAuthenticator("labanorodraugaibendrija@gmail.com", "labanoro123"));
    email.setSSLOnConnect(true);
    email.setCharset("UTF-8");
    email.setFrom("labanorodraugaibendrija@gmail.com", "Labanoro draugai");
}

From source file:de.cosmocode.palava.services.mail.EmailFactory.java

@SuppressWarnings("unchecked")
Email build(Document document, Embedder embed) throws EmailException, FileNotFoundException {
    /* CHECKSTYLE:ON */

    final Element root = document.getRootElement();

    final List<Element> messages = root.getChildren("message");
    if (messages.isEmpty())
        throw new IllegalArgumentException("No messages found");

    final List<Element> attachments = root.getChildren("attachment");

    final Map<ContentType, String> available = new HashMap<ContentType, String>();

    for (Element element : messages) {
        final String type = element.getAttributeValue("type");
        final ContentType messageType = StringUtils.equals(type, "html") ? ContentType.HTML : ContentType.PLAIN;
        if (available.containsKey(messageType)) {
            throw new IllegalArgumentException("Two messages with the same types have been defined.");
        }//from w ww .  j a v a 2s  . c  o m
        available.put(messageType, element.getText());
    }

    final Email email;

    if (available.containsKey(ContentType.HTML) || attachments.size() > 0) {
        final HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setCharset(CHARSET);

        if (embed.hasEmbeddings()) {
            htmlEmail.setSubType("related");
        } else if (attachments.size() > 0) {
            htmlEmail.setSubType("related");
        } else {
            htmlEmail.setSubType("alternative");
        }

        /**
         * Add html message
         */
        if (available.containsKey(ContentType.HTML)) {
            htmlEmail.setHtmlMsg(available.get(ContentType.HTML));
        }

        /**
         * Add plain text alternative
         */
        if (available.containsKey(ContentType.PLAIN)) {
            htmlEmail.setTextMsg(available.get(ContentType.PLAIN));
        }

        /**
         * Embedded binary data
         */
        for (Map.Entry<String, String> entry : embed.getEmbeddings().entrySet()) {
            final String path = entry.getKey();
            final String cid = entry.getValue();
            final String name = embed.name(path);

            final File file;

            if (path.startsWith(File.separator)) {
                file = new File(path);
            } else {
                file = new File(embed.getResourcePath(), path);
            }

            if (file.exists()) {
                htmlEmail.embed(new FileDataSource(file), name, cid);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        /**
         * Attached binary data
         */
        for (Element attachment : attachments) {
            final String name = attachment.getAttributeValue("name", "");
            final String description = attachment.getAttributeValue("description", "");
            final String path = attachment.getAttributeValue("path");

            if (path == null)
                throw new IllegalArgumentException("Attachment path was not set");
            File file = new File(path);

            if (!file.exists())
                file = new File(embed.getResourcePath(), path);

            if (file.exists()) {
                htmlEmail.attach(new FileDataSource(file), name, description);
            } else {
                throw new FileNotFoundException(file.getAbsolutePath());
            }
        }

        email = htmlEmail;
    } else if (available.containsKey(ContentType.PLAIN)) {
        email = new SimpleEmail();
        email.setCharset(CHARSET);
        email.setMsg(available.get(ContentType.PLAIN));
    } else {
        throw new IllegalArgumentException("No valid message found in template.");
    }

    final String subject = root.getChildText("subject");
    email.setSubject(subject);

    final Element from = root.getChild("from");
    final String fromAddress = from == null ? null : from.getText();
    final String fromName = from == null ? fromAddress : from.getAttributeValue("name", fromAddress);
    email.setFrom(fromAddress, fromName);

    final Element to = root.getChild("to");
    if (to != null) {
        final String toAddress = to.getText();
        if (StringUtils.isNotBlank(toAddress) && toAddress.contains(EMAIL_SEPARATOR)) {
            final String[] toAddresses = toAddress.split(EMAIL_SEPARATOR);
            for (String address : toAddresses) {
                email.addTo(address);
            }
        } else if (StringUtils.isNotBlank(toAddress)) {
            final String toName = to.getAttributeValue("name", toAddress);
            email.addTo(toAddress, toName);
        }
    }

    final Element cc = root.getChild("cc");
    if (cc != null) {
        final String ccAddress = cc.getText();
        if (StringUtils.isNotBlank(ccAddress) && ccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] ccAddresses = ccAddress.split(EMAIL_SEPARATOR);
            for (String address : ccAddresses) {
                email.addCc(address);
            }
        } else if (StringUtils.isNotBlank(ccAddress)) {
            final String ccName = cc.getAttributeValue("name", ccAddress);
            email.addCc(ccAddress, ccName);
        }
    }

    final Element bcc = root.getChild("bcc");
    if (bcc != null) {
        final String bccAddress = bcc.getText();
        if (StringUtils.isNotBlank(bccAddress) && bccAddress.contains(EMAIL_SEPARATOR)) {
            final String[] bccAddresses = bccAddress.split(EMAIL_SEPARATOR);
            for (String address : bccAddresses) {
                email.addBcc(address);
            }
        } else if (StringUtils.isNotBlank(bccAddress)) {
            final String bccName = bcc.getAttributeValue("name", bccAddress);
            email.addBcc(bccAddress, bccName);
        }
    }

    final Element replyTo = root.getChild("replyTo");
    if (replyTo != null) {
        final String replyToAddress = replyTo.getText();
        if (StringUtils.isNotBlank(replyToAddress) && replyToAddress.contains(EMAIL_SEPARATOR)) {
            final String[] replyToAddresses = replyToAddress.split(EMAIL_SEPARATOR);
            for (String address : replyToAddresses) {
                email.addReplyTo(address);
            }
        } else if (StringUtils.isNotBlank(replyToAddress)) {
            final String replyToName = replyTo.getAttributeValue("name", replyToAddress);
            email.addReplyTo(replyToAddress, replyToName);
        }
    }

    return email;
}

From source file:actors.ValidationEmailSender.java

@Override
public void onReceive(Object object) {
    if (!(object instanceof Email)) {
        return;/* w w w  .j a v  a2s .  c o  m*/
    }

    Email email = (Email) object;

    final HtmlEmail htmlEmail = new HtmlEmail();

    try {
        htmlEmail.setFrom(Config.getEmailFromSmtp(), utils.Config.getSiteName());
        htmlEmail.addTo(email.email, email.user.name);
        htmlEmail.setSubject(Messages.get("emails.validation.email.title", utils.Config.getSiteName()));
        htmlEmail.setHtmlMsg(getMessage(email.confirmUrl));
        htmlEmail.setCharset("utf-8");
        Mailer.send(htmlEmail);
        String escapedTitle = htmlEmail.getSubject().replace("\"", "\\\"");
        String logEntry = String.format("\"%s\" %s", escapedTitle, htmlEmail.getToAddresses());
        play.Logger.of("mail").info(logEntry);
    } catch (Exception e) {
        Logger.warn("Failed to send a notification: " + email + "\n" + ExceptionUtils.getStackTrace(e));
    }
}

From source file:com.mycollab.module.mail.DefaultMailer.java

private HtmlEmail getBasicEmail(String fromEmail, String fromName, List<MailRecipientField> toEmail,
        List<MailRecipientField> ccEmail, List<MailRecipientField> bccEmail, String subject, String html) {
    try {/*from   w w  w. j  a  v  a 2s. c  o m*/
        HtmlEmail email = new HtmlEmail();
        email.setHostName(emailConf.getHost());
        email.setSmtpPort(emailConf.getPort());
        email.setStartTLSEnabled(emailConf.getIsStartTls());
        email.setSSLOnConnect(emailConf.getIsSsl());
        email.setFrom(fromEmail, fromName);
        email.setCharset(EmailConstants.UTF_8);
        for (MailRecipientField aToEmail : toEmail) {
            if (isValidate(aToEmail.getEmail()) && isValidate(aToEmail.getName())) {
                email.addTo(aToEmail.getEmail(), aToEmail.getName());
            } else {
                LOG.error(String.format("Invalid to email input: %s---%s", aToEmail.getEmail(),
                        aToEmail.getName()));
            }
        }

        if (CollectionUtils.isNotEmpty(ccEmail)) {
            for (MailRecipientField aCcEmail : ccEmail) {
                if (isValidate(aCcEmail.getEmail()) && isValidate(aCcEmail.getName())) {
                    email.addCc(aCcEmail.getEmail(), aCcEmail.getName());
                } else {
                    LOG.error(String.format("Invalid cc email input: %s---%s", aCcEmail.getEmail(),
                            aCcEmail.getName()));
                }
            }
        }

        if (CollectionUtils.isNotEmpty(bccEmail)) {
            for (MailRecipientField aBccEmail : bccEmail) {
                if (isValidate(aBccEmail.getEmail()) && isValidate(aBccEmail.getName())) {
                    email.addBcc(aBccEmail.getEmail(), aBccEmail.getName());
                } else {
                    LOG.error(String.format("Invalid bcc email input: %s---%s", aBccEmail.getEmail(),
                            aBccEmail.getName()));
                }
            }
        }

        if (emailConf.getUser() != null) {
            email.setAuthentication(emailConf.getUser(), emailConf.getPassword());
        }

        email.setSubject(subject);

        if (StringUtils.isNotBlank(html)) {
            email.setHtmlMsg(html);
        }

        return email;
    } catch (EmailException e) {
        throw new MyCollabException(e);
    }
}

From source file:de.hybris.platform.acceleratorservices.email.impl.DefaultEmailService.java

@Override
public boolean send(final EmailMessageModel message) {
    if (message == null) {
        throw new IllegalArgumentException("message must not be null");
    }/*from www  . j  a  va2 s. c  o  m*/

    final boolean sendEnabled = getConfigurationService().getConfiguration()
            .getBoolean(EMAILSERVICE_SEND_ENABLED_CONFIG_KEY, true);
    if (sendEnabled) {
        try {
            final HtmlEmail email = getPerConfiguredEmail();
            email.setCharset("UTF-8");

            final List<EmailAddressModel> toAddresses = message.getToAddresses();
            if (CollectionUtils.isNotEmpty(toAddresses)) {
                email.setTo(getAddresses(toAddresses));
            } else {
                throw new IllegalArgumentException("message has no To addresses");
            }

            final List<EmailAddressModel> ccAddresses = message.getCcAddresses();
            if (ccAddresses != null && !ccAddresses.isEmpty()) {
                email.setCc(getAddresses(ccAddresses));
            }

            final List<EmailAddressModel> bccAddresses = message.getBccAddresses();
            if (bccAddresses != null && !bccAddresses.isEmpty()) {
                email.setBcc(getAddresses(bccAddresses));
            }

            final EmailAddressModel fromAddress = message.getFromAddress();
            email.setFrom(fromAddress.getEmailAddress(), nullifyEmpty(fromAddress.getDisplayName()));

            // Add the reply to if specified
            final String replyToAddress = message.getReplyToAddress();
            if (replyToAddress != null && !replyToAddress.isEmpty()) {
                email.setReplyTo(Collections.singletonList(createInternetAddress(replyToAddress, null)));
            }

            email.setSubject(message.getSubject());
            email.setHtmlMsg(getBody(message));

            // To support plain text parts use email.setTextMsg()

            final List<EmailAttachmentModel> attachments = message.getAttachments();
            if (attachments != null && !attachments.isEmpty()) {
                for (final EmailAttachmentModel attachment : attachments) {
                    try {
                        final DataSource dataSource = new ByteArrayDataSource(
                                getMediaService().getDataFromMedia(attachment), attachment.getMime());
                        email.attach(dataSource, attachment.getRealFileName(), attachment.getAltText());
                    } catch (final EmailException ex) {
                        LOG.error("Failed to load attachment data into data source [" + attachment + "]", ex);
                        return false;
                    }
                }
            }

            // Important to log all emails sent out
            LOG.info("Sending Email [" + message.getPk() + "] To [" + convertToStrings(toAddresses) + "] From ["
                    + fromAddress.getEmailAddress() + "] Subject [" + email.getSubject() + "]");

            // Send the email and capture the message ID
            final String messageID = email.send();

            message.setSent(true);
            message.setSentMessageID(messageID);
            message.setSentDate(new Date());
            getModelService().save(message);

            return true;
        } catch (final EmailException e) {
            LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject()
                    + "] cause: " + e.getMessage());
            if (LOG.isDebugEnabled()) {
                LOG.debug(e);
            }
        }
    } else {
        LOG.warn("Could not send e-mail pk [" + message.getPk() + "] subject [" + message.getSubject() + "]");
        LOG.info("Email sending has been disabled. Check the config property 'emailservice.send.enabled'");
        return true;
    }

    return false;
}