Java mail 發送郵件 主題(標題)亂碼


最近開發遇到Javamail  發送郵件標題亂碼問題,騰訊、網易郵箱不會亂碼,阿里郵箱  標題則會亂碼。解決辦法:

String subject = MimeUtility.encodeWord(mailEntity.getMailSubject(), "UTF-8", "Q");
            message.setSubject(subject);

發送郵件代碼:

/**
     * 發送郵件  可以帶附件   內容可為HTML
     *
     * @param mailEntity
     * @return
     * @throws GeneralSecurityException
     */
    public static boolean sendMail(MailEntity mailEntity)
            throws GeneralSecurityException {

        // 發件人電子郵箱
        final String from = mailEntity.getMailFromAddress();
        // 發件人電子郵箱密碼
        final String pass = mailEntity.getMailFromPwd();

        // 指定發送郵件的主機為 smtp.qq.com
        String host = mailEntity.getMailFromHost(); // 郵件服務器

        String port = mailEntity.getPort();

        // 獲取系統屬性
        Properties properties = System.getProperties();

        // 設置郵件服務器
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port",port);

        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "false");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 獲取默認session對象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() { // qq郵箱服務器賬戶、第三方登錄授權碼
                return new PasswordAuthentication(from, pass); // 發件人郵件用戶名、密碼
            }
        });

        try {
            // 創建默認的 MimeMessage 對象
            MimeMessage message = new MimeMessage(session);

            // Set From: 頭部頭字段
            message.setFrom(new InternetAddress(from));

            // Set To: 頭部頭字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailEntity.getMailReceiverAddress()));

            // Set Subject: 主題文字
            String subject = MimeUtility.encodeWord(mailEntity.getMailSubject(), "UTF-8", "Q");
            message.setSubject(subject);

            // 創建消息部分
            BodyPart messageBodyPart = new MimeBodyPart();

            // 消息
//            messageBodyPart.setText(mailEntity.getMailContent());
            messageBodyPart.setContent(mailEntity.getMailContent(), "text/html;charset=utf-8");

            // 創建多重消息
            Multipart multipart = new MimeMultipart();

            // 設置文本消息部分
            multipart.addBodyPart(messageBodyPart);

            if (mailEntity.getFilePaths() != null && mailEntity.getFilePaths().size() > 0) {
                for (String filePath : mailEntity.getFilePaths()) {
                    // 附件部分
                    messageBodyPart = new MimeBodyPart();
                    String suffix = "";
                    String oldPath = "";
                    if (filePath.indexOf(".") >0){
                        suffix = filePath.substring(filePath.indexOf(".")+1);
                        oldPath = filePath.substring(0,filePath.indexOf("."));

                        DataSource source = new FileDataSource(oldPath);
                        File file = ((FileDataSource) source).getFile();
                        file.renameTo(new File(oldPath + "." + suffix));
                        source = new FileDataSource(filePath);
                        messageBodyPart.setDataHandler(new DataHandler(source));

                    }else {
                        // 設置要發送附件的文件路徑
                        DataSource source = new FileDataSource(filePath);
                        messageBodyPart.setDataHandler(new DataHandler(source));
                    }

                    // 設置要發送附件的文件路徑

                    // messageBodyPart.setFileName(filename);
                    // 處理附件名稱中文(附帶文件路徑)亂碼問題
                    messageBodyPart.setFileName(MimeUtility.encodeText(filePath));
                    multipart.addBodyPart(messageBodyPart);
                }
            }

            // 發送完整消息
            message.setContent(multipart);

            // 發送消息
            Transport.send(message);
            logger.info("Sent mail successfully....");
            return true;
        } catch (MessagingException e) {
            logger.debug(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            logger.debug(e.getMessage());
        }
        return false;
    }

實體:

/**
 * @Auther: mxf
 * @Date: 2018/10/31 16:08
 * @Description:發送郵件實體類
 */
public class MailEntity implements Serializable {
    /**
     * 郵件接收地址
     */
    private String mailReceiverAddress;

    /**
     * 郵件主題
     */
    private String mailSubject;

    /**
     * 郵件內容
     */
    private String mailContent;

    /**
     * 附件路徑
     */
    private List<String> filePaths = new ArrayList<String>();

    /**
     * 發送地址
     */
    private String mailFromAddress;

    /**
     * 發送者的郵件密碼
     */
    private String mailFromPwd;

    /**
     * 指定發送郵件的主機
     */
    private String mailFromHost;

    /**
     * 發送郵件主機端口
     */
    private String port;

    public String getPort() {
        return port;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public String getMailReceiverAddress() {
        return mailReceiverAddress;
    }

    public void setMailReceiverAddress(String mailReceiverAddress) {
        this.mailReceiverAddress = mailReceiverAddress;
    }

    public String getMailSubject() {
        return mailSubject;
    }

    public void setMailSubject(String mailSubject) {
        this.mailSubject = mailSubject;
    }

    public String getMailContent() {
        return mailContent;
    }

    public void setMailContent(String mailContent) {
        this.mailContent = mailContent;
    }

    public List<String> getFilePaths() {
        return filePaths;
    }

    public void setFilePaths(List<String> filePaths) {
        this.filePaths = filePaths;
    }

    public String getMailFromAddress() {
        return mailFromAddress;
    }

    public void setMailFromAddress(String mailFromAddress) {
        this.mailFromAddress = mailFromAddress;
    }

    public String getMailFromPwd() {
        return mailFromPwd;
    }

    public void setMailFromPwd(String mailFromPwd) {
        this.mailFromPwd = mailFromPwd;
    }

    public String getMailFromHost() {
        return mailFromHost;
    }

    public void setMailFromHost(String mailFromHost) {
        this.mailFromHost = mailFromHost;
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM