SpringBoot JavaMailSender发送邮件功能

时间:2021-05-20

本文实例为大家分享了SpringBoot JavaMailSender发送邮件的具体代码,供大家参考,具体内容如下

引入Maven依赖包

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

163邮箱

application.properties

#####163邮箱########spring.mail.host=smtp.163.comspring.mail.username=*****@163.com#163邮箱密码spring.mail.password=!@#$%^&*spring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=truespring.mail.properties.mail.smtp.starttls.required=true

运行类:

import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)@SpringBootTest(classes=Application.class)public class My163MailTest { @Autowired private JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String username; @Test public void testSendSimple() { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(username); message.setTo("*******@qq.com"); message.setSubject("标题:测试标题"); message.setText("测试内容部份"); javaMailSender.send(message); }}

QQ邮箱和163邮箱的区别是需要设置授权码而不是密码,具体操作参考: 地址

application.properties

######qq邮箱########spring.mail.host=smtp.qq.comspring.mail.username=******@qq.com#QQ邮箱授权码spring.mail.password=xuojxtkdojvzbhjjspring.mail.properties.mail.smtp.auth=truespring.mail.properties.mail.smtp.starttls.enable=truespring.mail.properties.mail.smtp.starttls.required=true

运行类:

import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.mail.SimpleMailMessage;import org.springframework.mail.javamail.JavaMailSender;import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)@SpringBootTest(classes=Application.class)public class MyQQMailTest { @Autowired private JavaMailSender javaMailSender; @Value("${spring.mail.username}") private String username; @Test public void testSendSimple() { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(username); message.setTo("******@qq.com"); message.setSubject("标题:测试标题"); message.setText("测试内容部份"); javaMailSender.send(message); }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章