1.添加jar包
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
</dependencies>
2.配置密码地址等信息(注:本demo以qq邮箱为例,各个邮箱配置方式有些许不同)
#邮件服务器地址
spring.mail.host=smtp.qq.com
# 端口号 qq邮箱需要使用SSL 端口号465或587
spring.mail.port=587
#邮箱(改为自己的邮箱地址)
spring.mail.username=xxxxxx@qq.com
#授权码(改为自己的授权码)
spring.mail.password=aaaaaaaaaaaaaaaa
spring.mail.default-encoding=UTF-8
#发送地址(与上面的邮箱地址相同)
mail.fromMail.addr=xxxxxx@qq.com
3.m
ailService
@Component public class MailServiceImpl implements MailService{ private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private JavaMailSender mailSender; @Value("${mail.fromMail.addr}") private String from; @Override public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); logger.info("简单邮件已经发送。"); } catch (Exception e) { logger.error("发送简单邮件时发生异常!", e); } } }
4.测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {
@Autowired
private MailService MailService;
@Test
public void testSimpleMail() throws Exception {
MailService.sendSimpleMail("bbbbbbbb@oo.com","test simple mail"," hello this is simple mail");
}
}
5.常见错误及可能原因:
Caused by: javax.mail.AuthenticationFailedException: 530 Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28
--未指定端口spring.mail.port=587
Caused by: com.sun.mail.smtp.SMTPSenderFailedException: 501 mail from address must be same as authorization user
--发送地址需要和配置的邮箱名称一致
Caused by: javax.mail.AuthenticationFailedException: 535 Error: ÇëʹÓÃÊÚȨÂëµÇ¼¡£ÏêÇéÇë¿´: http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
--授权码不正确
获取qq邮箱授权码方式
PC端登录qq邮箱,进入设置-账户,开启POP3/SMTP服务,根据提示信息操作即可获取授权码
参考
http://www.ityouknow.com/springboot/2017/05/06/springboot-mail.html(纯洁的微笑)