Spring boot封装gmail邮箱服务器发送邮件

由于gmail邮箱发送邮对安全性校验比较高,因此,首先设置

https://myaccount.google.com/lesssecureapps?pli=1,需要开启“允许不够安全的应用”

接下来就可以开始代码编写了。

pom.xml文件中引入架包:


   org.springframework.boot
   spring-boot-starter-mail
   2.1.5.RELEASE

封装实现

class EmailClient {
/*
 * 通过gmail邮箱发送邮件
 */
public static void gmailSender(String email) {

    // Get a Properties object
    Properties props = new Properties();
    //选择ssl方式
    gmailssl(props);

    final String sendEmail = "####@gmail.com";//gmail邮箱
    final String password = "******";//密码
    Session session = Session.getDefaultInstance(props,
            new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(sendEmail, password);
                }
            });
    // -- Create a new message --
    Message msg = new MimeMessage(session);

    // -- Set the FROM and TO fields --
    try {
        msg.setFrom(new InternetAddress(sendEmail));
        msg.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(email));
        msg.setSubject("kkkk");
        msg.setText("这是一封测试邮件");
        msg.setSentDate(new Date());
        Transport.send(msg);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("Message sent.");
}
private static void gmailssl(Properties props) {
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    props.put("mail.debug", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.ssl.enable", "true");
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.port", "465");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
}

}

编写测试类

你可能感兴趣的:(java开发)