In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what are the methods of sending Spring Boot mail". In the daily operation, I believe that many people have doubts about the method of sending Spring Boot mail. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "what are the methods of sending Spring Boot mail?" Next, please follow the editor to study!
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 in Shenzhen first delivered the mail to the post office in Shenzhen.
The post office in Shenzhen transports the mail to the post office in Shanghai.
Xiao Zhang from Shanghai came to the post office 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 delivers the mail to Tencent's mail server first.
Tencent's mail server delivers our mail to NetEase's mail server.
111@163.com logs in to NetEase's mail server to check email
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:
P266
Then click the account tab:
P267
Find the option to enable POP3/SMTP in the account tab, as follows:
P268
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.com spring.mail.port=587 spring.mail.username=1510161612@qq.com spring.mail.password=ubknfzhjkhrbbabe spring.mail.default-encoding=UTF-8 spring.mail.properties.mail.smtp.socketFactoryClass=javax.net.ssl.SSLSocketFactory spring.mail.properties.mail.debug=true
The meanings of configuration are as follows:
Configure the SMTP server address
Port of the SMTP server
Configure mailbox user name
Configure the password, note that it is not the real password, but the authorization code you just applied for
Default message encoding
Accessories SSL encryption factory
Indicates that DEBUG mode is enabled, 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:
@ Autowired JavaMailSender javaMailSender; @ Test public void sendSimpleMail () {SimpleMailMessage message = new SimpleMailMessage (); message.setSubject ("this is a test email"); 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 message subject
Set up the message sender
Set up mail recipients, which can have multiple recipients
Set up a CC. There can be multiple CC.
Set up secret CC, there can be more than one
Set the date the message was sent
Set the body of the message
Send an email
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.
@ Test public void sendAttachFileMail () 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 ("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).
@ Test public 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.
@ Test public 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:
@ Autowired TemplateEngine templateEngine; @ Test public 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);}
Call this method to send an email. The effect is as follows:
At this point, the study of "what are the methods of sending Spring Boot mail" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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.