一、SMTP协议
SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。SMTP协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。使用javamail编写发送程序发送邮件。
以QQ邮箱为例:
需要开启SMTP服务,设置授权码。授权码不是登录密码,授权码是QQ邮箱用于登录第三方客户端/服务的专用密码,适用于登录以下服务:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV 服务。不同邮箱可能不一样。
还需要服务器地址,QQ 邮箱的服务器地址 (host) 是:
收信服务器 (POP3) : pop.qq.com
发信服务器 (SMTP) : smtp.qq.com
二、代码编写
1、配置文件
可以将邮件的账号密码等放入配置文件
#邮件配置,需要修改密码。username:账号,password:密码/授权码,serverUrl:服务器地址,serverPort:服务器端口,sendMail:邮箱
email:
username: 1074004100@qq.com
password:
serverUrl: smtp.qq.com
serverPort: 25
sendMail: 1074004100@qq.com
配置对象:
package com.example.demo.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
* @author zhanglei
* @date : 2023/03/06 14:14
* 邮箱配置
*/
@Component
@Configuration
@Data
public class EmailConfig {
/**
* 邮件账号
*/
@Value("${email.username}")
private String username;
/**
* 邮件密码/授权码
*/
@Value("${email.password}")
private String password;
/**
* 服务器地址
*/
@Value("${email.serverUrl}")
private String serverUrl;
/**
* 服务器端口
*/
@Value("${email.serverPort}")
private Integer serverPort;
/**
* 发送邮箱
*/
@Value("${email.sendMail}")
private String sendMail;
}
2、发送方法
参数对象:
package com.example.demo.entity;
import lombok.Data;
import java.util.List;
/**
* 邮件内容
* @author zhanglei
*/
@Data
public class MailContent {
/**
* 邮件标题
*/
private String subject;
/**
* 邮件内容
*/
private String text;
/**
* 附件名称
*/
private List<String> attachmentNameList;
/**
* 附件地址
*/
private List<String> attachmentUrlList;
/**
* 目标邮箱
*/
private String toEmail;
/**
* 抄送邮箱
*/
private String ccEmail;
}
发送方法:
package com.example.demo.util;
import com.example.demo.config.EmailConfig;
import com.example.demo.entity.MailContent;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 自定义邮箱发送邮件
*
* @author zhanglei
* @version 1.0
* @date 2024-03-05 15:08
*/
@Component
public class MailSendSmtp {
/**
* 默认端口号
*/
public static final Integer MAIL_DEFAULT_PORT = 25;
@Autowired
private EmailConfig emailConfig;
/*{
"attachmentNameList": [
"附件名.pdf"
],
"attachmentUrlList": [
"https://invtest.nntest.cn/fp/BoRzE95ScXVqSZDehEhBZbz0YyYUFDwZ4Rr8oEuLzBfeM7rFoDSjYRKObeRPOHXyAnrfgbHtf4mz5r3-qvJRvQ.pdf"
],
"ccEmail": "",
"subject": "测试邮件",
"text": "你好,这个测试邮件,请忽略",
"toEmail": "1953623531.qq.com"
}*/
/**
* 发送邮件,自己发送,不使用消息中心
*
* @param mailContent 邮件内容
* @throws Exception 异常
*/
public boolean send(MailContent mailContent) {
try {
//抄送地址
List<String> addresses = new ArrayList<>();
addresses.add(mailContent.getToEmail());
if (StringUtils.isNotBlank(mailContent.getCcEmail())) {
String[] ccs = mailContent.getCcEmail().split(";");
for (String addr : ccs) {
if (StringUtils.isNotBlank(addr)) {
addresses.add(addr);
}
}
}
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
// 设置邮件内容格式
javaMailSender.setDefaultEncoding("utf-8");
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
javaMailSender.setHost(emailConfig.getServerUrl());
// 设置默认端口,防止使用域名的时候,解析不正确
Integer port = emailConfig.getServerPort() == null ? MAIL_DEFAULT_PORT : emailConfig.getServerPort();
if (!MAIL_DEFAULT_PORT.equals(port)) {
javaMailSender.setPort(port);
}
javaMailSender.setUsername(emailConfig.getUsername());
javaMailSender.setPassword(emailConfig.getPassword());
// 如果配置的发送邮箱为空,则使用邮件账号;否则使用发送邮箱
helper.setFrom(StringUtils.isBlank(emailConfig.getSendMail()) ? emailConfig.getUsername() : emailConfig.getSendMail());
//目标邮箱
helper.setTo(mailContent.getToEmail());
//邮件内容
helper.setText(mailContent.getText(), true);
//邮件标题
helper.setSubject(mailContent.getSubject());
// 增加抄送人
if (StringUtils.isNotBlank(mailContent.getCcEmail())) {
helper.setCc(addresses.toArray(new String[0]));
}
//附件,可以是多个,获取文件流
if (CollectionUtils.isNotEmpty(mailContent.getAttachmentNameList())) {
for (int i = 0; i < mailContent.getAttachmentNameList().size(); i++) {
String fileName = mailContent.getAttachmentNameList().get(i);
String url = mailContent.getAttachmentUrlList().get(i);
byte[] pdfBytes = HttpClientUtil.getRemoteResource(url, 5000);
if (pdfBytes != null) {
ByteArrayResource pdfResource = new ByteArrayResource(pdfBytes);
helper.addAttachment(MimeUtility.encodeText(fileName), pdfResource, "application/pdf");
}
}
}
Properties props = new Properties();
/*// 增加ssl配置
if (mailInfoUtil.isEnableSsl()) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
}
// 增加tsl配置
if (mailInfoUtil.isEnableTls()) {
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
}
*/
if (!props.isEmpty()) {
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
@Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailConfig.getUsername(), emailConfig.getPassword());
}
});
javaMailSender.setSession(session);
}
// 发送邮件
javaMailSender.send(mimeMessage);
return true;
} catch (Exception e) {
return false;
}
}
}
项目地址:https://gitee.com/itzhl/dynamic-data-source-demo.git