@Data
public class SendToVo {
private static final long serialVersionUID = 1L;
/**
* 收件邮箱地址
*/
String toMail;
/**
* 附件
*/
List<File> files;
/**
* 标题
*/
String mailTitle;
/**
* 内容
*/
String content;
/**
* 文件路径
*/
String filesPath;
/**
* 月份/季度
*/
String monthDate;
/**
* 发件日期
*/
String sendDate;
}
## 2.不使用代理发送邮件
package com.xxx.common.utils.mail;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.xxx.common.exception.base.BaseException;
import com.xxx.common.utils.AESUtil;
import com.xxx.common.utils.DictUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.io.*;
import java.text.MessageFormat;
import java.util.List;
/**
-
@author wuhebin
-
@description 邮箱发送服务
-
@date 2024/1/24 16:36
**/
@Service
public class MyMailUtil {
private static final Logger log = LoggerFactory.getLogger(MyMailUtil.class);public void send(List toVoList) throws BaseException {
if(toVoList==null||toVoList.size()==0)return;
String fromMail = DictUtils.getDictValue(“sys_param”,“email.fromMail”);
String fromMailHost = DictUtils.getDictValue(“sys_param”,“email.fromMailHost”);
String fromMailPort = DictUtils.getDictValue(“sys_param”,“email.fromMailPort”);
String fromMailPass = DictUtils.getDictValue(“sys_param”,“email.fromMailPass”);
String sslEnable = DictUtils.getDictValue(“sys_param”,“email.sslEnable”);
String starttlsEnable = DictUtils.getDictValue(“sys_param”,“email.starttlsEnable”);if(StrUtil.isBlank(fromMail)){ log.error("邮件投递失败,发件人信息未配置邮箱地址"); return; } if(StrUtil.isBlank(fromMailHost)){ log.error("邮件投递失败,发件人信息未配置邮箱SMTP服务器域名"); return; } if(StrUtil.isBlank(fromMailPort)){ log.error("邮件投递失败,发件人信息未配置邮箱SMTP服务端口"); return; } if(!Validator.isNumber(fromMailPort)){ log.error("邮件投递失败,发件人信息配置的邮箱SMTP服务端口不正确,端口应为数字"); return; } if(StrUtil.isBlank(fromMailPass)){ log.error("邮件投递失败,发件人信息未配置邮箱授权密码"); return; } MailAccount mailAccount = new MailAccount(); mailAccount.setHost(fromMailHost); mailAccount.setPort(Integer.valueOf(fromMailPort)); mailAccount.setFrom(fromMail); mailAccount.setUser(fromMail); mailAccount.setPass(AESUtil.jiemi(fromMailPass));//163我的授权码 mailAccount.setAuth(true); mailAccount.setSslProtocols("TLSv1.2"); if(StrUtil.equals(sslEnable,"1")){ mailAccount.setSslEnable(true); }else{ mailAccount.setSslEnable(false); } if(StrUtil.equals(starttlsEnable,"1")){ mailAccount.setStarttlsEnable(true); }else{ mailAccount.setStarttlsEnable(false); } for (int i=0;i<toVoList.size();i++){ SendToVo toVo = toVoList.get(i); String subject = toVo.getMailTitle(); String to = toVo.getToMail(); if (StrUtil.isNotBlank(to)){ to = to + "," + fromMail; }else{ to = fromMail; } String content = toVo.getContent(); List<File> files = toVo.getFiles(); String messageId = ""; try { if(files!=null&&files.size()>0){ messageId = MailUtil.send( mailAccount, to, subject, content, null, false, files.toArray(new File[files.size()])); }else{ messageId = MailUtil.send( mailAccount, to, subject, content, null, true); } log.info("邮件投递成功,给【"+toVo.getToMail()+"】的主题【"+subject+"】邮件投递成功"); }catch (Exception e){ log.error("邮件投递失败,给【"+toVo.getToMail()+"】的主题【"+subject+"】邮件投递失败:",e); } }
}
public String buildContent(String[] array) throws IOException {
//加载邮件html模板
InputStream inputStream = MailUtil.class.getClassLoader().getResourceAsStream(“static/Email_Template.html”);
BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream, “UTF-8”));
StringBuffer buffer = new StringBuffer();
String line = “”;
try {
while ((line = fileReader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
log.error(“读取文件失败,fileName:{}”, “”, e);
} finally {
fileReader.close();
}
//替换参数
String htmlText = MessageFormat.format(buffer.toString(), array);
return htmlText;
}/**
- 读取html文件为String
- @param htmlFileName
- @return
- @throws Exception
*/
public String readHtmlToString(String htmlFileName) throws Exception{
InputStream is = null;
Reader reader = null;
try {
is = MailUtil.class.getClassLoader().getResourceAsStream(htmlFileName);
if (is == null) {
throw new Exception(“未找到模板文件”);
}
reader = new InputStreamReader(is, “UTF-8”);
StringBuilder sb = new StringBuilder();
int bufferSize = 1024;
char[] buffer = new char[bufferSize];
int length = 0;
while ((length = reader.read(buffer, 0, bufferSize)) != -1){
sb.append(buffer, 0, length);
}
return sb.toString();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
log.error(“关闭io流异常”, e);
}
try {
if (reader != null) {
reader.close();
}
} catch ( IOException e) {
log.error(“关闭io流异常”, e);
}
}
}
}
## 3.发送socks代理邮件
package com.xxx.util;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailUtil;
import com.xxx.common.exception.ServiceException;
import com.xxx.common.exception.base.BaseException;
import com.xxx.common.utils.AESUtil;
import com.xxx.common.utils.DictUtils;
import com.xxx.common.utils.mail.SendToVo;
import com.asiadb.system.service.impl.SysConfigServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.*;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
/**
-
@author wuhebin
-
@description 邮箱发送服务
-
@date 2024/1/24 16:36
**/
@Service
public class MyMailUtil {
private static final Logger log = LoggerFactory.getLogger(MyMailUtil.class);
@Autowired
private SysConfigServiceImpl sysConfigService;public void send(List toVoList) throws BaseException {
if(toVoList==null||toVoList.size()==0)return;
String fromMail = DictUtils.getDictValue(“sys_param”,“email.fromMail”);
String fromMailHost = DictUtils.getDictValue(“sys_param”,“email.fromMailHost”);
String fromMailPort = DictUtils.getDictValue(“sys_param”,“email.fromMailPort”);
String fromMailPass = DictUtils.getDictValue(“sys_param”,“email.fromMailPass”);
String sslEnable = DictUtils.getDictValue(“sys_param”,“email.sslEnable”);
String starttlsEnable = DictUtils.getDictValue(“sys_param”,“email.starttlsEnable”);if(StrUtil.isBlank(fromMail)){ log.error("邮件投递失败,发件人信息未配置邮箱地址"); return; } if(StrUtil.isBlank(fromMailHost)){ log.error("邮件投递失败,发件人信息未配置邮箱SMTP服务器域名"); return; } if(StrUtil.isBlank(fromMailPort)){ log.error("邮件投递失败,发件人信息未配置邮箱SMTP服务端口"); return; } if(!Validator.isNumber(fromMailPort)){ log.error("邮件投递失败,发件人信息配置的邮箱SMTP服务端口不正确,端口应为数字"); return; } if(StrUtil.isBlank(fromMailPass)){ log.error("邮件投递失败,发件人信息未配置邮箱授权密码"); return; } // 设置代理服务器 Properties props = System.getProperties(); // 设置发信邮箱的smtp服务器 props.setProperty("mail.smtp.host", fromMailHost); // 设置发信邮箱的smtp端口号 props.setProperty("mail.smtp.port", fromMailPort); // 安全验证 props.put("mail.smtp.auth", "true"); props.put("mail.smtp.ssl.protocols", "TLSv1.2"); props.setProperty("mail.transport.protocol", "smtp"); if(StrUtil.equals(sslEnable,"1")){ props.setProperty("mail.smtp.ssl.enable", "true"); }else{ props.setProperty("mail.smtp.ssl.enable", "false"); } if(StrUtil.equals(starttlsEnable,"1")){ props.setProperty("mail.smtp.starttls.enable", "true"); }else{ props.setProperty("mail.smtp.starttls.enable", "false"); } //调整修改为局部代理 props.remove("mail.smtp.socks.host"); props.remove("mail.smtp.socks.port"); String pwd = AESUtil.jiemi(fromMailPass); //使用代理 String agentHost = sysConfigService.selectConfigByKey( "network_export_agent.host"); String agentPort = sysConfigService.selectConfigByKey( "network_export_agent.port"); String agentUser = sysConfigService.selectConfigByKey( "network_export_agent.user"); String agentPassword = sysConfigService.selectConfigByKey( "network_export_agent.password"); if(StrUtil.isAllNotBlank(agentHost,agentPort)){ //全局代理,会造成系统使用代理,这里只需要发送邮件时使用代理,故作修改 //props.setProperty("proxySet", "true"); //props.setProperty("socksProxyHost", agentHost); //props.setProperty("socksProxyPort", agentPort); //设置局部代理 props.setProperty("mail.smtp.socks.host", agentHost); props.setProperty("mail.smtp.socks.port", agentPort); if (StrUtil.isAllNotBlank(agentUser,agentPassword)){ MyJavaAuthenticator authenticator = new MyJavaAuthenticator(agentUser, agentPassword); java.net.Authenticator.setDefault(authenticator); } } Session session = Session.getDefaultInstance(props); for (int i=0;i<toVoList.size();i++){ SendToVo toVo = toVoList.get(i); String subject = toVo.getMailTitle(); try { //创建邮件 MimeMessage message = createEmail(session,fromMail,toVo);//将用户和内容传递过来 //获取传输通道 Transport transport = session.getTransport(); transport.connect(fromMailHost,fromMail, pwd); //连接,并发送邮件 transport.sendMessage(message, message.getAllRecipients()); transport.close(); log.info("邮件投递成功,给【"+toVo.getToMail()+"】的主题【"+subject+"】邮件投递成功"); }catch (Exception e){ log.error("邮件投递失败,给【"+toVo.getToMail()+"】的主题【"+subject+"】邮件投递失败:",e); e.printStackTrace(); throw new ServiceException("Mail delivery failed, please contact administrator."); } }
}
class MyJavaAuthenticator extends java.net.Authenticator {
private String user = “”;
private String password = “”;public MyJavaAuthenticator(String user, String password) { this.user = user; this.password = password; } protected java.net.PasswordAuthentication getPasswordAuthentication() { return new java.net.PasswordAuthentication(user, password.toCharArray()); }
}
public static MimeMessage createEmail(Session session,String fromMail,SendToVo toVo) throws Exception {
String subject = toVo.getMailTitle();
String to = toVo.getToMail();
if (StrUtil.isNotBlank(to)){
to = to + “,” + fromMail;
}else{
to = fromMail;
}
String content = toVo.getContent();// 根据会话创建邮件 MimeMessage msg = new MimeMessage(session); // 设置发送邮件方 Address fromAddress = new InternetAddress(fromMail); msg.setFrom(fromAddress); // 设置邮件接收方 Address[] internetAddressTo = new InternetAddress().parse(to); msg.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo); // 设置邮件标题 msg.setSubject(subject, "utf-8"); msg.setContent(content,"text/html;charset=UTF-8"); // 设置显示的发件时间 msg.setSentDate(new Date()); return msg;
}
public String buildContent(String[] array) throws IOException {
//加载邮件html模板
InputStream inputStream = MailUtil.class.getClassLoader().getResourceAsStream(“static/Email_Template.html”);
BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream, “UTF-8”));
StringBuffer buffer = new StringBuffer();
String line = “”;
try {
while ((line = fileReader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
log.error(“读取文件失败,fileName:{}”, “”, e);
} finally {
fileReader.close();
}
//替换参数
String htmlText = MessageFormat.format(buffer.toString(), array);
return htmlText;
}/**
- 读取html文件为String
- @param htmlFileName
- @return
- @throws Exception
*/
public String readHtmlToString(String htmlFileName) throws Exception{
InputStream is = null;
Reader reader = null;
try {
is = MailUtil.class.getClassLoader().getResourceAsStream(htmlFileName);
if (is == null) {
throw new Exception(“未找到模板文件”);
}
reader = new InputStreamReader(is, “UTF-8”);
StringBuilder sb = new StringBuilder();
int bufferSize = 1024;
char[] buffer = new char[bufferSize];
int length = 0;
while ((length = reader.read(buffer, 0, bufferSize)) != -1){
sb.append(buffer, 0, length);
}
return sb.toString();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
log.error(“关闭io流异常”, e);
}
try {
if (reader != null) {
reader.close();
}
} catch ( IOException e) {
log.error(“关闭io流异常”, e);
}
}
}
}
## 4.使用
public void sendUserEmail(String email, String customerId, String userName, String password, String mailTitle) {
List toVoList = new ArrayList<>();
SendToVo sendToVo = new SendToVo();
sendToVo.setToMail(email);
sendToVo.setMailTitle(MessageUtils.message(mailTitle));
String array[] = {MessageUtils.message(“platform.name”),
MessageUtils.message(mailTitle),
MessageUtils.message(“platform.dear”) + userName,
MessageUtils.message(“platform.thank”),
MessageUtils.message(“platform.account”),
MessageUtils.message(“platform.customerId”),
customerId,
MessageUtils.message(“platform.username”),
“admin”,
MessageUtils.message(“platform.userPass”),
password,
MessageUtils.message(“platform.end”),
MessageUtils.message(“platform.jinggao”)};
try {
sendToVo.setContent(myMailUtil.buildContent(array));
} catch (IOException e) {
throw new RuntimeException(e);
}
toVoList.add(sendToVo);
myMailUtil.send(toVoList);
}
## 5.模板static/Email\_Template.html
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注:Python)
font-size:inherit
!important;
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。
深知大多数Python工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Python开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-k4gqAA63-1713592944105)]
[外链图片转存中…(img-lNQdDQVs-1713592944106)]
[外链图片转存中…(img-KFpT9xWb-1713592944106)]
[外链图片转存中…(img-2CFF8yHv-1713592944107)]
既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上前端开发知识点,真正体系化!
由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新
如果你觉得这些内容对你有帮助,可以扫码获取!!!(备注:Python)