springboot发送邮件

springboot发送邮件

概述

使用场景

  1. 注册验证
  2. 营销推送
  3. 触发机制
  4. 监控报警

邮件传输协议

  1. SMTP协议:全称为 Simple Mail Transfer Protocol,简单邮件传输协议。它定义了邮件客户端软件和SMTP邮件服务器之间,以及两台SMTP邮件服务器之间的通信规则。
  2. POP3协议:全称为 Post Office Protocol,邮局协议。它定义了邮件客户端软件和POP3邮件服务器的通信规则。
  3. IMAP协议:全称为 Internet Message Access Protocol,Internet消息访问协议,它是对POP3协议的一种扩展,也是定义了邮件客户端软件和IMAP邮件服务器的通信规则。

springboot发送邮件

准备邮箱

开启服务,新增授权密码

引入依赖

pom.xml依赖spring-boot-starter-mail模块:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

添加配置

spring:
	#邮件
  mail:
    host: smtp.163.com
    # 你的163邮箱
    username: 163发送邮箱
    # 注意这里不是邮箱密码,而是SMTP授权密码
    password: smtp授权码
    port: 25
    protocol: smtp
    default-encoding: UTF-8

代码

服务类

@Slf4j
@Service
public class MailService {
    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 设置邮件附件名不被截取,解决附件中文名乱码问题
     */
    public MailService() {
        System.setProperty("mail.mime.splitlongparameters", "false");
    }

    /**
     * 简单文本邮件
     *
     * @param to      接收者邮件
     * @param subject 邮件主题
     * @param contnet 邮件内容
     */
    public void sendSimpleMail(String to, String subject, String contnet) {

        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(contnet);
        message.setFrom(from);

        mailSender.send(message);
    }

    /**
     * HTML 文本邮件
     *
     * @param to      接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @throws MessagingException
     */
    public void sendHtmlMail(String to, String subject, String contnet) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(contnet, true);
        helper.setFrom(from);

        mailSender.send(message);
    }

    /**
     * 附件邮件
     *
     * @param to       接收者邮件
     * @param subject  邮件主题
     * @param contnet  HTML内容
     * @param filePath 附件路径
     * @throws MessagingException
     */
    public void sendAttachmentsMail(String to, String subject, String contnet,
                                    String filePath) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(contnet, true);
        helper.setFrom(from);

        FileSystemResource file = new FileSystemResource(new File(filePath));
        String fileName = file.getFilename();
        helper.addAttachment(fileName, file);

        mailSender.send(message);
    }

    /**
     * 图片邮件
     *
     * @param to      接收者邮件
     * @param subject 邮件主题
     * @param contnet HTML内容
     * @param rscPath 图片路径
     * @param rscId   图片ID
     * @throws MessagingException
     */
    public void sendInlinkResourceMail(String to, String subject, String contnet,
                                       String rscPath, String rscId) {
        log.info("发送静态邮件开始: {},{},{},{},{}", to, subject, contnet, rscPath, rscId);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;

        try {

            helper = new MimeMessageHelper(message, true);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(contnet, true);
            helper.setFrom(from);

            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);
            mailSender.send(message);
            log.info("发送静态邮件成功!");

        } catch (MessagingException e) {
            log.info("发送静态邮件失败: ", e);
        }

    }

}

测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes = HealthApplication.class)
public class MailServiceTest {
    @Autowired
    private MailService mailService;
    private String toMail = "1048579371@qq.com";

    @Test
    public void sendSimpleMail() {
        mailService.sendSimpleMail(toMail,"测试spring boot imail-主题","测试spring boot imail - 内容");
    }

    @Test
    public void sendHtmlMail() throws MessagingException {

        String content = "<html>\n" +
                "<body>\n" +
                "<h3>hello world</h3>\n" +
                "<h1>html</h1>\n" +
                "<body>\n" +
                "</html>\n";

        mailService.sendHtmlMail(toMail,"这是一封HTML邮件",content);
    }

    @Test
    public void sendAttachmentsMail() throws MessagingException {
        String filePath = "/Users/liufq/Downloads/心电获客排名2020-08-26 16_26_54.xlsx";
        String content = "<html>\n" +
                "<body>\n" +
                "<h3>hello world</h3>\n" +
                "<h1>html</h1>\n" +
                "<h1>附件传输</h1>\n" +
                "<body>\n" +
                "</html>\n";
        mailService.sendAttachmentsMail(toMail,"这是一封HTML邮件",content, filePath);
    }

    @Test
    public void sendInlinkResourceMail() throws MessagingException {
        //TODO 改为本地图片目录
        String imgPath = "/ijiangtao/img/blob/dd9899b4cf95cbf074ddc4607007046c022564cb/blog/animal/dog/dog-at-work-with-computer-2.jpg?raw=true";
        String rscId = "admxj001";
        String content = "<html>" +
                "<body>" +
                "<h3>hello world</h3>" +
                "<h1>html</h1>" +
                "<h1>图片邮件</h1>" +
                "<img src='cid:"+rscId+"'></img>" +
                "<body>" +
                "</html>";

        mailService.sendInlinkResourceMail(toMail,"这是一封图片邮件",content, imgPath, rscId);
    }

}

部署

在生产环境,一般邮件服务会单独部署,并通过HTTP或MQ等方式暴露出来。

问题

附件显示名中文乱码的解决

原因:编码后的文件名长度如果大于60并且splitLongParameters的值为true,encodeParameters的值为true,文件名就会被截取

service的构造中添加设置,或在主启动类中添加设置

 public MailService() {
        System.setProperty("mail.mime.splitlongparameters", "false");
    }

550 User has no permission

发送方邮箱为开启smtp授权

参考资料

https://blog.csdn.net/sinat_26342009/article/details/89425836

posted @ 2020-08-28 16:30  dev_liufq  阅读(283)  评论(0编辑  收藏  举报