一:邮箱发送原理
1:狂神图解
张三通过smtp协议连接到Smtp服务器,然后发送一封邮件给网易的邮件服务器 网易分析发现需要去QQ的邮件服务器,通过Smtp协议将邮件转投给QQ的Smtp服务器 QQ将接收到的邮件存储在456789@qq.com这个邮件账号的空间中 李四通过Pop3协议连接到Pop3服务器收取邮件 从456789@qq.com这个邮件账号的空间中取出邮件 Pop3服务器将取出来的邮件送道李四手中
2:自我理解
我们在qq邮箱上申请一个账号,我们发送邮件的时候,首先是先发送到qq的邮箱服务器中,每个邮箱服务器中又包含不同功能的邮箱服务器,那么专门发送邮件的是SMTP邮箱服务器,专门接收文件的是Pop3服务器。那么邮件是通过邮箱服务器中SMTP发送给目标地址的Pop3服务器。 邮件服务器就是一个供在网上存储邮件的空间。一般每个邮件服务器的提供商都有自己的邮件服务器,只要你申请了他的邮箱账号,你就会在他的邮件服务器上拥有自己邮箱。像Google,腾讯都是邮件服务的提供商,他们都有自己的邮件服务器,如果你申请了Gamil邮箱,那么在Google的邮件服务器上面,你就有自己的一块存储空间了。同样,如果你申请了qq邮箱,那么在qq邮件服务器上面也有你自己的空间了,也就是你的邮箱。当你要收取信件的时候,你就需要连接到不同的服务器上面。不同的邮件服务提供商,他们的邮件服务器的地址是不一样的。
二:springboot上代码演示
1:导入相关的依赖
< dependency> < groupId> org. springframework. boot< / groupId> < artifactId> spring- boot- starter- mail< / artifactId> < version> 2.1 .5 . RELEASE< / version>
< / dependency>
< ! -- thymeleaf模板依赖 -- > < dependency> < groupId> org. springframework. boot< / groupId> < artifactId> spring- boot- starter- thymeleaf< / artifactId> < / dependency>
2:在application.properties配置mail
# 访问邮箱的域名 smtp表示协议
spring. mail. host= smtp. qq. com
spring. mail. username= * * * * * * * @qq. com
#授权码
spring. mail. password= * * * * * * * * * * *
spring. mail. protocol= smtps
# 采用ssl安全连接
spring. mail. properties. mail. smtp. ssl. enable= true
3:编写工具类
@Component
public class MailClient { @Autowiredprivate JavaMailSender mailSender; @Value ( "${spring.mail.username}" ) private String from; public void sendMail ( String to, String subject, String content) { try { MimeMessage message = mailSender. createMimeMessage ( ) ; MimeMessageHelper helper = new MimeMessageHelper ( message) ; helper. setFrom ( from) ; helper. setTo ( to) ; helper. setSubject ( subject) ; helper. setText ( content, true) ; mailSender. send ( helper. getMimeMessage ( ) ) ; } catch ( MessagingException e) { e. getMessage ( ) ; } } }
4:测试
@Autowiredprivate MailClient mailClient; @Autowiredprivate TemplateEngine templateEngine; @Testvoid textMailSend ( ) { mailClient. sendMail ( "2231678004@qq.com" , "Text" , "wyj" ) ; } @Testvoid textMailSend2 ( ) {
Context context = new Context ( ) ; context. setVariable ( "username" , "晓峰我是你媳妇 如花" ) ; String content = templateEngine. process ( "/mail/demo" , context) ; System. out. println ( content) ; for ( int i = 0 ; i < 20 ; i++ ) mailClient. sendMail ( "1561962503@qq.com" , "老公" , content) ; }
要发送的html页面
< ! DOCTYPE html>
< html lang= "en" xmlns: th= "http://www.thymeleaf.org" >
< head> < meta charset= "UTF-8" > < title> Title< / title>
< / head>
< body> < h1> Welcome, < span style= "color: aqua" th: text= "${username}" > < / span> < / h1>
< / body>
< / html>