Spring Boot实现用QQ邮件发送

springboot对JMS提供了很好的支持,对其做了起步依赖。可以直接加入坐标

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

添加配置(application.properties)

spring.mail.host=smtp.qq.com
spring.mail.username=这么填写邮箱账号
#这里要用邀请码,不是你登录邮箱的密码
spring.mail.password=邀请码 
spring.mail.port=465
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true

注意:

PO3/SMTP服务必须开启
在这里插入图片描述

测试发邮件

代码如下:

import java.io.File;

import javax.mail.internet.MimeMessage;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailApplicationTests {
	@Autowired
	private JavaMailSenderImpl mailSender;
	@Test
	public void contextLoads() {
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
		// 设置收件人,寄件人
		simpleMailMessage.setTo(new String[] {"not404@foxmail.com"});
		simpleMailMessage.setFrom("not404@foxmail.com");
		simpleMailMessage.setSubject("测试邮件主题");
		simpleMailMessage.setText("测试邮件内容");
		// 发送邮件
		mailSender.send(simpleMailMessage);

		System.out.println("邮件已发送");
	}
	/**
	 * 发送包含HTML文本的邮件
	 * @throws Exception
	 */
	@Test
	public void sendHtmlMail() throws Exception {
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
		mimeMessageHelper.setTo("not404@foxmail.com");
		mimeMessageHelper.setFrom("871641773@qq.com");
		mimeMessageHelper.setSubject("测试邮件主题");

		StringBuilder sb = new StringBuilder();
		sb.append("<html><head></head>");
		sb.append("<body><h1>spring 邮件测试</h1><p>测试邮件主题</p></body>");
		sb.append("</html>");

		// 启用html
		mimeMessageHelper.setText(sb.toString(), true);
		// 发送邮件
		mailSender.send(mimeMessage);

		System.out.println("邮件已发送");

	}
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页