Spring Boot uses javamailsender to send mail

Source: Internet
Author: User

Spring provides a very useful Javamailsender interface for mail delivery. the corresponding automation configuration is also available in Spring Boot.

This article is mainly about how to use javamailsender to send messages in Spring Boot .

Send mail

1, the introduction of Spring-boot-starter-mail dependency in pom.xml :

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId> Spring-boot-starter-mail</artifactid></dependency>

2, Configure the appropriate properties in application.properties :( I'm simulating 163 here. e-mail to QQ mail )

spring.mail.host=smtp.163. comspring.mail.username= Mailbox User name so****@163. Comspring.mail.password= email password spring.mail. default-encoding=utf-8

3, write the test class to send the message

ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.mail.SimpleMailMessage;ImportOrg.springframework.mail.javamail.JavaMailSender;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController, @RestController @requestmapping ("/mail") Public classMailcontroller {Private FinalLogger Logger = Loggerfactory.getlogger ( This. GetClass ()); @AutowiredPrivateJavamailsender MailSender; @RequestMapping ("/send") Public voidSendMail () {simplemailmessage message=NewSimplemailmessage (); Message.setfrom ("So****@163.com"); Message.setto ("239**** @qq. com"); Message.setsubject ("It's a test for spring boot"); Message.settext ("Hello, I am Xiao Huang, I am testing to send mail." "); Try{mailsender.send (message); Logger.info ("The small yellow test message was sent. "); } Catch(Exception e) {logger.error ("Little Yellow sent a message when an exception occurred!" ", E); }    }}

4. Run the Startup class

ImportOrg.mybatis.spring.annotation.MapperScan;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.EnableAutoConfiguration;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication (exclude = {Datasourceautoconfiguration.class}) @EnableAutoConfiguration @mapperscan ("Cn.yideng.*.dao") Public classDemoApplication { Public Static voidMain (string[] args) {Springapplication.run (demoapplication.class, args);}} 

5, browser run http://localhost:8080/mail/send

6, login 163 Mailbox , in the Send box to view

7, login QQ mailbox , in the Inbox to view , such as

can see The Spring Boot starter module provides an automated configuration that , after the introduction of spring-boot-starter-mail dependencies, The Javamailsender instance is created based on the content in the configuration file , so we can directly @Autowired it directly where we need it to introduce Javamailsender the message to send the object.

of course, in the actual use of the process, it will not be so simple, we may require the attachment, or the use of mail modules. At this point we need to use mimemessage to set more complex right-click content, and here's how to implement it.

Send a message with an attachment

Test class : or simulate 163 mailbox to send mail to QQ mailbox

ImportJava.io.File;Importjavax.mail.MessagingException;ImportJavax.mail.internet.MimeMessage;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.core.io.FileSystemResource;ImportOrg.springframework.mail.javamail.JavaMailSender;ImportOrg.springframework.mail.javamail.MimeMessageHelper;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;/*** Send mail with attachments **/@RestController @requestmapping ("/mail") Public classAttachmentsmailcontroller {Private FinalLogger Logger = Loggerfactory.getlogger ( This. GetClass ()); @AutowiredPrivateJavamailsender MailSender; @RequestMapping ("/att") Public voidSendMail ()throwsmessagingexception{mimemessage mimemessage=Mailsender.createmimemessage (); Mimemessagehelper Helper=NewMimemessagehelper (MimeMessage,true); Helper.setfrom ("So****@163.com"); Helper.setto ("239**** @qq. com"); Helper.setsubject ("topic: Sending mail with attachments"); Helper.settext ("Hello, I am Xiao Huang, I am testing to send a message with an attachment. "); Filesystemresource file1=NewFilesystemresource (NewFile ("D:\\cat.jpg")); Filesystemresource file2=NewFilesystemresource (NewFile ("D:\\java-1.jpg")); Helper.addattachment ("Accessory -1.jpg", file1); Helper.addattachment ("Accessory -2.jpg", file2); Try{mailsender.send (mimemessage); Logger.info ("The small yellow test with the attachment of the message has been sent. "); } Catch(Exception e) {logger.error ("Small yellow sent with attachment message when an exception occurred!" ", E); }    }}

2, need to prepare two pictures under D disk cat.jpg java-1.jpg,

3, browser run http://localhost:8080/mail/att

4, login 163 Mailbox , in the Sending box to view , such as

5, login QQ mailbox , in the Inbox to view , such as

Messages embedded in static resources

There is also a kind of static resources such as embedding images, you can see the picture directly, instead of looking at the specific pictures from the nearby, to see it.

Test class:

 ImportJava.io.File;Importjavax.mail.MessagingException;ImportJavax.mail.internet.MimeMessage;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.beans.factory.annotation.Autowired;ImportOrg.springframework.core.io.FileSystemResource;ImportOrg.springframework.mail.javamail.JavaMailSender;ImportOrg.springframework.mail.javamail.MimeMessageHelper;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RestController;/*** Embedded Static resources*/@RestController @requestmapping ("/mail") Public classStaticresourcemailcontroller {Private FinalLogger Logger = Loggerfactory.getlogger ( This. GetClass ()); @AutowiredPrivateJavamailsender MailSender; @RequestMapping ("/static") Public voidSendMail ()throwsmessagingexception{mimemessage mimemessage=Mailsender.createmimemessage (); Mimemessagehelper Helper=NewMimemessagehelper (MimeMessage,true); Helper.setfrom ("So****@163.com"); Helper.setto ("239**** @qq. com"); Helper.setsubject ("topic: Embedding Static Resources"); Helper.settext ("true); //Note that the resource name Hello in addinline () must correspond to the Cid:hello in the text body.Filesystemresource file1=NewFilesystemresource (NewFile ("D:\\cat.jpg")); Helper.addinline ("Hello", file1); Try{mailsender.send (mimemessage); Logger.info ("Small yellow test embedded static resource of the message has been sent. "); } Catch(Exception e) {logger.error ("Little yellow sent a message embedded in a static resource when an exception occurred!" ", E); }    }}

It is important to note that the resource name Hello in Addinline () must be in the text body Cid:hello corresponding .

2, you need to prepare two pictures under D disk cat.jpg

3, browser run http://localhost:8080/mail/static

4, login 163 Mailbox , in the Sending box to view , such as

5, login QQ mailbox , in the Inbox to view , such as

Well, Spring boot is here to send mail using Javamailsender.

Spring Boot uses javamailsender to send mail

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.