spring boot 发送邮件

一、前期准备

1.包引入

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

2.配置文件

spring.mail.protocol=smtp
spring.mail.host=smtp.163.com
spring.mail.username=zhaobaolintest@163.com
spring.mail.password=abc123456789

这里切记 password是授权密码 授权密码 授权密码  不是你的邮箱登陆密码

二、核心代码

import com.example.demo.dto.vo.MailSendVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

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

/**
 * @Author:zhao-baolin
 * @Description: 邮件发送类
 * @Date:Created in 2018/4/17
 * @Modified By:
 */
@Component
public class MailUtil {

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

    @Value("${spring.mail.password}")
    private String fromPassword;

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

    /**
     * 邮件发送
     */
    public boolean send(MailSendVo sendMailVo) throws Exception
    {
        System.out.println(sendMailVo.toString());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        if(StringUtils.isEmpty(sendMailVo.getToMail()) || StringUtils.isEmpty(sendMailVo.getTitle()) || StringUtils.isEmpty(sendMailVo.getContent())){
            System.out.println("发送邮件参数为空 "+sendMailVo.toString());
            return false;
        }
        // 1. 创建一封邮件
        Properties props = new Properties();
        props.setProperty("mail.smtp.host",host);
        props.setProperty("mail.smtp.auth", "true");

        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");

        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");

        Authenticator auth = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(fromMail, fromPassword);
            }
        };
        Session session = Session.getInstance(props,auth);

        // 2.创建一个Message,它相当于是邮件内容
        Message message = new MimeMessage(session);

        // 设置发送者
        message.setFrom(new InternetAddress(fromMail));

        // 设置收件人 抄送给自己 避免网易554错误
        message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(fromMail));
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(sendMailVo.getToMail()));

        // 邮件主题
        message.setSubject(sendMailVo.getTitle());
        // 邮件正文
        message.setContent(sendMailVo.getContent(), "text/html;charset=utf-8");

        // 设置显示的发件时间
        message.setSentDate(new Date());

        // 保存前面的设置
        message.saveChanges();

        try {
            // 创建 Transport用于将邮件发送
            Transport.send(message);

        }catch (Exception e){
            System.out.println(sendMailVo.getTitle()+"发送邮件失败 "+e.getMessage());
            return false;
        }

        System.out.println("邮件发送结束");
        return true;

    }
    
}

里面有一个MailSendVo对象 这个对象封装了收件人、邮件标题、邮件内容三个属性 详情可以点进源码查看

三、源码分享

Fork me on Gitee

 

多说一句 邮件发送的速度与程序无关,千万不要跑程序里到处找bug,邮件发送只与网络有关。

 

posted @ 2018-10-26 17:30  不该相遇在秋天  阅读(546)  评论(0编辑  收藏  举报