Basic protocol and mail configuration integration
Noun concept interpretation
- What are POP3, SMTP, and IMAP?
Simply put: POP3 and IMAP are used to download mail from the server. SMTP is used to find the next destination when sending or forwarding a message. So we should use SMTP protocol to send mail.
- What is the free email client authorization code function?
The mailbox client authorization code is a unique security function designed to prevent the thief from logging in to the mailbox through the client after your mailbox password is stolen. It can be understood that the client authorization code is the secondary password sent by mail.
Integrated mail sending function
Introduce dependency
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency>
Mailbox configuration
QQ mailbox configuration
Official Configuration Description: Refer to the official help center
Obtain client authorization code: Refer to the official help center
The detailed configuration is as follows:
spring: mail: host: smtp.qq.com #outgoing mail server username: xx@qq.com #QQ email password: xxxxxxxxxxx #Client authorization code protocol: smtp #Send mail protocol properties.mail.smtp.auth: true properties.mail.smtp.port: 465 #Port number 465 or 587 properties.mail.display.sendmail: Javen #Can be arbitrary properties.mail.display.sendname: Spring Boot Guide Email #Can be arbitrary properties.mail.smtp.starttls.enable: true properties.mail.smtp.starttls.required: true properties.mail.smtp.ssl.enable: true default-encoding: utf-8
Note: when opening SSL, you cannot connect to the QQ mail server when using port 587
Netease (126 / 163 / year) mailbox configuration
Netease mailbox client code granting: Refer to the official help center
Client port configuration description: Refer to the official help center
The detailed configuration is as follows:
spring: mail: host: smtp.126.com username: xx@126.com password: xxxxxxxx protocol: smtp properties.mail.smtp.auth: true properties.mail.smtp.port: 994 #465 or 994 properties.mail.display.sendmail: Javen properties.mail.display.sendname: Spring Boot Guide Email properties.mail.smtp.starttls.enable: true properties.mail.smtp.starttls.required: true properties.mail.smtp.ssl.enable: true default-encoding: utf-8 from: xx@126.com
Special note:
- 126 mailbox SMTP server address: smtp.126.com, port number: 465 or 994
- 163 mailbox SMTP server address: smtp.163.com, port number: 465 or 994
- Year mailbox SMTP server address: smtp.year.net, port number: 465 or 994
Some mail servers accept sending mail using the client authorization code, and some mail servers accept sending mail using the mailbox password, so the password configuration cannot be generalized. If the client authorization code does not work, try the email password; If the mailbox password doesn't work, try the client authorization code.
Send simple mail
The simple mail here refers to the mail whose content is only ordinary text.
@Service public class MailService { @Resource private JavaMailSender mailSender; @Value("${spring.mail.username}") private String fromEmail; /** * Send text mail */ public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(fromEmail); message.setTo(to); message.setSubject(subject); message.setText(content); mailSender.send(message); } }
The three parameters of sendSimpleMail are: the sending destination, the title and the content of the message.
Test code:
//Defined with the specified port of the configuration file_ Port runs the test case as the boot port @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class MailServiceTest { @Resource MailService mailService; @Test public void sendSimpleMail() { mailService.sendSimpleMail("431899405@qq.com", "Plain text mail", "Plain text mail content test"); } }
test result
Appendix: QQ email settings
1. Start SMTP service
2. After configuring and enabling SMTP, a client authorization code will be returned to us. This authorization code is the password used to send e-mail above, so write it down.
Send html and template based mail
Send html mail service
The first parameter of the sendHtmlMail function is the sending target mailbox, the second parameter is the message title, and the third parameter is the message body (html).
- In the previous section, simple mailmessage is used to send ordinary text file mail
- The text sent in the following code is HTML mail, and MimeMessage is used
/** * Send html mail */ public void sendHtmlMail(String to, String subject, String content) throws MessagingException { //Note that MimeMessage is used here MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(fromEmail); helper.setTo(to); helper.setSubject(subject); //The second parameter is html. true indicates that the body of the sent message is html text helper.setText(content, true); mailSender.send(message); }
In the test case, you can see that this method is used to send HTML mail. We write HTML in Java code in the form of string splicing, which is very unfriendly to developers. Later, we will introduce the method of sending HTML mail using java template engine, which makes HTML writing more friendly.
@Test public void sendHtmlMail() throws MessagingException { mailService.sendHtmlMail("431899405@qq.com","A letter html Test mail","<body style=\"text-align: center;margin-left: auto;margin-right: auto;\">\n" + " <div id=\"welcome\" style=\"text-align: center;position: absolute;\" >\n" +" <h3>\"A letter html Test mail\"</h3>\n" +" <span>http://www.zimug.com</span>" + " <div style=\"text-align: center; padding: 10px\"><a style=\"text-decoration: none;\" href=\"https://zimug.com\" target=\"_bank\" >" + " <strong>I'm very attentive. I hope you can gain something</strong></a></div>\n" + " </div>\n" + "</body>"); }
Screenshot of mail sending success
Email based on freemaker template
The premise of using the following method to send e-mail is that your project has correctly integrated freemaker template engine
Freemaker based template mail is essentially sending html mail, but there is a process of converting the template into html string.
@Autowired private FreeMarkerConfigurer freeMarkerConfigurer; @Test public void sendTemplateMail() throws IOException, TemplateException, MessagingException { //Add dynamic data and replace the placeholder in the template List<ArticleVO> articles = new ArrayList<>(); articles.add(new ArticleVO(1L,"dhy","spring boot1","Content I",new Date(),null)); articles.add(new ArticleVO(2L,"xpy","spring boot2","Content II",new Date(),null)); Template template = freeMarkerConfigurer.getConfiguration().getTemplate("freemarker-temp.html"); //After the template file and data are rendered, it is converted to html string Map<String,Object> model = new HashMap<>(); model.put("articles",articles); String templateHtml = FreeMarkerTemplateUtils.processTemplateIntoString(template,model); //Send mail mailService.sendHtmlMail("123456@qq.com","A letter freemarker Templated html Test mail",templateHtml); }
The template file freemaker-temp.html, written in freemaker syntax, can realize dynamic assignment.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title>freemarker Simple example</title> </head> <body> <h1>Hello Freemarker</h1> <table class=""> <tr> <td>author</td> <td>Tutorial name</td> <td>content</td> </tr> <#list articles as article> <tr> <td>${article.author}</td> <td>${article.title}</td> <td>${article.content}</td> </tr> </#list> </table> </body> </html>
ArticleVO
@Data @AllArgsConstructor @NoArgsConstructor @Builder public class ArticleVO { private Long id; private String author; private String title; private String content; private Date createTime; private List<Reader> reader; }
thymeleaf can also be implemented. You might as well try it.
Send mail with attachments and inline attachments
Send mail with attachments
/** * Send mail with attachments */ public void sendAttachmentsMail(String to, String subject, String content, String filePath) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); //Second parameter with attachment true MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(fromEmail); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); //Add attachment resource FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); //Send mail mailSender.send(message); }
The first parameter of sendAttachmentsMail is the sending target mailbox, the second parameter is the content of the message, and the third parameter is the attachment of the message.
Run the following test cases to test:
@Test public void sendAttachmentsMailTest() throws MessagingException { String filePath = "D:\\courseview\\springboot\\template.png"; mailService.sendAttachmentsMail("431899405@qq.com", "This is an email with attachments", "There are attachments in the email, please check!", filePath); }
Email result display
Send mail with inline attachments
The so-called inline attachment is that the attachment file is displayed in the mail body, usually a picture resource.
/** * Send messages with static resources in the body */ public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId) throws MessagingException { MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(fromEmail); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); //Add an inline attachment and specify a resource id:rscId FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); }
Parameter description of sendResourceMail method:
[] parameter 1: target mailbox for sending mail
[] parameter 2: file title
[] parameter 3: email body: html (including image resource id: rscId)
[] parameter 4: picture resource file local disk path res
[] parameter 5: resource Id of picture resource file: rscId
Parameter 3: if the HTML text contains < img SRC = CID: rscid >, it will be based on parameter 5: helper.addInline(rscId, res);, Find the resource file res corresponding to parameter 4 and render it to HTML.
The following code is a test case. See the results after execution
@Test public void sendResourceMail() throws MessagingException { String rscId = "dhy"; String content = "<html><body>This is an email with pictures<br/><img src=\'cid:" + rscId + "\' ></body></html>"; String imgPath = "D:\\courseview\\springboot\\template.png"; mailService.sendResourceMail("431899405@qq.com", "This email contains pictures", content, imgPath, rscId); }
Email result display:
Reference articles
Implementation of Java mail sending based on springboot
[SpringBoot summary] 7. SpringBoot integrates JavaMailSender to realize mail sending
Teach you how to verify the mailbox registration code through SpringBoot
Note the connection timeout problem: the corresponding mailbox does not exist