登录QQ邮箱打开设置,点击账号
找到服务
按照提示开通POP3/SMTP服务,根据提示完成
新建Springboot项目,这里有个链接供大家参考:https://blog.csdn.net/xwd718/article/details/80640357
接下来开始正式的编码啦,
1、在pom文件中添加依赖
springboot支持邮件服务,只要加入相应的依赖即可,如下:
<!-- email -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
2、在 application.yml中添加参数
#邮箱设置
mail:
host: smtp.qq.com
username: XXX@XXXXX.com
#邮箱授权码
password: XXXXX
default-encoding: UTF-8
form: ${spring.mail.username}
protocol: smtp
port: 25
host:服务器
userName:你的邮箱地址
password:邮箱授权码是刚才开启POP3/SMTP服务时生成的链接字符
form:发送人
protocol:SMTP 可以理解为协议
port:端口号
3、编码
1)controller: 我的项目是前后端分离的,有多个服务,我的参数基本上都封装了
@RestController
@RequestMapping("/a/email")
public class MailController {
@Autowired
private IMailServic mailServic;
@ApiOperation("发送简单邮件")
@PostMapping("/sendSimpleEmail/u")
public Result sendSimpleEmail(@RequestBody MailDto dto) {
ValidatorUtils.validateEntity(dto);
return mailServic.sendSimpleEmail(dto);
}
@ApiOperation("发送复杂邮件,附件是file")
@PostMapping("/complexEmailByFiles/u")
public Result complexEmailByFiles(MailDto dto, MultipartFile[] files) {
ValidatorUtils.validateEntity(dto);
return mailServic.sendComplexEmail(dto, files);
}
@ApiOperation("发送复杂邮件,附件是filepath")
@PostMapping("/complexEmailByFilePath/u")
public Result complexEmailByFilePath(@RequestBody MailDto dto) {
ValidatorUtils.validateEntity(dto);
return mailServic.sendComplexEmail(dto);
}
@ApiOperation("发送HTML邮件")
@PostMapping("/sendHtmlEmail/u")
public Result sendHtmlEmail(@RequestBody MailDto dto) {
ValidatorUtils.validateEntity(dto);
return mailServic.sendComplexEmail(dto, null);
}
@ApiOperation("查询邮件发送记录")
@PostMapping("/getList/u")
public Result getList(@RequestBody MailSearchDto dto) {
return mailServic.searchList(dto);
}
}
dto封装:
@ApiModelProperty(value = "发件人id", required = true)
@NotEmpty(message = "发件人id不能为空")
private String send;
@ApiModelProperty(value = "收件人id,多个用逗号分隔", required = true)
@NotEmpty(message = "收件人id不能为空")
private String receiver;
@ApiModelProperty(value = "收件人邮箱,多个用逗号分隔", required = true)
@NotEmpty(message = "收件人邮箱不能为空")
private String receiverEmail;
@ApiModelProperty(value = "抄送人id,多个用逗号分隔", required = true)
private String ccid;
@ApiModelProperty(value = "抄送人邮箱,多个用逗号分隔", required = true)
private String ccEmail;
@ApiModelProperty(value = "邮件主题")
private String subject;
@ApiModelProperty(value = "邮件内容")
private String content;
2)service:我的代码牵扯业务太多,复制主要的部分
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.form}")
private String from;
public void sendSimpleMail(MailDto dto) {
String[] to = validEmail(dto.getReceiverEmail());
if (to != null && to.length > 0) {
try {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
if (StringUtils.isNotEmpty(dto.getCcEmail())) {
message.setCc(validEmail(dto.getCcEmail()));
}
message.setSubject(dto.getSubject());
message.setText(dto.getContent());
message.setFrom(from);
javaMailSender.send(message);
} catch (Exception e) {
log.error(e.getMessage());
invalidAddress(dto, e);
sendSimpleMail(dto);
//throw new EcmException(MailEnum.ERROR.getMsg() + ":" + e.getMessage());
}
}
}
public void sendHtmlMail(MailDto dto) {
String[] to = validEmail(dto.getReceiverEmail());
if (to != null && to.length > 0) {
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
//true代表支持多组件,如附件,图片等
helper.setFrom(from);
helper.setTo(to);
if (StringUtils.isNotEmpty(dto.getCcEmail())) {
helper.setCc(validEmail(dto.getCcEmail()));
}
helper.setSubject(dto.getSubject());
helper.setText(dto.getContent(), true);
javaMailSender.send(message);
} catch (Exception e) {
log.error(e.getMessage());
throw new EcmException(MailEnum.ERROR.getMsg());
}
}
}
public void sendAttachmentMail(MailDto dto, MultipartFile[] files) {
String[] to = validEmail(dto.getReceiverEmail());
if (to != null && to.length > 0) {
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper;
helper = new MimeMessageHelper(message, true);
//true代表支持多组件,如附件,图片等
helper.setFrom(from);
helper.setTo(to);
String[] cc = validEmail(dto.getCcEmail());
if (cc != null && cc.length > 0) {
helper.setCc(validEmail(dto.getCcEmail()));
}
helper.setSubject(dto.getSubject());
helper.setText(dto.getContent(), true);
if (files != null) {
for (int i = 0; i < files.length; i++) {
helper.addAttachment(files[i].getOriginalFilename(), files[i]);
}
}
javaMailSender.send(message);
} catch (Exception e) {
log.error(e.getMessage());
invalidAddress(dto, e);
sendAttachmentMail(dto, files);
}
}
}
private String[] validEmail(String emails) {
if (StringUtils.isNotBlank(emails)) {
return Arrays.asList(emails.split(","))
.stream()
.filter(itme -> isEmail(itme))
.distinct()
.toArray(String[]::new);
}
return null;
}
private Boolean isEmail(String email) {
String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
return Pattern.compile(regEx1).matcher(email.trim()).matches();
}
private void invalidAddress(MailDto dto, Throwable e) {
String s = getInvalidAddresses(e);
if (StringUtils.isNotBlank(s)) {
List<String> list = Arrays.asList(dto.getReceiverEmail().split(","));
StringBuffer sb = new StringBuffer();
list.stream().forEach(s1 -> {
if (!s.contains(s1)) {
sb.append(s1 + ",");
}
});
dto.setReceiverEmail(sb.toString());
} else {
throw new EcmException(MailEnum.ERROR.getMsg() + ":" + e.getMessage());
}
}
private static String getInvalidAddresses(Throwable e) {
if (e == null) {
return null;
}
if (e instanceof MailSendException) {
for (Exception exception : ((MailSendException) e).getMessageExceptions()) {
if (exception instanceof SendFailedException) {
return getStringAddress(((SendFailedException) exception).getInvalidAddresses());
}
}
}
if (e instanceof SendFailedException) {
return getStringAddress(((SendFailedException) e).getInvalidAddresses());
}
return null;
}
private static String getStringAddress(Address[] address) {
List<String> invalid = new ArrayList<>();
for (Address a : address) {
String aa = ((InternetAddress) a).getAddress();
if (!StringUtils.isEmpty(aa)) {
invalid.add(aa);
}
}
return invalid.stream().distinct().collect(Collectors.joining(","));
}
保存测试,因为我用的是swagger 直接启动项目进行测试就可以了
企业邮箱做邮箱服务器和这个差不太多,欢迎交流
交流邮箱 664616192@qq.com