一、简单实现

1.引入依赖

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

2. application.yml配置

spring:
  mail:
    host: smtp.163.com
    username: xxx@163.com
    password: xxxxxx			#有的是授权码,有的是密码
    protocol: smtp

默认端口25

3.EmailUtil工具类,自己写

@Component
public class EmailUtil {
    @Resource
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String from;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public void send(String to, String subject, String text) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, true);
        } catch (MessagingException e) {
            logger.error(e.getMessage());
        }
        mailSender.send(message);
        logger.info("发送成功");
    }
}

4.测试

@SpringBootTest
class ServerApplicationTests {
    @Resource
    private EmailUtil emailUtil;

    @Test
    void contextLoads() {
        emailUtil.send("xxx@qq.com","模板邮件","xxx");
    }

}

二、踩过的坑

本地电脑是windows环境,通过简单实现就能发送邮件了。

问题:服务器是阿里云linux的,这种情况下会出错误提示,连接超时。

Couldn't connect to host, port: xxx.xxx.xxx.xxx, 25; timeout -1;

网上说,linux无法自动解析域名,需要先将邮件服务器地址host解析成ip

解析之后还是会报错。

根据网上说法是,阿里云25号端口没开,开了之后发现还是不行。

使用命令发现,邮件服务器端的25端口连接不上

telnet xxx.xxx.xxx.xxx 25

使用命令发现,邮件服务器端的465端口能连接上

telnet xxx.xxx.xxx.xxx 465

然后把port改成465,出现以下错误

Could not connect to SMTP host: 202.101.149.132, port: 465, response: -1

465端口是ssl协议,需要进行配置

application.yml配置修改为:

spring:
  mail:
    host: xxx.xxx.xxx.xxx
    username: xxx
    password: xxx
    protocol: smtp
    port: 465
    default-encoding: UTF-8
    properties:
      mail.smtp.auth: true
      mail:
        smtp:
          ssl:
            enable: true
      mail.smtp.socketFactory.port: 465
      mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
      mail.smtp.socketFactory.fallback: false

修改完成后,报错

 PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

问题原因是因为信任证书,百度了很久没有找到合适的方法,后来试着把邮件服务器地址加入信任,就可以了。

最终配置如下:

spring:
  mail:
    host: xxx.xxx.xxx.xxx
    username: xxx
    password: xxx
    protocol: smtp
    port: 465
    default-encoding: UTF-8
    properties:
      mail.smtp.auth: true
      mail:
        smtp:
          ssl:
            enable: true
            trust: xxx.xxx.xxx.xxx
      mail.smtp.socketFactory.port: 465
      mail.smtp.socketFactory.class: javax.net.ssl.SSLSocketFactory
      mail.smtp.socketFactory.fallback: false

 

Logo

更多推荐