SpringBoot实现简单的qq邮箱发送邮件功能

以下使用springboot(2.5.3)标准工程实现简单的qq邮箱发送邮件功能

准备工作

开启qq邮箱的POP3/SMTP服务

打开qq邮箱,点击设置->账户->开启POP3/SMTP服务
开启后如图所示:
SpringBoot实现简单的qq邮箱发送邮件功能
开启后会有一个动态码,需保存好,之后会用到


实现步骤

导入依赖

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

配置application.properties

spring.mail.username=使用者qq号
spring.mail.password=开启服务时获取到的动态码
spring.mail.host=smtp.qq.com
# 开启加密验证
spring.mail.properties.mail.smtp.ssl.enable=true

springboot测试代码

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@SpringBootTest
class SpringBoot09TestApplicationTests {

    @Autowired
    JavaMailSenderImpl mailSender;

    @Test
    void contextLoads() {
        //一个简单的邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();

        mailMessage.setSubject("blank你好呀!");
        mailMessage.setText("believe yourself!");

        mailMessage.setTo("接收者qq号");
        mailMessage.setFrom("发送者qq号");

        mailSender.send(mailMessage);
    }

    @Test
    void contextLoads2() throws MessagingException {
        //一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);

        //正文
        helper.setSubject("blank你好呀!plus");
        helper.setText("<p style=‘color: red‘>try your best!plus</p>",true);

        //附件
        helper.addAttachment("0.jpg",new File("D:\\xxx.jpg"));
        helper.addAttachment("1.png",new File("D:\\yyy.png"));

        helper.setTo("接收者qq号");
        helper.setFrom("发送者qq号");

        mailSender.send(mimeMessage);
    }
}

分别测试两个方法即可

封装发送邮件方法模板

    /**
     * 封装邮件发送方法
     *
     * @param html      multipart
     * @param subject   正文
     * @param text      正文主体
     * @throws MessagingException
     * @Author kuangshen
     */
    public void sendMail(Boolean html,String subject,String text) throws MessagingException {
        //一个复杂的邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,html);

        //正文
        helper.setSubject(subject);
        helper.setText(text,true);

        //附件
        helper.addAttachment("0.jpg",new File("D:\\xxx.jpg"));
        helper.addAttachment("1.jpg",new File("D:\\yyy.jpg"));
	//...

        helper.setTo("接收者qq号");
        helper.setFrom("发送者qq号");

        mailSender.send(mimeMessage);
    }

SpringBoot实现简单的qq邮箱发送邮件功能

上一篇:java目录下的描述


下一篇:监控SpringBoot应用的两种方式