“This is the second day of my participation in the First Challenge 2022.
๐จ๐ Author: Bug Bacteria
โ๏ธ blog: CSDN, Nuggets, etc
๐ public account: Magic House of the Circle of the Apes
๐ซ special statement: original is not easy, reprint please attach the original source link and this article statement, thank you for your cooperation.
๐ Copyright notice: part of the text or pictures in the article may come from the Internet or Baidu Encyclopedia, if there is infringement, please contact bug bacteria processing.
Hi, family. I’m the bug. Here I go again. Today we are going to talk about something, OK, and we will continue the Series of articles on SpringBoot. Hope to help more beginners quickly start!
In the process of reviewing articles, if you think the articles are helpful to you at all, please don’t be too mean with your likes and bravely light up the articles ๐. Your likes (collect โญ๏ธ+ pay attention to ๐จ port + message board) are the best encouragement and support for bugs on my creation path. Time does not abandon ๐๐ปโ๏ธ, creation stopped ๐, refueling ๐ป
A: the preface
First of all, let’s review last time: we did all the setup work, right? The first is the acquisition of QQ mailbox verification code, the second is the introduction of POM dependency, and the third is yamL file configuration. If you have a small partner directly inserted midway, please also bother to see the preparation article “Springboot series (12) : how to code to send email reminders (preparation)”, good log? Otherwise directly open this period to follow knock, will certainly step on the pit.
Ok! Let’s get to today’s topic! How to send simple mail? Let’s move on.
Second, the body
1. First of all, let’s define a Builder, which is used to write mail sending and other related business code blocks.
/** * @author luoYong * @version 1.0 * @date 2022/1/18 9:36 */ @component public class SendMailBuild {@autowired private JavaMailSender javaMailSender; @Autowired private SpringTemplateEngine templateEngine; // create template engine // define method}Copy the code
Actually do this also is for the convenience of code maintenance in the future, if it is sent directly to the mail content assignment, that if the email field increased or changed, then you only have to move the delivery method, the basic low coupling thinking as you do not have what relation, moreover, the basic module will be exquisite packaging, code can encapsulate encapsulation, as far as possible can reuse, reuse, Eliminating redundant code, improving code quality is something we must pay attention to in daily operations. So that makes it easy to understand.
Next, we define a message body to hold the contents of the outgoing message.
package com.example.demo.component.mail.model; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; /** @author luoYong * @version 1.0 * @date 2022/1/18 9:37 */ @apimodel (value = "basic email parameters ",description = "Basic Mail ") public class Mail {@apiModelProperty (" sender email account ") private String sendMailAccount; @apiModelProperty (" recipient email account ") private String acceptMailAccount; @APIModelProperty (" email theme ") private String theme; @apiModelProperty (" email content ") private String mailText; @APIModelProperty (" sendTime ") private Date sendTime = new Date(); public String getTheme() { return theme; } public void setTheme(String theme) { this.theme = theme; } public String getSendMailAccount() { return sendMailAccount; } public void setSendMailAccount(String sendMailAccount) { this.sendMailAccount = sendMailAccount; } public String getAcceptMailAccount() { return acceptMailAccount; } public void setAcceptMailAccount(String acceptMailAccount) { this.acceptMailAccount = acceptMailAccount; } public Date getSendTime() { return sendTime; } public void setSendTime(Date sendTime) { this.sendTime = sendTime; } public String getMailText() { return mailText; } public void setMailText(String mailText) { this.mailText = mailText; }}Copy the code
Next, let’s write a way to send mail first, to achieve the function of sending mail first.
To construct an email body, you need to define the email address of the sender, email subject, email body, and email notification time.
Let’s start with the following code:
Public void sendSimpleMail(Mail model) {SimpleMailMessage MSG = new SimpleMailMessage(); Msg.setfrom (model.getsendMailAccount ()); / / mail recipients MSG. SetTo (model. GetAcceptMailAccount ()); Msg.setsubject (model.getTheme()); Msg.settext (model.getmailText ()); Msg.setsentdate (model.getsendTime ()); // Send javamailSender.send (MSG); }Copy the code
Code interpretation:
Since the starter module of Spring Boot provides automatic configuration, after introducing the spring-boot-starter-mail dependency, the JavaMailSender instance is created based on the contents of the configuration file. So we can introduce the JavaMailSender mail sending object directly at @AutoWired where we need to use it. That is, you end up sending emails directly through the javaMailSender’s Send () method.
Now that the above method of sending an email has been defined, shall we test whether the email can be sent successfully?
General test method, the suggestion is to open a test class to test, for example, I write a test case on the byte to test. You manually define all the preconditions for sending the message before calling the method
package com.example.demo.component.build; import com.example.demo.component.mail.build.SendMailBuild; import com.example.demo.component.mail.model.*; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.mail.MessagingException; import java.util.ArrayList; import java.util.Date; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class MailTest { @Autowired private SendMailBuild sendMailBuild; / / @test void testSendSimpleMail() {Mail mailModel = new Mail(); Mailmodel.settheme (" Title: This is a test email!" ); / / set the mail subject mailModel. SetSendMailAccount (" [email protected] "); / / set the email sender mailModel. SetAcceptMailAccount (" [email protected] "); Mailmodel.setsendtime (new Date()); SetMailText ("text: this is the body of the test email: I am testMail"); / / set the mail text sendMailBuild sendSimpleMail (mailModel); }}Copy the code
So how do you verify that the email was actually sent?
The project code does not print any error messages
The email just arrived in my mailbox
The content of the email is consistent with the content you send
All of the above is satisfied, that is, the mail sending function is truly successful.
Now, it’s time for the magic. Let’s run TestCase and go!
Die! Wrong report ah! Can’t get up, what to do? Solve it. The ogNL jar package is missing.
Here are the OGNL dependencies:
<dependency> <groupId>ognl</ artifactId> ogNL </artifactId> <version>3.1.12</version> </dependency>Copy the code
The ogNL dependency problem is solved. It’s not a big problem. Let’s continue testing and check whether the email has been sent successfully.
Wechat was first reminded, received the mail. Prove that the email has been sent successfully, happy.
Log in QQ mailbox to check, see if the normal content display. The actual screenshot is as follows:
This is the email we just sent by test. The content is also self-defined, and there is no error on the console, which indicates that there is no problem with the email sending function and the production environment can be launched.
. .
OK, that’s all for this episode. If you have any questions, feel free to comment in the comments section. See you next time.
Three, the past popular recommendation
Springboot series (12) : how to code to send email reminders (preparation)
Springboot series (12) : how to code the implementation of pictures, doc and other attachments to mail (in the middle)
Springboot series (12) : How to code static template mail (part 2)
Springboot series (12) : how to code to achieve the large copy of email – with complete code (summary)
. .
If you want to learn more, you can pay attention to the bug bug column “SpringBoot Zero-based Introduction”, from scratch, from zero to one! Hope I can help you.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
โ๏ธ Be who you want to be, there is no time limit, you can start whenever you want,
๐ You can change from now on, you can also stay the same, this thing, there are no rules to speak of, you can live the most wonderful yourself.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
โ
๐ If this article is helpful to you, please leave a like! (# ^. ^ #);
๐ if you like the article shared by bug fungus, please give bug fungus a point of concern! (เน ‘แด โต เน);
๐ if you have any questions about the article, please also leave a message at the end of the article or add a group [QQ communication group :708072830];
๐ In view of the limited personal experience, all views and technical research points, if you have any objection, please directly reply to participate in the discussion (do not post offensive comments, thank you);
๐ copyright notice: original is not easy, reprint please attach the original source link and this article statement, all rights reserved, piracy will investigate!! thank you