Example usage for javax.mail.internet MimeUtility encodeWord

List of usage examples for javax.mail.internet MimeUtility encodeWord

Introduction

In this page you can find the example usage for javax.mail.internet MimeUtility encodeWord.

Prototype

public static String encodeWord(String word) throws UnsupportedEncodingException 

Source Link

Document

Encode a RFC 822 "word" token into mail-safe form as per RFC 2047.

Usage

From source file:com.springstudy.utils.email.MimeMailService.java

/**
 * ??MIME?.//from   w w w .  j  a  v a2 s.c  o  m
 */
public boolean sendNotificationMail(com.gmk.framework.common.utils.email.Email email) {
    try {
        MimeMessage msg = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING);
        //??????
        String from = Global.getConfig("productName");
        if (StringUtils.isNotEmpty(email.getFrom())) {
            from = from + "-" + email.getFrom();
        }
        helper.setFrom(Global.getConfig("mailFrom"), from);
        helper.setTo(email.getAddress());
        if (StringUtils.isNotEmpty(email.getCc())) {
            String cc[] = email.getCc().split(";");
            helper.setCc(cc);//?
        }
        //
        helper.setSubject(email.getSubject());
        //
        if (StringUtils.isNotEmpty(email.getTemplate())) {
            String content = generateContent(email.getTemplate(), email.getContentMap());
            helper.setText(content, true);
        } else {
            helper.setText(email.getContent());
        }
        //
        if (ListUtils.isNotEmpty(email.getAttachment())) {
            for (File file : email.getAttachment()) {
                helper.addAttachment(MimeUtility.encodeWord(file.getName()), file);
            }
        }
        mailSender.send(msg);
        logger.info("HTML??");
        return true;
    } catch (MessagingException e) {
        logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "", e);
    } catch (Exception e) {
        logger.error(email.getAddressee() + "-" + email.getSubject() + "-" + "??", e);
    }
    return false;
}

From source file:net.groupbuy.service.impl.MailServiceImpl.java

public void send(String smtpFromMail, String smtpHost, Integer smtpPort, String smtpUsername,
        String smtpPassword, String toMail, String subject, String templatePath, Map<String, Object> model,
        boolean async) {
    Assert.hasText(smtpFromMail);//from   w w w.java 2 s.  c o m
    Assert.hasText(smtpHost);
    Assert.notNull(smtpPort);
    Assert.hasText(smtpUsername);
    Assert.hasText(smtpPassword);
    Assert.hasText(toMail);
    Assert.hasText(subject);
    Assert.hasText(templatePath);
    try {
        Setting setting = SettingUtils.get();
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Template template = configuration.getTemplate(templatePath);
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
        javaMailSender.setHost(smtpHost);
        javaMailSender.setPort(smtpPort);
        javaMailSender.setUsername(smtpUsername);
        javaMailSender.setPassword(smtpPassword);
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, "utf-8");
        mimeMessageHelper.setFrom(MimeUtility.encodeWord(setting.getSiteName()) + " <" + smtpFromMail + ">");
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setTo(toMail);
        mimeMessageHelper.setText(text, true);
        if (async) {
            addSendTask(mimeMessage);
        } else {
            javaMailSender.send(mimeMessage);
        }
    } catch (TemplateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

From source file:com.glaf.mail.MailSenderImpl.java

public void send(JavaMailSender javaMailSender, MailMessage mailMessage) throws Exception {
    if (StringUtils.isEmpty(mailMessage.getMessageId())) {
        mailMessage.setMessageId(UUID32.getUUID());
    }//w  w  w .  ja  v a2s.co  m

    mailHelper = new MxMailHelper();
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);

    if (StringUtils.isNotEmpty(mailMessage.getFrom())) {
        messageHelper.setFrom(mailMessage.getFrom());
        mailFrom = mailMessage.getFrom();
    } else {
        if (StringUtils.isEmpty(mailFrom)) {
            mailFrom = MailProperties.getString("mail.mailFrom");
        }
        messageHelper.setFrom(mailFrom);
    }

    logger.debug("mailFrom:" + mailFrom);

    if (mailMessage.getTo() != null) {
        messageHelper.setTo(mailMessage.getTo());
    }

    if (mailMessage.getCc() != null) {
        messageHelper.setCc(mailMessage.getCc());
    }

    if (mailMessage.getBcc() != null) {
        messageHelper.setBcc(mailMessage.getBcc());
    }

    if (mailMessage.getReplyTo() != null) {
        messageHelper.setReplyTo(mailMessage.getReplyTo());
    }

    String mailSubject = mailMessage.getSubject();
    if (mailSubject == null) {
        mailSubject = "";
    }

    if (mailSubject != null) {
        // mailSubject = MimeUtility.encodeText(new
        // String(mailSubject.getBytes(), encoding), encoding, "B");
        mailSubject = MimeUtility.encodeWord(mailSubject);
    }

    mimeMessage.setSubject(mailSubject);

    Map<String, Object> dataMap = mailMessage.getDataMap();
    if (dataMap == null) {
        dataMap = new java.util.HashMap<String, Object>();
    }

    String serviceUrl = SystemConfig.getServiceUrl();

    logger.debug("mailSubject:" + mailSubject);
    logger.debug("serviceUrl:" + serviceUrl);

    if (serviceUrl != null) {
        String loginUrl = serviceUrl + "/mx/login";
        String mainUrl = serviceUrl + "/mx/main";
        logger.debug("loginUrl:" + loginUrl);
        dataMap.put("loginUrl", loginUrl);
        dataMap.put("mainUrl", mainUrl);
    }

    mailMessage.setDataMap(dataMap);

    if (StringUtils.isEmpty(mailMessage.getContent())) {
        Template template = TemplateContainer.getContainer().getTemplate(mailMessage.getTemplateId());
        if (template != null) {
            String templateType = template.getTemplateType();
            logger.debug("templateType:" + templateType);
            // logger.debug("content:" + template.getContent());
            if (StringUtils.equals(templateType, "eml")) {
                if (template.getContent() != null) {
                    Mail m = mailHelper.getMail(template.getContent().getBytes());
                    String content = m.getContent();
                    if (StringUtils.isNotEmpty(content)) {
                        template.setContent(content);
                        try {
                            Writer writer = new StringWriter();
                            TemplateUtils.evaluate(mailMessage.getTemplateId(), dataMap, writer);
                            String text = writer.toString();
                            writer.close();
                            writer = null;
                            mailMessage.setContent(text);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            throw new RuntimeException(ex);
                        }
                    }
                }
            } else {
                try {
                    String text = TemplateUtils.process(dataMap, template.getContent());
                    mailMessage.setContent(text);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    if (StringUtils.isNotEmpty(mailMessage.getContent())) {
        String text = mailMessage.getContent();
        if (StringUtils.isNotEmpty(callbackUrl)) {
            String href = callbackUrl + "?messageId=" + mailMessage.getMessageId();
            text = mailHelper.embedCallbackScript(text, href);
            mailMessage.setContent(text);
            logger.debug(text);
            messageHelper.setText(text, true);
        }
        messageHelper.setText(text, true);
    }

    logger.debug("mail body:" + mailMessage.getContent());

    Collection<Object> files = mailMessage.getFiles();

    if (files != null && !files.isEmpty()) {
        Iterator<Object> iterator = files.iterator();
        while (iterator.hasNext()) {
            Object object = iterator.next();
            if (object instanceof java.io.File) {
                java.io.File file = (java.io.File) object;
                FileSystemResource resource = new FileSystemResource(file);
                String name = file.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, resource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataSource) {
                DataSource dataSource = (DataSource) object;
                String name = dataSource.getName();
                name = MailTools.chineseStringToAscii(name);
                messageHelper.addAttachment(name, dataSource);
                logger.debug("add attachment:" + name);
            } else if (object instanceof DataFile) {
                DataFile dataFile = (DataFile) object;
                if (StringUtils.isNotEmpty(dataFile.getFilename())) {
                    String name = dataFile.getFilename();
                    name = MailTools.chineseStringToAscii(name);
                    InputStreamSource inputStreamSource = new MxMailInputSource(dataFile);
                    messageHelper.addAttachment(name, inputStreamSource);
                    logger.debug("add attachment:" + name);
                }
            }
        }
    }

    mimeMessage.setSentDate(new java.util.Date());

    javaMailSender.send(mimeMessage);

    logger.info("-----------------------------------------");
    logger.info("????");
    logger.info("-----------------------------------------");
}

From source file:org.latticesoft.util.resource.MessageUtil.java

/**
 * Sends the email.//from ww w . j  a v  a2  s.  c o m
 * @param info the EmailInfo containing the message and other details
 * @param p the properties to set in the environment when instantiating the session
 * @param auth the authenticator
 */
public static void sendMail(EmailInfo info, Properties p, Authenticator auth) {
    try {
        if (p == null) {
            if (log.isErrorEnabled()) {
                log.error("Null properties!");
            }
            return;
        }
        Session session = Session.getInstance(p, auth);
        session.setDebug(true);
        if (log.isInfoEnabled()) {
            log.info(p);
            log.info(session);
        }
        MimeMessage mimeMessage = new MimeMessage(session);
        if (log.isInfoEnabled()) {
            log.info(mimeMessage);
            log.info(info.getFromAddress());
        }
        mimeMessage.setFrom(info.getFromAddress());
        mimeMessage.setSentDate(new Date());
        List l = info.getToList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                if (log.isInfoEnabled()) {
                    log.info(addr);
                }
                mimeMessage.addRecipients(Message.RecipientType.TO, addr);
            }
        }
        l = info.getCcList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.CC, addr);
            }
        }
        l = info.getBccList();
        if (l != null) {
            for (int i = 0; i < l.size(); i++) {
                String addr = (String) l.get(i);
                mimeMessage.addRecipients(Message.RecipientType.BCC, addr);
            }
        }

        if (info.getAttachment().size() == 0) {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
                mimeMessage.setText(info.getContent(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
                mimeMessage.setText(info.getContent());
            }
            mimeMessage.setContent(info.getContent(), info.getContentType());
        } else {
            if (info.getCharSet() != null) {
                mimeMessage.setSubject(info.getSubject(), info.getCharSet());
            } else {
                mimeMessage.setSubject(info.getSubject());
            }
            Multipart mp = new MimeMultipart();
            MimeBodyPart body = new MimeBodyPart();
            if (info.getCharSet() != null) {
                body.setText(info.getContent(), info.getCharSet());
                body.setContent(info.getContent(), info.getContentType());
            } else {
                body.setText(info.getContent());
                body.setContent(info.getContent(), info.getContentType());
            }
            mp.addBodyPart(body);
            for (int i = 0; i < info.getAttachment().size(); i++) {
                String filename = (String) info.getAttachment().get(i);
                MimeBodyPart attachment = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(filename);
                attachment.setDataHandler(new DataHandler(fds));
                attachment.setFileName(MimeUtility.encodeWord(fds.getName()));
                mp.addBodyPart(attachment);
            }
            mimeMessage.setContent(mp);
        }
        Transport.send(mimeMessage);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error("Error in sending email", e);
        }
    }
}