本文以QQ邮箱为例,实现springboot邮件发送
- 邮箱设置 主要获取授权码
- 按照步骤开启服务 获取授权码
- 导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
- 配置邮件发送类
@Configuration public class TestConfig { @Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setPassword(授权码); javaMailSender.setHost("smtp.qq.com"); javaMailSender.setUsername(邮箱名称); javaMailSender.setPort(587); return javaMailSender; } }
邮箱地址,端口参数 在qq邮箱帮助中心搜索SSL获取,如下:
- 测试发送
@Autowired private JavaMailSender javaMailSender; @Test public void testSendMail() { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom("[email protected]"); simpleMailMessage.setTo("[email protected]"); simpleMailMessage.setSentDate(new Date()); simpleMailMessage.setSubject("测试"); simpleMailMessage.setText("简单邮件可以直接构建一个SimpleMailMessage对象进行配置,配置完成后,通过JavaMailSender将邮件发送出去"); javaMailSender.send(simpleMailMessage); }