springboot使用gmail发送邮件
温馨提示:
本文最后更新于 2024年09月18日,已超过 318 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
一.准备
登录gmail邮箱,找到设置-查询所有设置-forwarding and POP/IMAP 。 开启POP 和IMAP
必须先开启两步验证,在两步验证页面底部生成专属密码
参考https://support.google.com/accounts/answer/185833?sjid=8842516791271134821-AP#
1转到您的Google 帐户。
2选择安全。
3在“登录 Google”下,选择两步验证。
4在页面底部,选择应用程序密码。
5输入可帮助您记住将在何处使用应用密码的名称。
6选择生成。
7要输入应用程序密码,请按照屏幕上的说明进行操作。应用程序密码是在您的设备上生成的 16 个字符的代码。
8选择完成。
找不到直接访问https://myaccount.google.com/apppasswords
选择mail和 computer 生成对应的专用密码
二. springboot配置
安装依赖
<!--发送邮件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
gmail配置
spring.mail.host=smtp.gmail.com
spring.mail.username=xxxx@gmail.com
spring.mail.password=申请的专用密码
spring.mail.properties.mail.smtp.port=465
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.connectiontimeout=6000
spring.mail.properties.mail.smtp.timeout=5000
spring.mail.properties.mail.smtp.writetimeout=5000
spring.mail.default-encoding=utf-8
使用(junit测试)
@Resource
JavaMailSender javaMailSender;
@Test
//方法5个参数分别表示:邮件发送者、收件人、抄送人、邮件主题以及邮件内容
public void sendSimpleMail() {
// 简单邮件直接构建一个 SimpleMailMessage 对象进行配置并发送即可
SimpleMailMessage simpMsg = new SimpleMailMessage();
simpMsg.setFrom("xxxx@gmail.com");//此处的邮箱要和配置中的邮箱一致
//如果需要设置别名,则将以上写法修改为如下方式
simpMsg.setFrom("王小虎"+"<xxxx@gmail.com>");
simpMsg.setTo("xxxx@163.com");
simpMsg.setSubject("Login Code");
simpMsg.setText("your login code is 9537");
javaMailSender.send(simpMsg);
}
正文到此结束
- 本文标签: Java Spring Boot
- 本文链接: https://www.tianyajuanke.top/article/85
- 版权声明: 本文由吴沛芙原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权