Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

There is often a need for email notification reminders after mq has been invoked or after an event has completed. Springboot also provides start, and you just need to call the method as required. However, most things on the network how to call the extranet mailbox blog, this article will be implemented separately how to call extranet mail.

1. Business code

1. The pom file

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> < version > 2.3.7. RELEASE < / version > < / dependency >Copy the code

2. The entity class

Stores the sending information of the interface.

Public class MailVO {/** * email Id */ @apiModelProperty (value = "email Id", name =" email Id") private String Id; /** * @apimodelproperty (value = "emailSender ", name =" emailSender ") private String emailSender; /** * @apiModelProperty (value = "email recipient ", name =" email recipient ") private String emailReciever; / / @apiModelProperty (value = "email ", name =" email ") private String emailSubject; / @apiModelProperty (value = "email ", name =" email ") private String emailText; / @apiModelProperty (value = "", name =" ") private Long sentDate; / @apiModelProperty (value = "", name =" ") private Long sentDate; */ @apiModelProperty (value = "CCC "," CCC "," value =" CCC ", Name = "name ") private String carbonCopy; /** * ApiModelProperty(value = "ApiModelProperty ", value =" ApiModelProperty ", value = "ApiModelProperty ", Name = "blindCarbonCopy ") private String blindCarbonCopy; /** * status */ @apiModelProperty (value = "status ", name =" status ") private String status; / @apiModelProperty (value = "error ", name =" error ") private String error; / @jsonignore @APIModelProperty (value = "email ", name =" email ") private MultipartFile[]; }Copy the code

3.controller

@RestController @RequestMapping("/mail") public class MailController { @Autowired private MailService mailService; /** * * * @param mailVO * @return mailVO */ @postMapping ("/send") @apiOperation (value = "Send email ") public mailVO SendMail (@requestBody MailVO MailVO) {return mailService.sendMail(MailVO); }}Copy the code

3.service

Public interface MailService {/** ** sendMail ** @param mailVO * @return mailVO */ mailVO sendMail(mailVO mailVO); ** @mailvo * @return */ void checkMail(mailVo mailVo); ** @param mailVo * @return */ void sendMimeMail(mailVo mailVo); ** @param mailVo * @return mailVo */ mailVo saveMail(mailVo mailVo); }Copy the code

5.serviceImpl

The logical function of sending emails.

@Service("mailService") public class MailServiceImpl implements MailService { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private JavaMailSenderImpl mailSender; @Override public MailVO sendMail(MailVO mailVO) { try { //1. CheckMail checkMail(mailVO); //2. SendMimeMail (mailVO); //3. Save the mail return saveMail(mailVO); } catch (Exception e) {// Print error message logger.error(" failed to send mail :", e); mailVO.setStatus("fail"); mailVO.setError(e.getMessage()); return mailVO; } } @Override public void checkMail(MailVO mailVo) { if (StringUtils.isEmpty(mailVo.getEmailReciever())) { throw new RuntimeException(" Mail recipient cannot be empty "); } if (stringutils.isempty (mailvo.getemailSubject ())) {throw new RuntimeException(" Mail subject cannot be empty "); } if (stringutils.isempty (mailvo.getemailText ())) {throw new RuntimeException(" Mail content cannot be empty "); }} @override public void sendMimeMail(MailVO MailVO) {try {//true: supports complex types MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true); // The mail sender reads mailvo.setemailSender (mailvo.getemailSender ()) from the configuration item; // MessageHelper.setFrom (mailvo.getemailSender ()); // MessageHelper.setto (mailvo.getemailreciever ().split(",")); // MessageHelper.setSubject (mailvo.getemailSubject ()); Messagehelper.settext (mailvo.getemailtext ()); // copy if (! StringUtils.isEmpty(mailVo.getCarbonCopy())) { messageHelper.setCc(mailVo.getCarbonCopy().split(",")); } // encrypt if (! StringUtils.isEmpty(mailVo.getBlindCarbonCopy())) { messageHelper.setCc(mailVo.getBlindCarbonCopy().split(",")); } // Add mail attachment if (mailvo.getMultipartFiles ()! = null) { for (MultipartFile multipartFile : mailVo.getMultipartFiles()) { messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile); } // Send time if (! StringUtils.isEmpty(mailVo.getSentDate().toString())) { messageHelper.setSentDate(new Date()); } / / formal email mailSender. Send (messageHelper. GetMimeMessage ()); mailVo.setStatus("ok"); Logger. info(" Message sent successfully: {}->{}", mailvo.getemailSender (), mailvo.getemailReciever ()); } catch (Exception e) {throw new RuntimeException(e); } } @Override public MailVO saveMail(MailVO mailVo) { return mailVo; }}Copy the code

2. Configuration file

The code above is much the same in other posts. The key is configuration files.

1. Use the Internet (QQ mailbox)

Modify the application. The XML.

Spring: mail: host: smtp.qq.com #SMTP server address username: [email protected] # login account password: 1 # authentication code is not password default-encoding: Utf-8 # UTF-8 properties: mail: SMTP: SSL: enable: true # SMTP: SSL: enable: true Max-request-size: 50MB # limit the total number of requestsCopy the code

Note: Do not fill in the password, but the authorization code.

1. Obtain the authorization code

Visit qq mailbox, visit the help center in the upper left corner.

The return is the authorization code, copy to the above.

2. Intranet mailbox

Spring: mail: host: mail.xxx.com #SMTP server address port: 25 # Intranet need to specify the port need to specify username: [email protected] # login account password: XXXX # login password default-encoding: utF-8 properties: mail: SMTP: SSL: enable: false # configure servlet: multipart: Max-file-size: 10MB # limit the size of a single file max-request-size: 50MB # limit the total number of requestsCopy the code

Then you can send the email.

Note: this is the login password of the mailbox, not the authorization code! At the same time, confirm the type and port number of the open mailbox with the email creator. If not, it will be a failure.

3. The interface calls the input parameter

{"emailSender":"[email protected]", "emailReciever":"[email protected]", "emailSubject":" Test email ", "emailText":" morning of 7th June, The first Chinese test will be completed in 2021. The Paper has learned from the National Education Examinations Authority (NEEA) that there are 8 sets of Chinese test papers for this year's national college entrance examination (GAOKAO). The NEEA has ordered 4 sets of Chinese test papers for Beijing, Tianjin, Shanghai and Zhejiang. , "sentDate": 20210607 }Copy the code

After the interface is successfully invoked, you can access the mail to check whether the mail is successfully sent.