pom.xml引入spring-boot-starter-mail

Spring Boot2.x集成了mail模块,在dependencies引入这个

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

application.yml配置

spring:
	mail:
    	# 163
    	host: smtp.163.com
    	port:
    	username: yimcarson@163.com
    	password: ************
    	protocol: smtp
    	default-encoding: UTF-8
    	properties:
      		mail.smtp.auth: true
      		mail.smtp.starttls.enable: true
      		mail.smtp.starttls.required: true
      		mail.smtp.socketFactory.port: 465
      		mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
      		mail.smtp.socketFactory.fallback: false

其中spring.mail.host spring.mail.port spring.mail.username spring.mail.password不同邮箱的配置方法也不同

163邮箱

spring:
	mail:
    		host: smtp.163.com
    		port:
    		username: yimcarson@163.com
    		password: ************

其中spring.mail.port不指定;spring.mail.password不是邮箱密码,需要登录mail.163.com,前往设置 客户端授权密码中获取的一个16个字符的密码,同时允许POP3/SMTP服务。

163邮箱设置1

163邮箱设置2

QQ邮箱

spring:
	mail:
    		host: smtp.qq.com
    		port: 587
    		username: yimcarson@qq.com
    		password: ************

spring.mail.password不是QQ密码,登录mail.qq.com,前往设置 账户 POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务开启POP3/SMTP服务获取一个16个字符的密码

mail.163.com设置

Gmail邮箱

spring:
	mail: 
		host: smtp.gmail.com
		port: 465
		username: yimcarson@gmail.com
		password: ****************

spring.mail.password是Gmail的密码,但是要前往Google账户的安全性较低的应用的访问权限中允许不安全应用。

Google账户设置

发送邮件

这是一个验证码模版邮件

service实现类

import com.my.demo.project.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.UUID;

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    /**
     * 用来发送模版邮件
     */
    @Autowired
    private TemplateEngine templateEngine;

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

    @Override
    public void send(String to, String subject, String text) {

//        SimpleMailMessage message = new SimpleMailMessage();
//        message.setFrom(from);
//        message.setTo(to);
//        message.setSubject(subject);
//        message.setText(text);

        Context context = new Context();
        context.setVariable("project", "demo");
        context.setVariable("author", "yimcarson");
        context.setVariable("code", text);
        String emailContent = templateEngine.process("mail", context);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(emailContent, true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        mailSender.send(message);
    }
}

templates模版

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
	    <meta charset="UTF-8">
	    <title>yimcarson</title>
	    <style>
	        body {
	            text-align: center;
	            margin-left: auto;
	            margin-right: auto;
	        }
	        #main {
	            text-align: center;
	            position: absolute;
	        }
	    </style>
	</head>
	<body>
		<div id="main">
	    	<h3>Welcome <span th:text="${project}"></span> -By <span th:text=" ${author}"></span></h3>
	    	Your Verification Code is
	    	<h2><span th:text="${code}"></span></h2>
		</div>
	</body>
</html>

测试

import com.my.demo.Application;
import org.junit.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 org.thymeleaf.TemplateEngine;

import java.util.Date;
import java.util.UUID;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class MailServiceTest {
    @Autowired
    private MailService mailService;

    @Test
    public void testSend() {
    	String to = "yimcarson@qq.com";
		mailService.send(to, "模板邮件", UUID.randomUUID().toString().toUpperCase());
    }
}

接收到的模版邮件

结语

163 QQ这两个邮箱比较常用,至于Gmail……,如果服务器是阿里云香港或者国外、亚马逊这些的话可以正常使用,否则……,Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1

Couldn't connect to host, port: smtp.gmail.com, 465; timeout -1

GitHub 加速计划 / sp / spring-boot
40
10
下载
spring-projects/spring-boot: 是一个用于简化Spring应用开发的框架。适合用于需要快速开发企业级Java应用的项目。特点是可以提供自动配置、独立运行和内置的Tomcat服务器,简化Spring应用的构建和部署。
最近提交(Master分支:4 个月前 )
c9246cec The built-in decompression support in HttpClient 5.6 breaks Elasticsearch's Rest5Client as it results in double decompression. The first decompression is performed by the Apache HTTP client. It succeeds. The Elasticsearch Rest5Client then sees the Content-Encoding: gzip header and makes a second attempt to inflate the data. This fails as it has already been inflated. Closes gh-48743 1 天前
d914467f - 1 天前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐