Spring Boot 发送邮件

  • pom.xml

<dependency>
     <groupId>org.springframework.bootgroupId>
     <artifactId>spring-boot-starter-mailartifactId>
dependency>


<dependency>
    <groupId>org.quartz-schedulergroupId>
    <artifactId>quartzartifactId>
    <version>2.3.2version>
dependency>
spring: 
  mail:
    default-encoding: UTF-8
    host: smtp.exmail.qq.com #发送邮件服务器
    username: 发件人@qq.com  #发送邮件的邮箱地址
    password: 授权码	#客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的
    properties.mail.smtp.port: 465 #端口号465或587
    type: 1   # 0 普通文本,1 Html文本
    subject: 发送主题
    cron: 0 0 9 * * ?	# 定时发送 cron 表达式
    properties:
      mail.smtp.ssl.enable: true
      mail.smtp.ssl.socketFactory.class: com.superbeyone.config.MailSSLSocketFactory
  • MailSSLSocketFactory
package com.superbeyone.config;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author Mr.superbeyone
 */
public class MailSSLSocketFactory extends SSLSocketFactory {

    private SSLSocketFactory factory;

    public MailSSLSocketFactory() {
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[]{new MailTrustManager()}, null);
            factory = sslcontext.getSocketFactory();
        } catch (Exception ex) {
            // ignore
        }
    }

    public static SocketFactory getDefault() {
        return new MailSSLSocketFactory();
    }

    @Override
    public Socket createSocket() throws IOException {
        return factory.createSocket();
    }

    @Override
    public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException {
        return factory.createSocket(socket, s, i, flag);
    }

    @Override
    public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr1, int j) throws IOException {
        return factory.createSocket(inaddr, i, inaddr1, j);
    }

    @Override
    public Socket createSocket(InetAddress inaddr, int i) throws IOException {
        return factory.createSocket(inaddr, i);
    }

    @Override
    public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException {
        return factory.createSocket(s, i, inaddr, j);
    }

    @Override
    public Socket createSocket(String s, int i) throws IOException {
        return factory.createSocket(s, i);
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return factory.getDefaultCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return factory.getSupportedCipherSuites();
    }
}
  • MailTrustManager
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author superbeyone 
 */
public class MailTrustManager implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        
    }


    @Override
    public void checkServerTrusted(X509Certificate[] cert, String authType) {
        // everything is trusted
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

}

public interface MailService {
/**
     * 发送简单的文本邮件
     *
     * @param subject 主题
     * @param content 证明
     * @param to      目标
     */
    void sendSimpleMail(String subject, String content, String... to);

    /**
     * 发送HTMl的文本邮件
     *
     * @param subject 主题
     * @param content 证明
     * @param to      目标
     */
    void sendHtmlMail(String subject, String content, String... to);
    
}
@Service
public class MailServiceImpl implements MailService {

    @Resource
    JavaMailSender mailSender;

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

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


/**
     * 发送简单的文本邮件
     *
     * @param subject 主题
     * @param content 证明
     * @param to      目标
     * @throws MailException 异常
     */
    @Override
    public void sendSimpleMail(String subject, String content, String... to) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            mailSender.send(message);
            logger.debug("邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("邮件发送失败");
        }
    }

    /**
     * 发送HTMl的文本邮件
     *
     * @param subject 主题
     * @param content 证明
     * @param to      目标
     * @throws Exception 异常
     */
    @Override
    public void sendHtmlMail(String subject, String content, String... to) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
            messageHelper.setFrom(from);
            messageHelper.setTo(to);
            messageHelper.setSubject(subject);
            messageHelper.setText(content, true);
            mailSender.send(message);
            logger.debug("邮件发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("邮件发送失败");
        }
    }
}

Mr.superbeyone


你可能感兴趣的:(工具类,Spring,Boot)