Example usage for javax.mail.internet MimeUtility encodeText

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

Introduction

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

Prototype

public static String encodeText(String text) throws UnsupportedEncodingException 

Source Link

Document

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

Usage

From source file:com.vicky.common.utils.sendemail.SendEmailImpl.java

@Override
public void send(Mail mail) throws Exception {
    try {//from w w w  . j  a va 2s  .com
        HtmlEmail htmlEmail = new HtmlEmail();
        htmlEmail.setHostName(mail.getHost());
        htmlEmail.setCharset(Mail.ENCODEING);
        htmlEmail.addTo(mail.getReceiverEmailAddress());
        htmlEmail.setFrom(mail.getSenderEmailAddress(), mail.getName());
        htmlEmail.setAuthentication(mail.getSenderUsername(), mail.getSenderPassword());
        htmlEmail.setSubject(mail.getSubject());
        htmlEmail.setMsg(mail.getMessage());
        for (MailAttach mailFile : mail.getMailAttachs()) {
            EmailAttachment attachment = new EmailAttachment();//  
            attachment.setPath(mailFile.getFilePath());//?    
            //attachment.setURL(new URL("http://www.baidu.com/moumou"));//?  
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setName(MimeUtility.encodeText(mailFile.getFileName()));//??  
            htmlEmail.attach(attachment);//,?
        }
        htmlEmail.send();
    } catch (Exception exception) {
        exception.printStackTrace();
        this.logger.error("toString" + exception.toString());
        this.logger.error("getMessage" + exception.getMessage());
        this.logger.error("exception", exception);
        throw new StatusMsgException(
                "??,??,?,?V!");
    }
}

From source file:ar.com.zauber.commons.message.impl.mail.MimeEmailNotificationStrategy.java

/**
 * If message is a {@link HeaderMessage}, adds headers to the {@link MimeMessage}
 * @param message/*from  ww w.ja v a2  s. c  o  m*/
 * @param mail
 * @throws UnsupportedEncodingException 
 * @throws MessagingException 
 */
private void addHeaders(final Message message, final MimeMessage mail)
        throws MessagingException, UnsupportedEncodingException {
    if (message instanceof HeaderMessage) {
        final Map<String, String> headers = ((HeaderMessage) message).getHeaders();
        for (final Entry<String, String> entry : headers.entrySet()) {
            mail.addHeader(entry.getKey(), MimeUtility.encodeText(entry.getValue()));
        }
    }
}

From source file:com.github.dactiv.fear.service.service.message.MessageService.java

/**
 * ???/*from w w  w  .j  a v a  2s  . c o m*/
 *
 * @param nickname 
 * @param javaMailSender ??
 *
 * @return ??
 */
private String getSendForm(String nickname, JavaMailSender javaMailSender) {

    JavaMailSenderImpl impl = null;

    if (javaMailSender instanceof JavaMailSenderImpl) {
        impl = (JavaMailSenderImpl) javaMailSender;
    }

    if (impl == null) {
        throw new ServiceException(
                JavaMailSenderImpl.class + " ?? " + javaMailSender.getClass() + "");
    }

    String address;

    String propertiesNickname = impl.getJavaMailProperties().getProperty("mail.nickname", nickname);

    try {
        if (StringUtils.isEmpty(propertiesNickname)) {
            address = impl.getUsername();
        } else {
            address = MimeUtility.encodeText(propertiesNickname) + " <" + impl.getUsername() + ">";
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("?[" + nickname + "],?" + impl.getUsername()
                + "", e);
        address = impl.getUsername();
    }

    return address;

}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

public void sendMail(Mail mail) {
    LOG.debug("sendEmail() to: " + mail.getRecipient());
    try {/*ww  w. j ava  2s.co  m*/
        Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
        session.setDebug(false);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(m_bag.m_fromAddress);
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
        msg.setSubject(mail.getSubject());
        msg.setSentDate(new Date());

        Multipart mp = new MimeMultipart();

        MimeBodyPart txtmbp = new MimeBodyPart();
        txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE);
        mp.addBodyPart(txtmbp);

        List<String> attachments = mail.getAttachments();
        for (Iterator<String> it = attachments.iterator(); it.hasNext();) {
            MimeBodyPart mbp = new MimeBodyPart();
            String filename = it.next();
            FileDataSource fds = new FileDataSource(filename);
            mbp.setDataHandler(new DataHandler(fds));
            mbp.setFileName(MimeUtility.encodeText(fds.getName()));
            mp.addBodyPart(mbp);
        }

        msg.setContent(mp);

        if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null)
                && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) {
            cheat(msg,
                    m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@")));
        }

        Transport.send(msg);

        LOG.info("Successfully send the mail to " + mail.getRecipient());

    } catch (Throwable e) {

        LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e);
        LOG.debug("Details:", e);
    }
}

From source file:com.ms.commons.message.impl.sender.AbstractEmailSender.java

/**
 * Email/*w  w  w .  ja  v  a  2  s. c o m*/
 * 
 * @param mail
 * @return
 * @throws Exception
 */
protected Email getEmail(MsunMail mail) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("send mail use smth : " + hostName);
    }
    // set env for logger
    mail.getEnvironment().setHostName(hostName);
    mail.getEnvironment().setUser(user);
    mail.getEnvironment().setPassword(password);

    Email email = null;

    if (!StringUtils.isEmpty(mail.getHtmlMessage())) {
        email = makeHtmlEmail(mail, mail.getCharset());
    } else {
        if ((mail.getAttachment() == null || mail.getAttachment().length == 0)
                && mail.getAttachments().isEmpty()) {
            email = makeSimpleEmail(mail, mail.getCharset());
        } else {
            email = makeSimpleEmailWithAttachment(mail, mail.getCharset());
        }
    }

    if (auth) {
        // email.setAuthenticator(new MyAuthenticator(user, password));
        email.setAuthentication(user, password);
    }
    email.setHostName(hostName);

    if (mail.getTo() == null) {
        mail.setTo(defaultTo.split(";"));
    }

    if (StringUtils.isEmpty(mail.getFrom())) {
        mail.setFrom(defaultFrom);
    }

    email.setFrom(mail.getFrom(), mail.getFromName());

    List<String> unqualifiedReceiver = mail.getUnqualifiedReceiver();
    String[] mailTo = mail.getTo();
    String[] mailCc = mail.getCc();
    String[] mailBcc = mail.getBcc();
    if (unqualifiedReceiver != null && unqualifiedReceiver.size() > 0) {
        if (mailTo != null && mailTo.length > 0) {
            mailTo = filterReceiver(mailTo, unqualifiedReceiver);
        }
        if (mailCc != null && mailCc.length > 0) {
            mailCc = filterReceiver(mailCc, unqualifiedReceiver);
        }
        if (mailBcc != null && mailBcc.length > 0) {
            mailBcc = filterReceiver(mailBcc, unqualifiedReceiver);
        }
    }

    if (mailTo == null && mailCc == null && mailBcc == null) {
        throw new MessageSerivceException("?????");
    }

    int count = 0;

    if (mailTo != null) {
        count += mailTo.length;
        for (String to : mailTo) {
            email.addTo(to);
        }
    }

    if (mailCc != null) {
        count += mailCc.length;
        for (String cc : mailCc) {
            email.addCc(cc);
        }
    }
    if (mailBcc != null) {
        count += mailBcc.length;
        for (String bcc : mailBcc) {
            email.addBcc(bcc);
        }
    }

    if (count < 1) {
        throw new MessageSerivceException("?????");
    }

    if (!StringUtils.isEmpty(mail.getReplyTo())) {
        email.addReplyTo(mail.getReplyTo());
    }

    if (mail.getHeaders() != null) {
        for (Iterator<String> iter = mail.getHeaders().keySet().iterator(); iter.hasNext();) {
            String key = (String) iter.next();
            email.addHeader(key, (String) mail.getHeaders().get(key));
        }
    }

    email.setSubject(mail.getSubject());

    // 
    if (email instanceof MultiPartEmail) {
        MultiPartEmail multiEmail = (MultiPartEmail) email;

        if (mail.getAttachments().isEmpty()) {
            File[] fs = mail.getAttachment();
            if (fs != null && fs.length > 0) {
                for (int i = 0; i < fs.length; i++) {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setPath(fs[i].getAbsolutePath());
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    attachment.setName(MimeUtility.encodeText(fs[i].getName()));// ???
                    multiEmail.attach(attachment);
                }
            }
        } else {
            for (MsunMailAttachment attachment : mail.getAttachments()) {
                DataSource ds = new ByteArrayDataSource(attachment.getData(), null);
                multiEmail.attach(ds, MimeUtility.encodeText(attachment.getName()), null);
            }
        }
    }
    return email;
}

From source file:com.glaf.mail.util.MailUtils.java

public static String getMailAddress(String mailAddress) {
    if (mailAddress == null) {
        return null;
    }/*  w  ww  . j  a  v a2 s . c  o  m*/
    try {
        mailAddress = MimeUtility.encodeText(mailAddress);
        if (mailAddress.startsWith("=?GBK?Q?=") || mailAddress.startsWith("=?GB2312?Q?=")) {
            mailAddress = native2unicode(mailAddress);
        } else {
            mailAddress = MimeUtility.decodeText(mailAddress);
        }
        mailAddress = convertString(mailAddress);
        mailAddress = StringTools.replaceIgnoreCase(mailAddress, "<", " < ");
        mailAddress = StringTools.replaceIgnoreCase(mailAddress, ">", " > ");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return mailAddress;
}

From source file:com.glaf.mail.util.MailUtils.java

public static String getSubject(String mailSubject) {
    if (mailSubject == null) {
        mailSubject = "";
        return mailSubject;
    }//from   w ww.  ja v  a 2 s  . c o  m
    try {
        mailSubject = MimeUtility.encodeText(mailSubject);
        if (mailSubject.startsWith("=?GBK?Q?=") || mailSubject.startsWith("=?GB2312?Q?=")) {
            mailSubject = native2unicode(mailSubject);
        } else {
            mailSubject = MimeUtility.decodeText(mailSubject);
        }
        mailSubject = convertString(mailSubject);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    if (mailSubject == null || mailSubject.trim().equals("null") || mailSubject.trim().equals("")) {
        mailSubject = "";
    }
    return mailSubject;
}

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

/**
 * ?????/*ww w.  ja v a 2  s  . com*/
 *
 * @param msg
 * @return
 */
public static ALMailMessage getReplyMessage(ALMailMessage mailmsg) {
    if (mailmsg == null) {
        return null;
    }

    ALLocalMailMessage msg = null;
    try {
        msg = (ALLocalMailMessage) mailmsg;

        StringBuffer sb = new StringBuffer();
        sb.append("From: ").append(getFromDelegate(msg)).append(CR);
        sb.append("To: ").append(getAddressString(msg.getRecipients(Message.RecipientType.TO, false)))
                .append(CR);
        sb.append("Sent: ").append(msg.getSentDate()).append(CR);
        sb.append("Subject: ").append(UnicodeCorrecter.correctToISO2022JP(msg.getSubject())).append(CR)
                .append(" ").append(CR);

        msg.setSubject(MimeUtility.encodeText(UnicodeCorrecter.correctToISO2022JP(msg.getSubject())));
        msg.setRecipient(Message.RecipientType.TO, getReplyToDelegateExtract(msg));
        String[] lines = msg.getBodyTextArray();
        if (lines != null && lines.length > 0) {
            int length = lines.length;
            for (int i = 0; i < length; i++) {
                sb.append(lines[i]).append(CR);
            }
        }
        msg.setText(UnicodeCorrecter.correctToISO2022JP(sb.toString()));
    } catch (Exception e) {
        logger.error("ALMailUtils.getReplyMessage", e);
        return null;
    }
    return msg;
}

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

/**
 * ?????/*w ww  . j ava  2s  .c  om*/
 *
 * @param msg
 * @return
 */
public static ALMailMessage getReplyAllMessage(ALMailMessage mailmsg) {
    if (mailmsg == null) {
        return null;
    }

    ALLocalMailMessage msg = null;
    try {
        msg = (ALLocalMailMessage) mailmsg;

        StringBuffer sb = new StringBuffer();
        sb.append("From: ").append(getFromDelegate(msg)).append(CR);
        sb.append("To: ").append(getAddressString(msg.getRecipients(Message.RecipientType.TO, false)))
                .append(CR);
        sb.append("Sent: ").append(msg.getSentDate()).append(CR);
        sb.append("Subject: ").append(UnicodeCorrecter.correctToISO2022JP(msg.getSubject())).append(CR)
                .append(" ").append(CR);

        msg.setSubject(MimeUtility.encodeText(UnicodeCorrecter.correctToISO2022JP(msg.getSubject())));
        String[] lines = msg.getBodyTextArray();
        if (lines != null && lines.length > 0) {
            int length = lines.length;
            for (int i = 0; i < length; i++) {
                sb.append(lines[i]).append(CR);
            }
        }
        msg.setText(UnicodeCorrecter.correctToISO2022JP(sb.toString()));
    } catch (Exception e) {
        logger.error("ALMailUtils.getReplyMessage", e);
        return null;
    }
    return msg;
}

From source file:com.aimluck.eip.mail.util.ALMailUtils.java

/**
 * ??????/*from  ww w  . j  a  v  a  2 s  .co m*/
 *
 * @param msg
 * @return
 */
public static ALMailMessage getForwardMessage(ALMailMessage mailmsg) {
    if (mailmsg == null) {
        return null;
    }

    ALLocalMailMessage msg = null;
    try {
        msg = (ALLocalMailMessage) mailmsg;

        StringBuffer sb = new StringBuffer();
        sb.append("From: ").append(getFromDelegate(msg)).append(CR);
        sb.append("To: ").append(getAddressString(msg.getRecipients(Message.RecipientType.TO, false)))
                .append(CR);
        sb.append("Sent: ").append(msg.getSentDate()).append(CR);
        sb.append("Subject: ").append(UnicodeCorrecter.correctToISO2022JP(msg.getSubject())).append(CR)
                .append(" ").append(CR);

        msg.setSubject(MimeUtility.encodeText(UnicodeCorrecter.correctToISO2022JP(msg.getSubject())));
        // msg.setRecipient(Message.RecipientType.TO, msg.getFrom()[0]);
        String[] lines = msg.getBodyTextArray();
        if (lines != null && lines.length > 0) {
            int length = lines.length;
            for (int i = 0; i < length; i++) {
                sb.append(lines[i]).append(CR);
            }
        }
        msg.setText(UnicodeCorrecter.correctToISO2022JP(sb.toString()));
    } catch (Exception e) {
        logger.error("ALMailUtils.getForwardMessage", e);
        return null;
    }
    return msg;
}