In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about the five postures that must be used to send mail in SpringBoot. Many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Preface
Sending mail is actually a very common requirement, user registration, password recovery and other places, will be used, using JavaSE code to send mail, the steps are still very tedious, Spring Boot for mail sending, provides the relevant automatic configuration class, making it very easy to send mail, let's take a look at it! Take a look at the 5 postures that use Spring Boot to send mail.
Mail Foundation
We often hear about various mail protocols, such as SMTP, POP3, IMAP, so what is the purpose of these protocols and what is the difference? Let's discuss this problem first.
SMTP is an application layer protocol based on TCP/IP, and its status is similar to that of a HTTP,SMTP server listening by default, with a port number of 25. Seeing this, friends may think that since SMTP is an application layer protocol based on TCP/IP, can I also send an email through Socket? The answer is yes.
In life, we have to go through the following steps to deliver an email:
Xiao Wang from Shenzhen first delivered the mail to the post office in Shenzhen. The post office in Shenzhen delivered the mail to the post office in Shanghai. Xiao Zhang came to the post office in Shanghai to pick up the mail.
This is a scaled-down version of the email sending process in life. These three steps can correspond to our email sending process, assuming sending email from aaa@qq.com to 111@163.com:
Aaa@qq.com first delivers the mail to Tencent's mail server. Tencent's mail server delivers our mail to NetEase's mail server. 111@163.com logs in to NetEase's mail server to check the mail.
Mail delivery is roughly this process, this process involves a number of protocols, let's take a look at them separately.
The full name of SMTP protocol is Simple Mail Transfer Protocol, which is translated as simple Mail transfer Protocol. It defines the communication rules between mail client software and SMTP server, as well as between SMTP server and SMTP server.
In other words, aaa@qq.com users use SMTP protocol in the process of first delivering mail to Tencent's SMTP server, and then Tencent's SMTP server delivers mail to NetEase's SMTP server. This process still uses SMTP protocol, and SMTP server is used to receive mail.
The full name of the POP3 protocol is Post Office Protocol, which is translated as the post office protocol, which defines the communication rules between the mail client and the POP3 server, so in what scenario will the protocol be used? When the mail arrives at NetEase's SMTP server, 111@163.com users need to log in to the server to check the mail, and this is when the protocol is used: the mail service provider will provide a special mail storage space for each user. After the SMTP server receives the mail, it will save the mail to the corresponding user's mail storage space. If the user wants to read the mail, It needs to be done through the POP3 mail server of the mail service provider.
Finally, some friends may have heard of the IMAP protocol, which is an extension of the POP3 protocol with stronger functions and similar effects, so I won't repeat it here.
Preparatory work
At present, most mail service providers in China are not allowed to directly use username / password to send mail in the code. They all need to apply for the authorization code first. Here, QQ Mail is taken as an example to demonstrate the application process of the authorization code: first, we need to log in to the QQ Mail web page and click the settings button above:
Then click the account tab:
Find the option to enable POP3/SMTP in the account tab, as follows:
Click to open, turn on the relevant functions, the opening process requires mobile phone number verification, you can follow the steps, do not repeat. After opening it successfully, you can get an authorization code, save the number and use it later.
Project creation
Next, we can create a project. In Spring Boot, an automatic configuration class is provided for sending mail. Developers only need to add relevant dependencies, and then configure the basic information of the mailbox to send mail.
First create a Spring Boot project to introduce mail delivery dependencies:
After creation, the project relies on the following:
Org.springframework.boot spring-boot-starter-mail org.springframework.boot spring-boot-starter-web
Configure basic mailbox information
After the project is created successfully, configure the basic information of the mailbox in application.properties:
Spring.mail.host=smtp.qq.comspring.mail.port=587spring.mail.username=1510161612@qq.comspring.mail.password=ubknfzhjkhrbbabespring.mail.default-encoding=UTF-8spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactoryspring.mail.properties.mail.debug=true
The meanings of configuration are as follows:
Configure SMTP server address SMTP server port configuration mailbox username configuration password, note that it is not the real password, but the authorization code just applied for the default mail coding accessories SSL encryption factory indicates that the DEBUG mode is turned on, so that the log of the mail sending process will be printed on the console to facilitate troubleshooting
If you don't know the port or address of the smtp server, you can refer to Tencent's email documentation.
Https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=371
After this is done, Spring Boot will automatically configure the email sending class for us. The relevant configuration is in the org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration class. Some of the source codes are as follows:
Configuration@ConditionalOnClass ({MimeMessage.class, MimeType.class, MailSender.class}) @ ConditionalOnMissingBean (MailSender.class) @ Conditional (MailSenderCondition.class) @ EnableConfigurationProperties (MailProperties.class) @ Import ({MailSenderJndiConfiguration.class, MailSenderPropertiesConfiguration.class}) public class MailSenderAutoConfiguration {}
From this code, you can see that another configuration MailSenderPropertiesConfiguration class is imported, which provides a utility class related to sending mail:
@ Configuration@ConditionalOnProperty (prefix = "spring.mail", name = "host") class MailSenderPropertiesConfiguration {private final MailProperties properties; MailSenderPropertiesConfiguration (MailProperties properties) {this.properties = properties;} @ Bean @ ConditionalOnMissingBean public JavaMailSenderImpl mailSender () {JavaMailSenderImpl sender = new JavaMailSenderImpl (); applyProperties (sender); return sender;}}
As you can see, an instance of JavaMailSenderImpl is created here. JavaMailSenderImpl is an implementation of JavaMailSender, and we will use JavaMailSenderImpl to send mail.
After completing the above two steps, the preparation for sending the email is complete, and then you can send the email directly.
Specific transmission, there are five different ways, let's look at one by one.
Send a simple email
A simple email means that the content of the message is an ordinary text document:
@ AutowiredJavaMailSender javaMailSender;@Testpublic void sendSimpleMail () {SimpleMailMessage message = new SimpleMailMessage (); message.setSubject ("this is a test message"); message.setFrom ("1510161612@qq.com"); message.setTo ("25xxxxx755@qq.com"); message.setCc ("37xxxxx37@qq.com"); message.setBcc ("14xxxxx098@qq.com"); message.setSentDate (new Date ()); message.setText ("this is the body of the test message"); javaMailSender.send (message);}
From top to bottom, the code meaning is as follows:
Build a mail object, set the subject of the message, set the sender of the message, set the recipient of the message, you can have multiple recipients set the CC, you can have multiple CC users set the secret CC, and you can have multiple settings for the date of delivery of the message to set the body of the message to send the message
Finally, by executing this method, the mail can be sent, and the sending effect is as follows:
Send mail with attachments
Email attachments can be pictures or ordinary files, all of which are supported.
@ Testpublic void sendAttachFileMail () throws MessagingException {MimeMessage mimeMessage = javaMailSender.createMimeMessage (); MimeMessageHelper helper = new MimeMessageHelper (mimeMessage,true); helper.setSubject ("this is a test message"); helper.setFrom ("1510161612@qq.com"); helper.setTo ("25xxxxx755@qq.com"); helper.setCc ("37xxxxx37@qq.com"); helper.setBcc ("14xxxxx098@qq.com"); helper.setSentDate (new Date ()); helper.setText ("this is the body of the test message") Helper.addAttachment ("javaboy.jpg", new File ("C:\ Users\\ sang\\ Downloads\\ javaboy.png"); javaMailSender.send (mimeMessage);}
Note that there is a difference between building a mail object here and the previous article. Here, we use javaMailSender to obtain a complex mail object, and then use MimeMessageHelper to configure mail. MimeMessageHelper is an auxiliary tool class for mail configuration. True at the time of creation means to build a multipart message type of mail. With MimeMessageHelper, we configure mail on behalf of MimeMessageHelper.
Finally, add an attachment through the addAttachment method.
When this method is executed, the effect of sending mail is as follows:
Send an email with picture resources
What's the difference between picture resources and attachments? The picture resources are placed in the body of the email, that is, as soon as you open the email, you can see the picture. In general, however, this approach is not recommended, and some companies have limits on the size of the e-mail content (because it sends pictures together).
@ Testpublic void sendImgResMail () throws MessagingException {MimeMessage mimeMessage = javaMailSender.createMimeMessage (); MimeMessageHelper helper = new MimeMessageHelper (mimeMessage, true); helper.setSubject ("this is a test email"); helper.setFrom ("1510161612@qq.com"); helper.setTo ("25xxxxx755@qq.com"); helper.setCc ("37xxxxx37@qq.com"); helper.setBcc ("14xxxxx098@qq.com"); helper.setSentDate (new Date ()); helper.setText ("
Hello Hello everyone, this is a test email, this email contains two kinds of pictures, which are as follows
The first picture:
The second picture:
", true); helper.addInline (" p01 ", new FileSystemResource (" C:\ Users\\ sang\\ Downloads\ javaboy.png ")); helper.addInline (" P02 ", new FileSystemResource (" C:\ Users\ sang\\ Downloads\ javaboy2.png ")); javaMailSender.send (mimeMessage);}
The email text here is a HTML text, in which the image resources involved are first occupied by a placeholder, and the second parameter true of the setText method indicates that the first parameter is a HTML text.
After setText, add image resources through the addInline method.
Finally, the method is executed to send e-mail, and the effect is as follows:
In the actual development of the company, neither the first nor the third is the most frequently used e-mail delivery scheme. Because normally, the content of e-mail is relatively rich, so most emails are presented through HTML. If you directly concatenate HTML strings, it will be difficult to maintain in the future. In order to solve this problem, there will be corresponding email templates when e-mails are sent. The two most representative templates are the Freemarker template and the Thyemeleaf template.
Use Freemarker as a mail template
First, you need to introduce Freemarker dependencies:
Org.springframework.boot spring-boot-starter-freemarker
Then create a mail.ftl under the resources/templates directory as a mail delivery template:
Title
Hello Welcome to the xxx family. Your entry information is as follows:
Name ${username} Job number ${num} salary ${salary} work together to create resplendence
Next, render the mail template to HTML and send it.
@ Testpublic void sendFreemarkerMail () throws MessagingException, IOException, TemplateException {MimeMessage mimeMessage = javaMailSender.createMimeMessage (); MimeMessageHelper helper = new MimeMessageHelper (mimeMessage, true); helper.setSubject ("this is a test email"); helper.setFrom ("1510161612@qq.com"); helper.setTo ("25xxxxx755@qq.com"); helper.setCc ("37xxxxx37@qq.com"); helper.setBcc ("14xxxxx098@qq.com"); helper.setSentDate (new Date ()) / / build the basic configuration of Freemarker Configuration configuration = new Configuration (Configuration.VERSION_2_3_0); / / configure template location ClassLoader loader = MailApplication.class.getClassLoader (); configuration.setClassLoaderForTemplateLoading (loader, "templates"); / / load template Template template = configuration.getTemplate ("mail.ftl"); User user = new User (); user.setUsername ("javaboy"); user.setNum (1); user.setSalary ((double) 99999); StringWriter out = new StringWriter () / / template rendering, the rendered result will be saved to out, and the html string in out can be sent to template.process (user, out); helper.setText (out.toString (), true); javaMailSender.send (mimeMessage);}
It should be noted that although the automatic configuration of Freemarker is introduced, we reconfigure Freemarker directly by new Configuration here, so the default configuration of Freemarker does not take effect here, so the value is templates when filling in the template location.
Call this method to send an email. The effect is as follows:
Use Thymeleaf as a mail template
It is recommended that you use Thymeleaf in Spring Boot to build mail templates. Because the automatic configuration of Thymeleaf provides a TemplateEngine, you can easily render the Thymeleaf template to HTML through TemplateEngine, while the automatic configuration of Thymeleaf continues to be valid here.
First, introduce Thymeleaf dependencies:
Org.springframework.boot spring-boot-starter-thymeleaf
Then, create a Thymeleaf mail template:
Title
Hello Welcome to the xxx family. Your entry information is as follows:
Name and salary work together to create resplendence
Next, send an email:
@ AutowiredTemplateEngine templateEngine;@Testpublic void sendThymeleafMail () throws MessagingException {MimeMessage mimeMessage = javaMailSender.createMimeMessage (); MimeMessageHelper helper = new MimeMessageHelper (mimeMessage, true); helper.setSubject ("this is a test email"); helper.setFrom ("1510161612@qq.com"); helper.setTo ("25xxxxx755@qq.com"); helper.setCc ("37xxxxx37@qq.com"); helper.setBcc ("14xxxxx098@qq.com"); helper.setSentDate (new Date ()); Context context = new Context () Context.setVariable ("username", "javaboy"); context.setVariable ("num", "000001"); context.setVariable ("salary", "99999"); String process = templateEngine.process ("mail.html", context); helper.setText (process,true); javaMailSender.send (mimeMessage);}
After reading the above, do you have any further understanding of the five postures that must be used by SpringBoot to send mail? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
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.