首页 归档 标签 关于

Spring Boot 带附件的邮件发送配置

虽然 Spring Boot 提供了邮件相关的功能,但在缺少部分配置的情况下或多或少会有一些问题,如附件的文件名乱码、文件格式等问题。本文提供统一解决这类问题的配置。

一、配置文件

以 QQ 邮箱为例:

spring:
  mail:
    host: smtp.qq.com
    port: 465
    username: [email protected] # 发送邮箱账户
    password: exmaplepassword # 申请的授权码
    properties:
      mail:
        smtp:
          socketFactory:
            port: 465
            class: javax.net.ssl.SSLSocketFactory
          ssl:
            enable: true
          starttls:
            enable: true
            required: true

二、封装统一工具类

/**
 * @author Kytrun
 * @version 1.0
 * @date 2022/07/25 16:14
 */
@RequiredArgsConstructor
@Component
public class MailUtil {
    private final JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String mailFrom;

    // 长文件名不截断
    static {
        System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
    }

    /**
     * 发送纯文字邮件
     *
     * @param to      收件地址
     * @param subject 主题
     * @param text    内容
     */
    public void send(String to, String subject, String text) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setSentDate(new Date());
        mailMessage.setText(text);
        mailMessage.setFrom(mailFrom);
        mailSender.send(mailMessage);
    }

    /**
     * 发送带多个附件的邮件
     *
     * @param to       收件地址
     * @param subject  主题
     * @param text     文字内容
     * @param fileList 文件列表
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public void send(String to, String subject, String text, List<MultipartFile> fileList) throws MessagingException, UnsupportedEncodingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setFrom(mailFrom);
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(text);
        if (fileList != null && !fileList.isEmpty()) {
            for (MultipartFile file : fileList) {
                String fileName = file.getOriginalFilename() == null ? "文件" : file.getOriginalFilename();
                //解决中文附件名的问题
                fileName = MimeUtility.encodeText(fileName);
                messageHelper.addAttachment(fileName, file);
            }
        }
        mailSender.send(mimeMessage);
    }

}

· 转载请注明 https://kytrun.com/spring-boot-attachment-mail-sender/