SpringBoot整合Email(电子邮件服务)
(1)、导入starter依赖
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-mail</artifactId> 4 </dependency>
(2)、配置相关属性
1 spring.mail.username=fanqixxxx@163.com 2 #spring.mail.password 填写授权码 3 spring.mail.password=xxxxxxx 4 #spring.mail.host 填写邮箱供应的SMTP地址 5 spring.mail.host=smtp.163.com 6 spring.mail.properties.mail.smtp.ssl.enable=true
(3)、使用JavaMailSenderImpl发送邮件
1 package cn.coreqi.service; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.mail.SimpleMailMessage; 5 import org.springframework.mail.javamail.JavaMailSenderImpl; 6 import org.springframework.mail.javamail.MimeMessageHelper; 7 import org.springframework.stereotype.Service; 8 9 import javax.mail.MessagingException; 10 import javax.mail.internet.MimeMessage; 11 import java.io.File; 12 13 @Service 14 public class EmailService { 15 @Autowired 16 private JavaMailSenderImpl javaMailSender; 17 //简单邮件测试 18 public void sendSimple(){ 19 SimpleMailMessage message = new SimpleMailMessage(); 20 message.setSubject("email测试"); 21 message.setText("邮件测试内容"); 22 message.setTo("fanqixxxx@vip.qq.com"); 23 message.setFrom("fanqixxxx@163.com"); 24 javaMailSender.send(message); 25 } 26 //复杂邮件测试 27 public void sendComplicated() throws MessagingException { 28 //创建一个复杂的消息邮件 29 MimeMessage mimeMessage = javaMailSender.createMimeMessage(); 30 //用MimeMessageHelper来包装MimeMessage 31 MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true); 32 mimeMessageHelper.setSubject("email测试"); 33 mimeMessageHelper.setText("邮件测试内容"); 34 mimeMessageHelper.setTo("fanqixxxx@vip.qq.com"); 35 mimeMessageHelper.setFrom("fanqixxxx@163.com"); 36 mimeMessageHelper.addAttachment("meinv.jpg",new File("D:\\meinv.jpg")); 37 javaMailSender.send(mimeMessage); 38 39 } 40 }
*我在测试代码的过程中发生了javax.mail.MessagingException: Could not connect to SMTP host: smtp.163.com, port: 465, response: 554,后即使关闭了SSL连接还是会发生25端口异常。借鉴https://blog.csdn.net/a2279860a/article/details/59012885后怀疑是运营商封禁了我的端口,于是用中国联通的流量测试了一下通过测试。so。如果你也发生了端口问题,建议切换一下网络环境进行测试。当然这种问题的发生也不一定是网络的问题。 多说一句,移动的网垃圾的很。Google挂VPN我就忍了,很多国内的网站还要挂VPN。