一、项目配置
1. 引入依赖
<!--发送邮件依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2. 开启邮箱的SMTP协议
本文以QQ邮箱为例进行叙述。
3. 配置文件添加相关配置
#编码格式
spring.mail.default-encoding=UTF-8
#配置STMP服务器,此处使用QQ邮箱
spring.mail.host=smtp.qq.com
#发送邮件的用户名及授权码,注意不是登陆密码
spring.mail.username=xxxxxxx@qq.com
spring.mail.password=xxxxxx
#使用的协议
spring.mail.protocol=smtp
二、发送简单文本邮件
MailServiceImpl
代码如下(示例):
@Service
public class MailServiceImpl implements MailService {
private Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
@Autowired
JavaMailSender javaMailSender;
@Override
public void sendSimplMail() {
SimpleMailMessage message = new SimpleMailMessage();
//发件人
message.setFrom("xxxxxx@qq.com");
//收件人
message.setTo("xxxxxxx@qq.com");
//邮件标题
message.setSubject("Come on!");
//邮件内容
message.setText("加油");
javaMailSender.send(message);
logger.info("邮件发送成功");
}
}
三、发送附件邮件
MailServiceImpl
代码如下(示例):
@Service
public class MailServiceImpl implements MailService {
private Logger logger = LoggerFactory.getLogger(MailServiceImpl.class);
@Autowired
JavaMailSender javaMailSender;
@Override
public void sendComplexMail(){
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try{
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
try{
//发件人
mimeMessageHelper.setFrom("xxxxxx@qq.com");
//收件人
mimeMessageHelper.setTo("xxxxxx@qq.com");
//邮件标题
mimeMessageHelper.setSubject("Happy");
mimeMessageHelper.addInline("dog.gif",new File("D:/dog.gif"));
mimeMessageHelper.addAttachment("test.doc",new File("D:/test.doc"));
javaMailSender.send(mimeMessage);
logger.info("复杂邮件发送成功");
} catch (MessagingException e) {
logger.warn("邮件发送失败=====>"+e.getMessage());
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
三、邮件功能工具类
- MailVo 实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.File;
import java.util.Date;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class MailVo {
private String id; //邮件id
private String from; //邮件发送人
private String to; //邮件接收人(多个邮箱则用逗号","隔开)
private String subject; //邮件主题
private String text; //邮件内容
private Date sentDate; //发送时间
private String cc; //抄送(多个邮箱则用逗号","隔开)
private String bcc; //密送(多个邮箱则用逗号","隔开)
private String status; //状态
private String error; //报错信息
private File[] files; //邮件附件
}
- MailUtil 工具类
import com.example.cabledisp.vo.MailVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Date;
@Component
public class MailUtil {
private static Logger logger = LoggerFactory.getLogger(MailUtil.class);//提供日志类
@Autowired
private ApplicationContext applicationContext;
private static JavaMailSender mailSender;
@PostConstruct
public void init(){
MailUtil.mailSender = applicationContext.getBean(JavaMailSender.class);
}
/**
* 邮箱信息检查,可根据实际需求更改
* @param mailVo
* */
public static void checkMail(MailVo mailVo) {
if (StringUtils.isEmpty(mailVo.getTo())) {
throw new RuntimeException("邮件收信人不能为空");
}
if (StringUtils.isEmpty(mailVo.getSubject())) {
throw new RuntimeException("邮件主题不能为空");
}
if (StringUtils.isEmpty(mailVo.getText())) {
throw new RuntimeException("邮件内容不能为空");
}
}
/**
* 构建复杂邮件信息类
* 附件邮件部分可优化
*
* @param mailVo
* */
public static void sendMimeMail(MailVo mailVo) {
try {
MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true); //true表示支持复杂类型
messageHelper.setFrom(mailVo.getFrom()); //邮件发信人
messageHelper.setTo(mailVo.getTo().split(",")); //邮件收信人
messageHelper.setSubject(mailVo.getSubject()); //邮件主题
messageHelper.setText(mailVo.getText()); //邮件内容
if (!StringUtils.isEmpty(mailVo.getCc())) { //抄送
messageHelper.setCc(mailVo.getCc().split(","));
}
if (!StringUtils.isEmpty(mailVo.getBcc())) { //密送
messageHelper.setCc(mailVo.getBcc().split(","));
}
if (mailVo.getFiles() != null) { /添加邮件附件
for (File file : mailVo.getFiles()) {
messageHelper.addAttachment(file.getName(), file);
}
}
if (StringUtils.isEmpty(mailVo.getSentDate())) { //发送时间
mailVo.setSentDate(new Date());
messageHelper.setSentDate(mailVo.getSentDate());
}
System.out.println(messageHelper.getMimeMessage());
mailSender.send(messageHelper.getMimeMessage()); //正式发送邮件
mailVo.setStatus("ok");
logger.info("发送邮件成功:{}->{}", mailVo.getFrom(), mailVo.getTo());
} catch (Exception e) {
throw new RuntimeException(e); //发送失败
}
}
/**
* 保存邮件,未完成
* 可根据需求决定是否启用
* @param mailVo
* */
public MailVo saveMail(MailVo mailVo) {
//将邮件保存到数据库..
return mailVo;
}
}
- 测试
import com.example.cabledisp.vo.MailVo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import java.util.Date;
@SpringBootTest
@RunWith(SpringRunner.class)
public class MailServiceTest {
@Autowired
MailService mailService;
@Test
public void sendComplexMail() {
mailService.sendComplexMail();
}
@Test
public void Send() {
File[] files = new File[1];
MailVo mailVo = new MailVo();
mailVo.setFrom("xxxxx@qq.com");
mailVo.setTo("xxxxx@qq.com");
mailVo.setSentDate(new Date());
mailVo.setSubject("Mail工具类");
mailVo.setText("Mail工具类");
files[0] =new File("D:/test.doc");
mailVo.setFiles(files);
mailService.send(mailVo);
}
}