springboot 发送邮件,以及邮件工具类 并且解决spring-boot-starter-mail 发送邮件附件乱码或者文件错乱

1、设置系统值

System.setProperty(“mail.mime.splitlongparameters”, “false”);

2、 在创建对象的时候定义编码格式(utf-8):

MimeMessageHelper helper = new MimeMessageHelper(mes, true, “utf-8”);

3、 其次,在添加附件的时候,附件名是需要定义编码的

helper.addAttachment(MimeUtility.encodeWord(附件名,“utf-8”,“B”), 你的附件对象);
————————————————
版权声明:本文为CSDN博主「往事不堪回首…」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq3892997/article/details/126013828

//生成的数据通过excel附件的方式,进行发送。
	public void sendMail(String mailFrom, String mailTo, String title, String content, File file) throws Exception {
		System.setProperty("mail.mime.splitlongparameters", "false");//1.设置系统值 ---处理文件名乱码
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper msg = new MimeMessageHelper(mimeMessage, true, "utf-8");//2.在创建对象的时候定义编码格式(utf-8)
		msg.addAttachment(MimeUtility.encodeWord(excelName,"utf-8","B"), file); //3.在添加附件的时候,附件名是需要定义编码的 ---以上3条都得有,否则文件名乱码
		msg.setFrom(mailFrom);
		msg.setTo(mailTo);
		msg.setSubject(title);
		msg.setText(content, true);
		mailSender.send(mimeMessage);
	}

工具类


@Component
@Slf4j
/**
 * 发送邮件工具类
 * @author ZMH
 * @date 7/7/2023 2:03 下午
 */
public class EmailUtils {

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送纯文本邮件
     * @author ZMH
     * @date 7/7/2023 10:37 上午
     * @param subject 邮件主题
     * @param text 邮件内容
     * @param targetEmail 目标邮件地址
     * @param sourceEmail 源邮件地址
     * @return void
     */
    public void sendTextEmail (String subject,String text,String targetEmail,String sourceEmail ){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setSubject(subject);//主题
        mailMessage.setText(text);//内容
        if (StringUtils.isNotBlank(targetEmail) && targetEmail.split(",").length>1){
            mailMessage.setTo(targetEmail.split(","));//多个号码发送,该发送会将目标邮件分组发送
        }else {
            mailMessage.setTo(targetEmail);
        }
        mailMessage.setFrom(sourceEmail);
        javaMailSender.send(mailMessage);
    }


    /**
     * 发送文本邮件和附件
     * @author ZMH
     * @date 7/7/2023 2:01 下午
     * @param subject 主题
     * @param text 文本内容
     * @param targetEmail 目标邮件
     * @param sourceEmail 源邮件
     * @param annexList 附件List
     * @param anneNameList 附件名称List
     * @return void
     */
    public void sendTextAndAnnexEmail(String subject,String text,String targetEmail,String sourceEmail,
                                      String personal, List<File> annexList,List<String> anneNameList ) throws MessagingException {
        sendSeniorEmail(subject,null,false,text,targetEmail,sourceEmail,personal,annexList,anneNameList);
    }




    /**
     * 发送邮件根据HTML模本文件
     * @author ZMH
     * @date 7/7/2023 11:16 上午
     * @param subject 主题
     * @param content 内容
     * @param targetEmail 目标邮件
     * @param sourceEmail 源邮件
     * @return void
     */
    public void sendHTMLEmail(String subject,String content,String targetEmail,String sourceEmail,String personal) throws MessagingException {
        sendSeniorEmail(subject,content,true,"",targetEmail,sourceEmail,personal,null,null);
    }

    /**
     * 发送模版文件并包含附件
     * @author ZMH
     * @date 7/7/2023 11:20 上午
     * @param subject 主题
     * @param content 内容
     * @param targetEmail 目标邮件
     * @param sourceEmail 源邮件
     * @param annexList 附件
     * @param annexNameList 附件名称
     * @return void
     */
    public void sendHTMLAndAnnexEmail(String subject,String content,String targetEmail,
                              String sourceEmail,String personal,List<File> annexList,List<String> annexNameList) throws MessagingException {
        sendSeniorEmail(subject,content,true,"",targetEmail,sourceEmail,personal,annexList,annexNameList);
    }



    /**
     * 发送高级邮件
     * @author ZMH
     * @date 7/7/2023 11:26 上午
     * @param subject 主题
     * @param concent content
     * @param targetEmail 目标邮箱
     * @param sourceEmail 源邮箱
     * @param annexList 附件
     * @param annexNameList 附件名称
     * @return void
     */
    private void sendSeniorEmail(String subject, String concent, Boolean isHtml, String txet, String targetEmail,
                                 String sourceEmail,String personal, List<File> annexList, List<String> annexNameList) throws MessagingException{
        System.setProperty("mail.mime.splitlongparameters", "false");//1.设置系统值 ---处理文件名乱码
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,true,"utf-8");
        helper.setSubject(subject);//邮件主题
        try {
            helper.setFrom(sourceEmail,personal);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotBlank(targetEmail) && targetEmail.split(",").length>1){
            helper.setTo(targetEmail.split(","));//多个号码发送,该发送为分组发送
        }else {
            helper.setTo(targetEmail);
        }
        if (isHtml) {
            //String absolutePath = htmlFile.getAbsolutePath();
            //String htmlModel = FileUtil.getStringByFile(absolutePath);
             concent = "\n" +
                    "\n" +
                    "\n" +
                    "    \n" +
                    "    \n" +
                    "    \n" +
                    "\n" +
                    "\n" +
                    "  
" + concent + "
\n"
+ "\n" + ""; helper.setText(concent,true); }else { helper.setText(txet,false); } helper.setSentDate(new Date());//邮件发送时间 if (!CollectionUtils.isEmpty(annexList)){ if (CollectionUtils.isEmpty(annexNameList)){ for (File file : annexList) { annexNameList.add(file.getName()); } }else { if (annexList.size()!= annexNameList.size()){ throw new MessagingException("附件名称和附件条次不一致"); } } try { for (int i = 0; i < annexList.size(); i++) { helper.addAttachment(MimeUtility.encodeWord(annexNameList.get(i), "utf-8", "B"), annexList.get(i)); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } javaMailSender.send(message); } }

yml配置文件增加

spring:
  mail:
    username: 邮箱号码
    password: 授权码
    host: smtp.qq.com
    port: 465
    properties:
      mail:
        smtp:
          auth: true
          socketFactory:
            class: javax.net.ssl.SSLSocketFactory
          starttls:
            enable: true
          ssl:
            enable: true

pom.xml 增加

	  
	  <dependency>
		  <groupId>org.springframework.bootgroupId>
		  <artifactId>spring-boot-starter-mailartifactId>
	  dependency>

你可能感兴趣的:(开发语言,spring,boot,spring)