陕西省交通建设集团公司西商分公司网站/google网站推广
一、名词概念解释
- 什么是POP3、SMTP和IMAP?
简单的说:POP3和IMAP是用来从服务器上下载邮件的。SMTP适用于发送或中转信件时找到下一个目的地。所以我们发送邮件应该使用SMTP协议。
POP3、SMTP和IMAP协议介绍
IMAP和POP3有什么区别? - 什么是免费邮箱客户端授权码功能?
邮箱客户端授权码是为了避免您的邮箱密码被盗后,盗号者通过客户端登录邮箱而独特设计的安防功能。
二、 整合邮件发送功能
引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
QQ邮箱配置
官方配置说明:参考官方帮助中心
获取客户端授权码:参考官方帮助中心
详细的配置如下:
spring:mail:host: smtp.qq.com #发送邮件服务器username: xx@qq.com #QQ邮箱password: xxxxxxxxxxx #客户端授权码protocol: smtp #发送邮件协议properties.mail.smtp.auth: trueproperties.mail.smtp.port: 465 #端口号465或587properties.mail.display.sendmail: Javen #可以任意properties.mail.display.sendname: Spring Boot Guide Email #可以任意properties.mail.smtp.starttls.enable: trueproperties.mail.smtp.starttls.required: trueproperties.mail.smtp.ssl.enable: truedefault-encoding: utf-8
说明:开启SSL时使用587端口时无法连接QQ邮件服务器
网易系(126/163/yeah)邮箱配置
网易邮箱客户端授码:参考官方帮助中心
客户端端口配置说明:参考官方帮助中心
详细的配置如下:
spring:mail:host: smtp.126.comusername: xx@126.compassword: xxxxxxxxprotocol: smtpproperties.mail.smtp.auth: trueproperties.mail.smtp.port: 994 #465或者994properties.mail.display.sendmail: Javenproperties.mail.display.sendname: Spring Boot Guide Emailproperties.mail.smtp.starttls.enable: trueproperties.mail.smtp.starttls.required: trueproperties.mail.smtp.ssl.enable: truedefault-encoding: utf-8from: xx@126.com
特别说明:
- 126邮箱SMTP服务器地址:smtp.126.com,端口号:465或者994
- 163邮箱SMTP服务器地址:smtp.163.com,端口号:465或者994
- yeah邮箱SMTP服务器地址:smtp.yeah.net,端口号:465或者994
三、发送简单邮件
@Service
public class MailService {@Resourceprivate JavaMailSender mailSender;@Value("${spring.mail.username}")private String fromEmail;/*** 发送文本邮件*/public void sendSimpleMail(String to, String subject, String content) {SimpleMailMessage message = new SimpleMailMessage();message.setFrom(fromEmail);message.setTo(to);message.setSubject(subject);message.setText(content);mailSender.send(message);}}
测试代码:
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {@ResourceMailService mailService;@Testpublic void sendSimpleMail() {mailService.sendSimpleMail("431899405@qq.com","普通文本邮件","普通文本邮件内容测试");}
}