1, Pom.xml Add spring-boot-starter-mail dependency
< Dependency > < groupId >org.springframework.boot</groupId> < Artifactid>spring-boot-starter-mail</artifactid> </ Dependency >
2. Add the configuration of sending mail in Application.properties
Spring.mail.host=smtp.163.comspring.mail.port=25spring.mail.username= e-mail account @163.comspring.mail.password= Authorization Code Spring.mail.default-encoding=utf-8spring.mail.properties.mail.smtp.auth= Truespring.mail.properties.mail.smtp.starttls.enable=truespring.mail.properties.mail.smtp.starttls.required= Truemail.frommail.addr= e-mail account @163.com
3, the interface to send mail
Package Com.st.service;public interface Mailservice {public void Sendsimplemail (string to, string subject, String co ntent); }
4, send the message implementation class
Package Com.st.service.impl;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.beans.factory.annotation.value;import Org.springframework.mail.simplemailmessage;import Org.springframework.mail.javamail.javamailsender;import Org.springframework.stereotype.component;import Org.springframework.stereotype.service;import Com.st.service.MailService; @Service @componentpublic 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 = NE W Simplemailmessage (); Message.setfrom (from); Message.setto (to); Message.setsubject (subject); Message.settext (content); try {Mailsender.send (message); Logger.info ("Send successfully ... "); } catch (Exception e) {logger.error ("Send failed!!!!!! ", e); } }}
5. Test class
Package Com.st;import Org.junit.test;import Org.junit.runner.runwith;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.boot.test.context.springboottest;import Org.springframework.test.context.junit4.springrunner;import Com.st.service.MailService; @RunWith ( Springrunner.class) @SpringBootTestpublic class Springbootmailapplicationtests { @Autowired private Mailservice Mailservice; Generate 6-bit random captcha int randnum = 1 + (int) (Math.random () * ((999999-1) + 1)); @Test public void Testsimplemail () throws Exception { mailservice.sendsimplemail ("Incoming mail account @qq.com", "Developing mail sending function "," Captcha: "+randnum);} }
Springboot send a simple text message