引入javax.mail包
<!--邮件发送-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
配置application.yml
需要使用公共邮箱的看这: 如何创建公共邮箱,可以把成员邮箱设置成管理员.然后就可以扫码登录企业公共邮箱了.
扫码登录网页端企业邮箱,在设置的的右边有个切换账号(如下图).
前提,在企业微信公共邮箱内 设置 ——>收发信设置——>开启服务,在①开启IMAP/SMTP服务,②开启POP/SMTP服务 前面打勾。
腾讯企业邮箱网页版:https://exmail.qq.com/login
下面代码块的password在 设置 ——>邮箱绑定——>安全登录,点击生成新密码,复制到
spring:
mail:
host: smtp.exmail.qq.com
port: 465
username: 企业微信公共邮箱名
password: 安全登录地方生成的新密码
default-encoding: utf-8
properties:
mail.smtps.connectiontimeout: 150000
mail.smtps.timeout: 250000
mail.smtps.writetimeout: 5000
mail.smtp.auth: true
mail.smtp.auth.starttls.required: true
mail.smtp.auth.starttls.enable: true
写一个mail的工具类;EmailUtil
package tech.youchu.ems.security.util;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
public class EmailUtil {
private static String account = "";// 登录账户
private static String password = "";// 登录密码
private static String host = "smtp.exmail.qq.com";// 服务器地址
private static String port = "465";// 端口
private static String protocol = "smtp";// 协议
//初始化参数
//初始化参数
public static Session initProperties() {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", protocol);
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", port);
// 使用smtp身份验证
properties.put("mail.smtp.auth", "true");
// 使用SSL,企业邮箱必需 start
properties.put("mail.debug","true");
// 开启安全协议
MailSSLSocketFactory mailSSLSocketFactory = null;
try {
mailSSLSocketFactory = new MailSSLSocketFactory();
mailSSLSocketFactory.setTrustAllHosts(true);
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
properties.put("mail.smtp.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
properties.put("mail.smtp.socketFactory.port", port);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(account, password);
}
});
// 使用SSL,企业邮箱必需 end
// TODO 显示debug信息 正式环境注释掉
session.setDebug(true);
return session;
}
/**
* 发送邮件
*
* @param sender 发件人别名
* @param subject 邮件主题
* @param content 邮件内容
* @param receiverList 接收者列表
* @param fileSrc 附件地址
*/
public void send(String sender, String subject, String content, String receiverList, String fileSrc) {
try {
Session session = initProperties();
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(account, sender));// 发件人,可以设置发件人的别名
// 收件人,多人接收
InternetAddress[] internetAddressTo = new InternetAddress().parse(receiverList);
mimeMessage.setRecipients(Message.RecipientType.TO, internetAddressTo);
// 主题
mimeMessage.setSubject(subject);
// 时间
mimeMessage.setSentDate(new Date());
// 容器类 附件
MimeMultipart mimeMultipart = new MimeMultipart();
// 可以包装文本,图片,附件
MimeBodyPart bodyPartContent = new MimeBodyPart();
// 设置内容
bodyPartContent.setContent(content, "text/html; charset=UTF-8");
mimeMultipart.addBodyPart(bodyPartContent);
// 添加图片&附件
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.attachFile(fileSrc);
mimeMultipart.addBodyPart(bodyPart);
mimeMessage.setContent(mimeMultipart);
mimeMessage.saveChanges();
Transport.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
接下来就是发送邮件,还是一样的套路;前端发出请求,后端接收数据之后处理完成之后,把需要发送到邮箱的数据生成execl, 在处理完数据之后调用发送邮件函数
HashMap<String, double[]> forecast = getReturnForecast(oneYearProfit, fullMoney, epc, sharingRatio, transCharge, 15);
result = this.generateExcel(forecast, companyName, params.getString("companyEmail"),15);
public static HashMap getReturnForecast(double firstYearReturn, double fullMoney, double epc, double sharingRatio, double transCharge, int years) {
HashMap<String, double[]> result = new HashMap<>();
double[] cashInflow = new double[years]; //现金流入
double[] cashOutFlow = new double[years]; //现金流出
//处理数据填充上面数组
.
.
.
return result;
}
/**
* 生成excel 并发送
* @param forecast 15年数据
* @param companyName 公司名称
*/
public JSONObject generateExcel(HashMap<String, double[]> forecast, String companyName, String companyEmail, int year) throws IOException {
JSONObject result = new JSONObject();
List<EmsExcelEmail> dataList = new ArrayList<>();
double[] cashInflow = forecast.get("cashInflow");
double[] cashOutFlow = forecast.get("cashOutFlow");
double tenThousand = 10000;
// 构造数据
for (int i = 0; i < year; i++) {
EmsExcelEmail data = new EmsExcelEmail();
data.setYearAndProject("第" + (i+1) + "年");
//需除10000并保留2位小数;单位是万元;
data.setCashInflow(cashInflow[i] / tenThousand);
data.setCashOutFlow(cashOutFlow[i] / tenThousand);
dataList.add(data);
}
// 获取资源文件存放路径,用于临时存放生成的excel文件
// String path = Objects.requireNonNull(this.getClass().getClassLoader().getResource("")).getPath();
// String path = Files.createTempDirectory(Paths.get("/tmp"),"abc").toString();
String tempDir = System.getProperty("java.io.tmpdir") + File.separator + "sendMail" + File.separator;
Path tempPath = Paths.get(tempDir);
if(!Files.exists(tempPath)){
Files.createDirectory(tempPath);
}
// 文件名:采用UUID,防止多线程同时生成导致的文件重名
String fileSrc = new String(String.format("%s%s的项目预测-%s.xlsx", tempDir, companyName, UUID.randomUUID()).getBytes(), "UTF-8");
// 发邮件
EmailUtil emailUtil = new EmailUtil();
if(companyEmail.equals("")){
result.put("companyEmail","收件邮箱为空");
return result;
}
try{
File file = ExcelUtil.generateExcel(fileSrc, dataList, EmsExcelEmail.class);
emailUtil.send("方案","方案规划","尊敬的先生/女士: 您的方案以计算完毕,请查收!", companyEmail, fileSrc);
file.delete();
// 邮件发送完成后删除临时生成的excel文件
}catch (IOException e){
log.error(String.format("生成excel失败,原因:%s", e));
e.printStackTrace();
}
result.put("data",true);
return result;
}
效果:
如有错误,请指正!
参考文章: 时间太久, 忘记了, 如有雷同,带上文章链接评论, 这个位置就是文章链接.