1.引入pom
org.springframework.boot spring-boot-starter-mail
2、在application.properties中添加邮箱配置
spring.mail.host=smtp.qiye.163.com //邮箱服务器地址spring.mail.username=xxx@oo.com //用户名spring.mail.password=xxyyooo //密码spring.mail.default-encoding=UTF-8mail.fromMail.addr=xxx@oo.com //以谁来发送邮件 实例:spring.mail.host=192.168.*.*spring.mail.username=wangwei3@inner.sss.comspring.mail.password=wangwei3spring.mail.default-encoding=UTF-8mail.fromMail.addr=wangwei3@inner.sss.com
3、编写mailService,这里只提供实现类。
@Component //或者@Servicepublic 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、编写test类进行测试
@RunWith(SpringRunner.class)@SpringBootTestpublic class MailServiceTest { @Autowired private MailService MailService; @Test public void testSimpleMail() throws Exception { MailService.sendSimpleMail("ityouknow@126.com","test simple mail"," hello this is simple mail"); }}
到此一个简单的邮件发送就结束了,还可以发送内容丰富的其他邮件模板,请参考
但是有坑,常见错误
解决方案:
1.开启Telnet
2.添加:-Xms512m -Xmx800m -Djava.net.preferIPv4Stack=true
如果还不行,参考下面链接,一般要更改tomcat,