Learn articles from: Springboot (10): Mail Service
Simple to use 1, POM package configuration
Add Spring-boot-starter-mail package reference inside POM Package
<Dependencies> <Dependency> <groupId>Org.springframework.boot</groupId> <Artifactid>Spring-boot-starter-mail</Artifactid> </Dependency> </Dependencies>
2. Add the mailbox configuration in Application.properties
spring.mail.host=smtp.qiye.163.com//mailbox server address [email protected]//user name Spring.mail.password=xxyyooo // Password Spring.mail.default-encoding=utf-8[email protected] //Who will send the message
3, write Mailservice, here only to propose implementation class.
@Component Public classMailserviceimplImplementsmailservice{Private FinalLogger Logger = Loggerfactory.getlogger ( This. GetClass ()); @AutowiredPrivateJavamailsender MailSender; @Value ("${mail.frommail.addr}") PrivateString from; @Override Public voidSendsimplemail (string to, string subject, string content) {Simplemailmessage message=NewSimplemailmessage (); Message.setfrom (from); Message.setto (to); Message.setsubject (subject); Message.settext (content); Try{mailsender.send (message); Logger.info ("Simple Mail has been sent. "); } Catch(Exception e) {logger.error ("An exception occurred when sending a simple message!" ", E); } }}
4, write test class for testing
@RunWith (Springrunner. Class) @SpringBootTestpublicclass mailservicetest { @Autowired Private Mailservice Mailservice; @Test publicvoidthrows Exception { Mailservice.sendsimplemail ("[email protected]", "Test Simple Mail", "Hello", "Simple Mail");} }
At this point a simple text send is complete.
Add material
But in the normal use of the process, we usually add images or attachments to the message to enrich the content of the message, the following describes how to use Springboot to send rich messages.
Sending HTML-formatted messages
Nothing else is changed in Mailservice add Sendhtmlmail method.
Public voidSendhtmlmail (string to, string subject, string content) {MimeMessage message=Mailsender.createmimemessage (); Try { //True indicates that a multipart message needs to be createdMimemessagehelper helper =NewMimemessagehelper (Message,true); Helper.setfrom (from); Helper.setto (to); Helper.setsubject (subject); Helper.settext (Content,true); Mailsender.send (message); Logger.info ("HTML message sent successfully"); } Catch(messagingexception e) {logger.error ("An exception occurred while sending an HTML message!" ", E); }}
Build HTML content in the test class, Test send
@Test Public void throws Exception { String content= "; Mailservice.sendhtmlmail ("[email protected]", "Test Simple Mail", content);}
Send a message with an attachment
Add the Sendattachmentsmail method to the Mailservice.
Public voidSendattachmentsmail (string to, string subject, string content, String filePath) {MimeMessage message=Mailsender.createmimemessage (); Try{Mimemessagehelper Helper=NewMimemessagehelper (Message,true); Helper.setfrom (from); Helper.setto (to); Helper.setsubject (subject); Helper.settext (Content,true); Filesystemresource file=NewFilesystemresource (NewFile (FilePath)); String FileName=filepath.substring (Filepath.lastindexof (file.separator)); Helper.addattachment (fileName, file); Mailsender.send (message); Logger.info ("The message with the attachment has been sent. "); } Catch(messagingexception e) {logger.error ("An exception occurred when sending messages with attachments!" ", E); }}
Multiple attachments can be added using more than onehelper.addAttachment(fileName, file)
To add a test method to a test class
@Test Public void Sendattachmentsmail () { String FilePath= "E:\\tmp\\application.log"; Mailservice.sendattachmentsmail ("[email protected]", "Subject: Mail with Attachments", "There are attachments, please check!" ", FilePath);}
Send a message with a static resource
Static resources in messages are generally referred to as pictures, and the Sendattachmentsmail method is added in Mailservice.
Public voidSendinlineresourcemail (string to, string subject, string content, String Rscpath, String rscid) {MimeMessage mess Age=Mailsender.createmimemessage (); Try{Mimemessagehelper Helper=NewMimemessagehelper (Message,true); Helper.setfrom (from); Helper.setto (to); Helper.setsubject (subject); Helper.settext (Content,true); Filesystemresource Res=NewFilesystemresource (NewFile (Rscpath)); Helper.addinline (Rscid, RES); Mailsender.send (message); Logger.info ("Messages embedded in static resources have been sent. "); } Catch(messagingexception e) {logger.error ("An exception occurred when sending messages embedded in a static resource!" ", E); }}
To add a test method to a test class
@Test Public void Sendinlineresourcemail () { = "neo006"; String content= "; = "C:\\users\\summer\\pictures\\favicon.png"; Mailservice.sendinlineresourcemail ("[email protected]", "Subject: This is an email with pictures", content, Imgpath, rscid);}
Adding multiple images can be
accomplished by using multiple lines and helper.addInline(rscId, res)
All mail delivery services have been completed.
Mail system
These are the basic services for sending mail, but there are a few things to consider if we are going to make an email system:
Mail templates
We will often receive emails like:
尊敬的neo用户: 恭喜您注册成为xxx网的用户,,同时感谢您对xxx的关注与支持并欢迎您使用xx的产品与服务。 ...
Only neo This user name in the change, the other message content is unchanged, if each send the message will need to be manually stitching is not elegant, and every time the template changes need to change the code is also very inconvenient, so for this type of mail needs, are recommended to be processed into a mail template. The essence of the template is simply to replace the changed parameters in the template and convert them to HTML strings, as thymeleaf
shown here as an example.
1, the Pom in the import thymeleaf package
< Dependency > < groupId >org.springframework.boot</groupId> < Artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency>
2. Create a emailtemplate.html under Resorces/templates
<!DOCTYPE HTML><HTMLLang= "zh"xmlns:th= "http://www.thymeleaf.org"> <Head> <MetaCharSet= "UTF-8"/> <title>Title</title> </Head> <Body>Hello, this is the verification email, please click the link below to complete the verification,<BR/> <ahref="#"Th:href= "@{Http://www.ityouknow.com/neo/{id} (Id=${id})}">Activate account</a> </Body></HTML>
3. Parse the template and send
@Test Public void Sendtemplatemail () { // Create message body new Context (); Context.setvariable ("id", "006"); = Templateengine.process ("emailtemplate", context); Mailservice.sendhtmlmail ("[email protected]", "Subject: This is template mail", emailcontent);}
Send failed
For various reasons, there will always be a failure to send mail, such as: Mail sent too frequently, network anomalies. When this happens, we generally consider retrying the sending of the message, which is divided into the following steps:
- 1, received the sending mail request, first records the request and the storage.
- 2. Call the mail sending interface to send the message and record the sent results into the library.
- 3, start the timing system scan time period, not sent successfully and retry less than 3 times of the message, to send again
Send asynchronously
Most of the time, mail delivery is not the result of our main business, such as notifying classes, reminding classes that the business can allow delays or failures. This time can be asynchronous to send mail, speed up the main transaction execution speed, in the actual project can use MQ Send message related parameters, listen to Message Queuing to start sending mail.
Before learning time is timed and send mail together, on a regular basis to send the mail! Learn more about the template of the mail! Hee Hee
Spring-boot (vi) Mail Service