Spring boot integrated mail function (minimum version)

The registration and login function will be encountered in the project. After registration, an email containing registration and activation information will be sent to the user.
Take Sina mailbox as an example.

step

1. Open the service in the mailbox

After entering the mailbox, open the smtp service in the settings, and remember the authorization code, which will be used later.

2. Add dependencies to the pom file

<!--        邮件服务-->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-mail -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
            <version>2.2.6.RELEASE</version>
        </dependency>

3. Write properties file

#MailProperties
#一般邮件服务端口号是465,username为邮件账户名,password为邮箱的授权码,不是开始的密码,否则会报错
spring.mail.host=smtp.sina.com
spring.mail.port=465
[email protected]
spring.mail.password=123
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true

4. Tools for writing emails

@Component
public class MailClient {

    private static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;
    public void sendMail(String to, String subject, String content){

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(helper.getMimeMessage());
        } catch (MessagingException e) {
            logger.error("发送邮件失败" + e.getMessage());
        }
    }

}

5. Write tests


@SpringBootTest
@ContextConfiguration(classes =写你自己的项目启动类.class)
public class MailTest {

    @Autowired
    private MailClient mailClient;

//这里用了thymeleaf的模板
    @Autowired
    private TemplateEngine templateEngine;

    @Test
    public void testHtmlMail(){
        Context context = new Context();
        context.setVariable("username","Jackson");

        String content = templateEngine.process("mail/mailDemo.html", context);
        mailClient.sendMail("目标邮件地址","主题", content);
    }
}

6. Write and send content

Since the method of sending html is adopted above, you also need to write your HTML template file, including registration information or information you want users to know, this free play =w=
For example, mine is written under the mail in the templates directory in the mailDemo file. The rest will not be repeated.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324137037&siteId=291194637