In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is about how Springboot integrates email services. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it with the editor.
Introduction
Mail service is one of the commonly used services, which has many functions, such as sending activities and marketing advertisements to users externally, and sending system monitoring reports and alarms internally.
This article will introduce how Springboot integrates mail services, and give the integrated configuration of different mail service providers.
As shown in the figure:
Development process Springboot building
The construction of Springboot is very simple. We use Spring Initializr to build, which is very convenient. By selecting the module you need, you can quickly build the project:
Introduce dependency
In order to use the mail service, we need to introduce related dependencies, which can be added to the following dependency for Springboot:
Org.springframework.boot spring-boot-starter-mail profile
You need to configure the relevant parameters of the mail service provider, such as service address, user name and password, etc. The following example is the configuration of QQ, where the password is not a QQ password, but a QQ authorization code. We'll talk about how to get it later.
The configuration file application.yml for Springboot is as follows:
Server: port: 8080spring: profiles: active: qq---spring: profiles: qq mail: host: smtp.qq.com username: xxx@qq.com password: xxx properties: mail: smtp: auth: true starttls: enable: true required: true---spring: profiles: netEase mail: host: smtp.163.com username: xxx@163.com Password: xxx properties: mail: smtp: auth: true starttls: enable: true required: true to implement sending service
After injecting JavaMailSender and assembling the Message, you can send the simplest text mail.
@ Autowiredprivate JavaMailSender emailSender;public void sendNormalText (String from, String to, String subject, String text) {SimpleMailMessage message = new SimpleMailMessage (); message.setFrom (from); message.setTo (to); message.setSubject (subject); message.setText (text); emailSender.send (message);} call API
After the service call is implemented, expose the REST interface through Controller. The specific code is as follows:
@ Value ("${spring.mail.username}") private String username;@Autowiredprivate MailService mailService;@GetMapping ("/ normalText") public Mono sendNormalText () {mailService.sendNormalText (username, username, "Springboot Mail (NormalText)", "This is a mail from Springboot!"); return Mono.just ("sent");}
Inject the implemented MailService into the Controller and call the corresponding method. The sender and recipient of this email are the same account, and the actual implementation can be flexibly configured.
Test whether it can be sent normally by calling the API Postman:
Successfully returned "sent", and received an email, the test passed.
Multiple types of mail simple text mail
How to send a simple text email has just been explained, so I won't repeat it.
HTML Mail
Although plain text has been able to meet many needs, it often needs richer styles to improve the expressiveness of email. HTML type mail is very useful at this time.
The Service code is as follows:
Public void sendHtml (String from, String to, String subject, String text) throws MessagingException {MimeMessage message = emailSender.createMimeMessage (); MimeMessageHelper helper = new MimeMessageHelper (message, true); helper.setFrom (from); helper.setTo (to); helper.setSubject (subject); helper.setText (text, true); emailSender.send (message);}
Unlike simple text, MimeMessage and MimeMessageHelper are used this time, which is a very useful class, which we will often use later, and the combination can greatly enrich the e-mail presentation.
The code for Controller is as follows:
@ GetMapping ("/ html") public Mono sendHtml () throws MessagingException {mailService.sendHtml (username, username, "Springboot Mail (HTML)", "This is a mail from Springboot!"); return Mono.just ("sent");} message with attachment
It is perfectly normal to send files by mail. You need to use the MimeMessageHelper.addAttachment (String attachmentFilename, InputStreamSource inputStreamSource) method to send attachments. The first parameter is the attachment name, and the second parameter is the file stream resource. The Service code is as follows:
Public void sendAttachment (String from, String to, String subject, String text, String filePath) throws MessagingException {MimeMessage message = emailSender.createMimeMessage (); MimeMessageHelper helper = new MimeMessageHelper (message, true); helper.setFrom (from); helper.setTo (to); helper.setSubject (subject); helper.setText (text, true); FileSystemResource file = new FileSystemResource (new File (filePath); helper.addAttachment (filePath, file); emailSender.send (message);}
The Controller code is as follows:
@ GetMapping ("/ attachment") public Mono sendAttachment () throws MessagingException {mailService.sendAttachment (username, username, "Springboot Mail (Attachment)", "Please check the attachment!", "/ Pictures/postman.png"); return Mono.just ("sent");} message with static resources
In fact, the web page we visit is also a HTML, which can bring a lot of static resources, such as pictures, videos and so on. The Service code is as follows:
Public void sendStaticResource (String from, String to, String subject, String text, String filePath, String contentId) throws MessagingException {MimeMessage message = emailSender.createMimeMessage (); MimeMessageHelper helper = new MimeMessageHelper (message, true); helper.setFrom (from); helper.setTo (to); helper.setSubject (subject); helper.setText (text, true); FileSystemResource file = new FileSystemResource (new File (filePath); helper.addInline (contentId, file); emailSender.send (message);}
Where contentId is the ID of static resources in HTML, which needs to be well addressed.
The Controller code is as follows:
@ GetMapping ("/ inlinePicture") public Mono sendStaticResource () throws MessagingException {mailService.sendStaticResource (username, username, "Springboot Mail (StaticResource)", "With inline picture"
"," / Pictures/postman.png "," picture "); return Mono.just (" sent ");} template message
Java has many template engines, such as Freemarker, Thymeleaf, Velocity, etc., which is not the focus of this point, so only use Freemarker as an example.
The Service code is as follows:
Autowiredprivate FreeMarkerConfigurer freeMarkerConfigurer;public void sendTemplateFreemarker (String from, String to, String subject, Map model, String templateFile) throws Exception {MimeMessage message = emailSender.createMimeMessage (); MimeMessageHelper helper = new MimeMessageHelper (message, true); helper.setFrom (from); helper.setTo (to); helper.setSubject (subject); Template template = freeMarkerConfigurer.getConfiguration (). GetTemplate (templateFile); String html = FreeMarkerTemplateUtils.processTemplateIntoString (template, model); helper.setText (html, true); emailSender.send (message);}
Note that you need to inject FreeMarkerConfigurer, then use FreeMarkerTemplateUtils to parse the template, return String, and then send it as content.
The Controller code is as follows:
@ GetMapping ("/ template") public Mono sendTemplateFreemarker () throws Exception {Map model = new HashMap (); model.put ("username", username); model.put ("templateType", "Freemarker") MailService.sendTemplateFreemarker (username, username, Springboot Mail (Template), model, "template.html"); return Mono.just ("sent");}
Note that the template file template.html should be placed under the * * resources/templates/** directory so that it can be found.
The template is as follows:
TitleHello ${username} This is a mail from Springboot using ${templateType}
Where ${username} and ${templateType} are variable names that need to be replaced, Freemarker provides a lot of rich variable expressions, which are not covered here.
Integrate different mail service providers
There are many mail service providers, and the most commonly used mailboxes in China are QQ Mail and NetEase.
To integrate QQ email, you need to have a necessary account and an authorization code. After activating the authorization code, you can configure it for use. The official documents are as follows:
What is the authorization code and how is it set?
It should be noted that to activate the authorization code, you need to use the bound mobile phone number to send text messages to a specific number. If the phone is not bound or the phone is not available, it will affect the activation.
After activation, the authorization code will be configured in the file as a password.
one hundred and sixty three
NetEase's activation method is not much different from that of QQ. For specific instructions, please see the following official documents:
How do I open the client authorization code?
It is also necessary to bind a mobile phone to operate.
Summary
After this example is sent, you receive the email as shown in the figure:
Email is powerful and Springboot is easy to integrate. The sharp weapon of technology, make good use of but not abuse.
The above is how Springboot integrates email services, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.