Be serious about writing, not clickbait.

The article is available at Github.com/niumoo/Java… And program ape Alang’s blog, point attention, don’t get lost.

In our era, email service is very important for communication at work, as well as various email notifications at ordinary times. Java has long supported mail services through Java Mail. Spring further encapsulates JavaMail, abstracting JavaMailSender. Later, with the advent of Springboot, spring-boot-starter-mail naturally emerged. Anyway, each encapsulation makes it easier to use.

Springboot mail rely on

Creating a Springboot project aside, let’s take a look at the overall directory structure.

Directly introduce the dependencies required by the Springboot mail service.

   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <! -- Mail service -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
        <! -- Thymeleaf template for sending template emails -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
Copy the code

Springboot mail configuration

To use the email service, you need to configure email information, such as SMTP, email account (for example, email 126), email password, and email encoding format.

spring.mail.host=smtp.126.com
spring.mail.port=25
# Your email address
spring.mail.username=[email protected] 
# Your authorization code (126 and 163 as well as QQ mailbox require authorization code login, without authorization code directly login webpage version of the mailbox Settings set)
spring.mail.password=password
spring.mail.default-encoding=UTF-8
Copy the code

Springboot Mail Text mail

Text mail is the simplest and most basic type of mail, and can be sent directly using the Spring-wrapped JavaMailSender.

Create the MailService class, inject JavaMailSender to send the mail, and bind the parameters in the @value (“${spring.mail.username}”) configuration file to set the mailbox from which the mail is sent. Use the @Service annotation to inject MailService into the Spring container, and use Lombok’s @slf4J to import logging.

/** * <p> * Mail service **@Author niujinpeng
 * @Date 2019/3/10 21:45
 */
@Service
@Slf4j
public class MailService {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    /** * Send a simple text message **@param to
     * @param subject
     * @param content
     */
    public void sendSimpleTextMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);
        message.setFrom(from);
        mailSender.send(message);
        log.info("[Text mail] sent successfully! to={}", to); }}Copy the code

A unit test class for Springboot was created to test text mail, and recipients in the experiment were set to their own mailboxes for convenience.

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Autowired
    private MailService mailService;
    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void sendSimpleTextMailTest(a) {
        String to = "[email protected]";
        String subject = "Springboot sends simple text mail";
        String content = "

First Springboot simple text message

"
; mailService.sendSimpleTextMail(to, subject, content); }}Copy the code

Run unit tests to test the sending of text messages.

PS: if you’re running report abnormal AuthenticationFailedException: 535 Error. It’s usually the wrong username and password.

Caused by: javax.mail.AuthenticationFailedException: 535 Error: authentication failed

	at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:965)
	at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:876)
	at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:780)
	at javax.mail.Service.connect(Service.java:366)
	at org.springframework.mail.javamail.JavaMailSenderImpl.connectTransport(JavaMailSenderImpl.java:517)
	at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:436)
	... 34 more
Copy the code

Logs that are successfully sent are generated during normal operation.

The 2019-03-11 23:35:14. 13608-743 the INFO [main] n.c odingme. Boot. Service. MailServiceTest: Started MailServiceTest in 3.964 seconds (JVM running for 5.749) 2019-03-11 23:35:24.718 INFO 13608 -- [main] Net. Codingme. Boot. Service. MailService: 【 text messages sent successfully! [email protected]Copy the code

Check your mailbox for incoming messages.The text mail is received normally, and the HTML tags in the visible text mail are not parsed.

Springboot Mail HTML mail

Add a new method, sendHtmlMail, to the MailService class above to test HTML mail.

    /** * send HTML message **@param to
     * @param subject
     * @param content
     * @throws MessagingException
     */
    public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        messageHelper.setFrom(from);
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        // true for HTML mail
        messageHelper.setText(content, true);
        mailSender.send(message);
        log.info("[HTML email] sent successfully! to={}", to);
    }
Copy the code

Add HTML mail test methods to test methods.

    @Test
    public void sendHtmlMailTest(a) throws MessagingException {
        String to = "[email protected]";
        String subject = "Springboot sends HTML mail";
        String content = "

Hi~

First Springboot HTML email

"
; mailService.sendHtmlMail(to, subject, content); } Copy the code

Run the unit tests to see how they are received.The HTML message is received normally, and the HTML tag is parsed to the appropriate style.

Springboot Mail Attachment mail

Add a new method sendAttachmentMail to the MailService class above to test attachment mail.

    /** * Send message with attachment **@param to
     * @param subject
     * @param content
     * @param fileArr
     */
    public void sendAttachmentMail(String to, String subject, String content, String... fileArr)
        throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setFrom(from);
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(content, true);

        // Add attachments
        for (String filePath : fileArr) {
            FileSystemResource fileResource = new FileSystemResource(new File(filePath));
            if (fileResource.exists()) {
                String filename = fileResource.getFilename();
                messageHelper.addAttachment(filename, fileResource);
            }
        }
        mailSender.send(mimeMessage);
        log.info("[Attached email] successfully sent! to={}", to);
    }
Copy the code

Add attachment mail test methods to test methods.

    @Test
    public void sendAttachmentTest(a) throws MessagingException {
        String to = "[email protected]";
        String subject = "Springboot sends HTML attachment mail";
        String content = "

Hi~

First Springboot HTML attachment email

"
; String filePath = "pom.xml"; mailService.sendAttachmentMail(to, subject, content, filePath, filePath); } Copy the code

Run the unit tests to see how they are received.

The mail with attachments is received normally, and multiple attachments are implemented in the same way.

Springboot Mail Picture mail

Picture mail is slightly different from other mail. Picture mail needs to define the position of the picture in the content and give a record ID, and then add the picture to the ID position of the message.

Add a new method sendImgMail to the MailService class above to test attached mail.

   /** * Send a message with a picture **@param to
     * @param subject
     * @param content
     * @param imgMap
     */
    public void sendImgMail(String to, String subject, String content, Map<String, String> imgMap)
        throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
        messageHelper.setFrom(from);
        messageHelper.setTo(to);
        messageHelper.setSubject(subject);
        messageHelper.setText(content, true);
        // Add images
        for (Map.Entry<String, String> entry : imgMap.entrySet()) {
            FileSystemResource fileResource = new FileSystemResource(new File(entry.getValue()));
            if (fileResource.exists()) {
                String filename = fileResource.getFilename();
                messageHelper.addInline(entry.getKey(), fileResource);
            }
        }
        mailSender.send(mimeMessage);
        log.info("[Picture email] sent successfully! to={}", to);
    }
Copy the code

Add an image mail test method to the test method that uses apple.png, an image from the project. See the project structure above.

    @Test
    public void sendImgTest(a) throws MessagingException {
        String to = "[email protected]";
        String subject = "Springboot sends HTML image mail";
        String content =
            "< h2 > Hi ~ < / h2 > < p > the first an email pictures Springboot HTML < / p > < br / > < img SRC = \ \" cid: img01 \ "/ > < img SRC = \" cid: img02 \ "/ >";
        String imgPath = "apple.png";
        Map<String, String> imgMap = new HashMap<>();
        imgMap.put("img01", imgPath);
        imgMap.put("img02", imgPath);
        mailService.sendImgMail(to, subject, content, imgMap);
    }
Copy the code

Run the unit tests to see how they are received.The two pictures are normally displayed in the email.

Springboot Mail template mail

Template emails can be used in a wide range of ways, such as registration success emails or operation notification emails. Template emails often only need to change a few variables. The template mail in Springboot requires the selection of a template engine first, and Thymeleaf has been added to the template engine when introducing dependencies.

Template mail first requires a mail template. Under Templates, create a new HTML file registerSuccess.html. Username is user-defined for us.

<! DOCTYPEhtml>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Notification of Registration Success</title>
</head>
<body>
<p>[${username}]]</p>
<p>A new public key has been added to your account:<br/>Title: HP - WIN10<br/>If the public key is not available, you can add it again here: SSH Keys</p>
</body>
</html>
Copy the code

Inject the template engine into the MailService, MailService, and write the mail template sending code.

    @Autowired
    private TemplateEngine templateEngine;

    /** * Send template email **@param to
     * @param subject
     * @param paramMap
     * @param template
     * @throws MessagingException
     */
    public void sendTemplateMail(String to, String subject, Map<String, Object> paramMap, String template)
        throws MessagingException {
        Context context = new Context();
        // Set the value of the variable
        context.setVariables(paramMap);
        String emailContent = templateEngine.process(template, context);
        sendHtmlMail(to, subject, emailContent);
        log.info("[Template email] sent successfully! ParamsMap = {}, the template = {}", paramMap, template);
    }
Copy the code

Add template mail test methods to unit unit tests, and then send mail tests.

    @Test
    public void sendTemplateMailTest(a) throws MessagingException {
        String to = "[email protected]";
        String subject = "Springboot sends template emails";
        Map<String, Object> paramMap = new HashMap();
        paramMap.put("username"."Darcy");
        mailService.sendTemplateMail(to, subject, paramMap, "RegisterSuccess");
    }
Copy the code

Check the receipt status.

You can see that the template email has been sent normally.

Springboot mail add

The example above, is the basic usage Springboot mail service, the code also has a lot of repetition, and compared to the actual usage and many deficiencies, such as lack of exception handling mechanism, it is sent failures retry mechanism also have no, mail services tend to be real-time in practical situation is not high, say more cases will be used for an asynchronous request.

Github Spring Boot – related integration – mail service has been uploaded.

After < >

Hello world 🙂

I am a lang, lang of the moon, a technical tool person who moves bricks every day. Personal website: www.wdbyte.com If you want to subscribe, you can follow the public account of “Procedural Ape Alang”, or the blog of procedural ape Alang, or add me on wechat (WN8398).

This article has also been compiled at GitHub.com/niumoo/Java… Welcome Star.