SpringBoot开发中mail中文附件乱码如何解决

https://baijiahao.baidu.com/s?id=1579662074536298902&wfr=spider&for=pc

未知原因仍然无法解决附件名称改变的问题,

由于使用的springBoot在配置文件中配置了

 在这里 账号密码用了读取配置的方法

oldSendMail方法为寻找到的原型,
sendMail为修改后的方法
package com.qgil.ums.com.utils;

import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.alibaba.druid.util.StringUtils;
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * 发送邮件工具类
 *
 * @author tp
 *
 */
@Component
public class EmailUtil {

    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.password}")
    private String password;

    /**
     * 发送带附件的邮件
     *
     * @param to  收件人
     * @param subject  邮件主题
     * @param msg      邮件内容
     * @param filename 附件地址
     * @return
     * @throws GeneralSecurityException
     */
    public boolean sendMail(String from,String to, String subject, String msg, String filename)
            throws Exception {

        if (StringUtils.isEmpty(to)) {
            return false;
        }
        if (StringUtils.isEmpty(subject)){
            return false;
        }
        if (StringUtils.isEmpty(msg)){
            msg = "";
        }
        // 创建默认的 MimeMessage 对象
        MimeMessage message = mailSender.createMimeMessage();
        try {

            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            helper.setFrom(from);

            helper.setTo(to);

            helper.setSubject(subject);

            helper.setText(msg, true);

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

            // 消息
            messageBodyPart.setText(msg);

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

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

            if(filename != null) {
                multipart = setFile(filename,multipart);
            }
            // 发送完整消息
            message.setContent(multipart);
            // 发送消息
            mailSender.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 发送带附件的邮件
     * @param from  发件人
     * @param to  收件人
     * @param subject  邮件主题
     * @param msg      邮件内容
     * @param filename 附件地址
     * @return
     * @throws GeneralSecurityException
     */
    public boolean oldSendMail(String from,String to, String subject, String msg, String filename)
            throws GeneralSecurityException {
        if (StringUtils.isEmpty(to)) {
            return false;
        }
        if (StringUtils.isEmpty(msg)){
            msg = "";
        }
        /*
         * 2.配置协议
         * */
        Properties props = new Properties();
        //协议
        props.setProperty("mail.transport.protocol", "smtp");
        //服务器
        props.setProperty("mail.smtp.host", "smtp.126.com");
        //端口
        props.setProperty("mail.smtp.port", "25");
        //使用smtp身份验证
        props.setProperty("mail.smtp.auth", "true");
        //使用SSL,企业邮箱必需!
        //开启安全协议
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);
        //发送邮箱账号密码
        Session session = Session.getDefaultInstance(props, new MyAuthenricator(from, password));

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

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

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // Set Subject: 主题文字
            message.setSubject(subject);

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

            // 消息
            messageBodyPart.setText(msg);

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

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

            if(filename != null) {
               multipart = setFile(filename,multipart);
            }
            // 发送完整消息
            message.setContent(multipart);
            // 发送消息
            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
        } /*catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        return false;
    }

    public  Multipart  setFile(String filename,Multipart multipart) throws MessagingException {
        // 附件部分
        BodyPart  messageBodyPart = new MimeBodyPart();
        // 设置要发送附件的文件路径
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        // messageBodyPart.setFileName(filename);
        // 处理附件名称中文(附带文件路径)乱码问题
        messageBodyPart.setFileName(source.getName());
        multipart.addBodyPart(messageBodyPart);
        return multipart;
    }
    //用户名密码验证,需要实现抽象类Authenticator的抽象方法PasswordAuthentication
    static class MyAuthenricator extends Authenticator {
        String u = null;
        String p = null;
        public MyAuthenricator(String u,String p){
            this.u=u;
            this.p=p;
        }
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(u,p);
        }
    }


}

解决附件名称过长,导致附件名称变化的问题

猜你喜欢

转载自blog.csdn.net/m0_37450089/article/details/83861643
今日推荐