Spring Boot利用Java Mail实现邮件发送

本文实例为大家分享了Spring Boot利用Java Mail实现邮件发送的具体代码,供大家参考,具体内容如下

实现邮件发送的方法有很多,这里只是简单记录一个demo实现

1. 引入maven依赖


 
  org.springframework
  spring-context-support
  3.2.0.RELEASE
 
  
  javax.mail
  mail

2. 配置邮箱bean信息

我的配置文件名称是application-bean.xml

我是用qq邮箱做的测试,这里需要注意的是password要配置成邮箱授权码,不是邮箱密码

简单说下邮箱授权码的获取方式:

登录网页版QQ邮箱 > 设置 > 账户,需要保证 SMTP 服务开启

Spring Boot利用Java Mail实现邮件发送_第1张图片



 
 
  
  
  
  
  
  
   
    true
    true
    465
    javax.net.ssl.SSLSocketFactory
   
  
 
 
  
 

3. 加载bean配置信息

实现了一个BeanConfig类:

package com.amwalle.walle.bean;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
 
@Configuration
@ImportResource(locations={"classpath:/application-bean.xml"})
public class BeanConfig {
}

4. 邮件发送类

简单实现了一个邮件发送的类,其中包含发送邮件方法 sendMail:

package com.amwalle.walle.util;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
 
import javax.mail.internet.MimeMessage;
 
public class Mail {
 private static final Logger logger = LoggerFactory.getLogger(Mail.class);
 
 private static JavaMailSenderImpl mailSender;
 
 public static void sendMail(String title, String html, String to) {
  try {
   MimeMessage msg = mailSender.createMimeMessage();
   MimeMessageHelper helper = new MimeMessageHelper(msg, true);
   helper.setFrom(mailSender.getUsername());
   helper.setTo(to);
   helper.setSubject(title);
   helper.setText(html, true);
   mailSender.send(msg);
  } catch (Exception e) {
   logger.error("sendMail error", e);
  }
 }
 
 public void setMailSender(JavaMailSenderImpl mailSender) {
  Mail.mailSender = mailSender;
 }
 
 public JavaMailSenderImpl getMailSender() {
  return mailSender;
 }
}

 

5. 测试邮件发送

调用邮件发送,检查是否发送成功:

package com.amwalle.walle.controller;
 
import com.amwalle.walle.util.Mail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@EnableAutoConfiguration
public class HelloWorldController {
 private static final Logger logger = LoggerFactory.getLogger(HelloWorldController.class);
 
 @RequestMapping(value = "/walle", method = RequestMethod.GET)
 public String helloWorld() {
  logger.info("--------test-------");
 
  Mail.sendMail("test","test", "接收邮箱地址");
 
  return "hello world";
 }
}

附我的工程目录,需要修改的就是圈出来的这几个:

Spring Boot利用Java Mail实现邮件发送_第2张图片

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(Spring Boot利用Java Mail实现邮件发送)