SpringBoot整合email

Java
273
0
0
2024-02-26
标签   SpringBoot

构建项目(以QQ邮箱为例)

构建SpringBoot项目(web)

pom.xml

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

application.properties(敲黑板)

spring.mail.username为你QQ邮箱

spring.mail.password不是不是不是 你的邮箱密码,是授权码,授权码,授权码 (授权码获取方式在下面有)

######################################
###Email
######################################
spring.mail.host=smtp.qq.com
#spring.mail.host=14.17.57.241
spring.mail.username=2568230656@qq.com
spring.mail.password=nezkixooldtw
spring.mail.default-encoding=UTF-8
spring.mail.port=465
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.debug=true

EmailService

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

	@Autowired
	private JavaMailSender mailSender;

	// 发送简单邮件
	/**
	 * 
	 * @param from
	 *            发送方
	 * @param to
	 *            接收方
	 * @param subject
	 *            主题
	 * @param text
	 *            内容
	 */
	public void sendSimpleMail(String from, String to, String subject, String text) {

		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(to);
		message.setSubject(subject);
		message.setText(text);
		mailSender.send(message);
	}
}

EmailController

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class EmailController {

	@Autowired
	private EmailService emailService;

	@RequestMapping("/email")
	@ResponseBody
	public String sendEmail() {

		// 发送邮件
		emailService.sendSimpleMail("2568230656@qq.com", "956056312@qq.com", "主题:简单邮件", "测试邮件内容");

		return "success";
	}

}

测试

http://localhost:8080/email

遇到的坑

异常

exception

具体异常记不清楚,我把异常用谷歌翻译的大体意思是 smtp.qq.com解析不到

解决办法

确保 ①用户名、②密码(授权码)、③编码 、④邮箱开启POP3/SMTP服务 没有问题的基础之上,用URL地址 ,查询 (smtp.qq.com)或者 (smtp.163.com)的ip地址,将配置文件中的域名改为你查询到的ip地址,如下所示

#spring.mail.host=smtp.qq.com
spring.mail.host=14.18.245.164

发送邮箱运行太慢

表现形式:

请求URL后要转圈圈很长一段时间

解决办法:异步加载

1)在方法上添加注解@Async

@Async
	public void sendSimpleMail(String from, String to, String subject, String text) {

		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);
		message.setTo(to);
		message.setSubject(subject);
		message.setText(text);
		mailSender.send(message);
	}

2)在启动类上开启异步注解功能@EnableAsync

@SpringBootApplication
@EnableAsync//开启异步注解功能
public class SpringBootDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootDemoApplication.class, args);
	}

}

邮箱授权码的获取(以QQ邮箱为例)