Java代码
controller
@Log(title = "发送邮件", businessType = BusinessType.INSERT)
@RequestMapping("/sendemail")
public AjaxResult sendemail(String toMails, String mailContent) throws Exception {
System.out.println(toMails);
System.out.println(mailContent);
MailUtil mailUtil = new MailUtil();
return mailUtil.sendMail(mailHost,fromMail,fromName,fromMailPwd,toMails,mailTitle,mailContent);
}
工具类 MailUtil (邮件发送有文本、图片、h5样式等调自己用到的)
package com.jtport.tgt.modules.bulk;
import java.io.*;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.jtport.common.core.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestBody;
/**
* 发送邮件工具类
*/
@ComponentScan
public class MailUtil {
private final static Logger logger = LoggerFactory.getLogger(MailUtil.class);
public static String buildContent(HashMap<String,String> parameterMap) throws IOException {
String reminderDate = parameterMap.get("reminderDate");
//加载邮件html模板
File fileName = new File("Email_Template_30.html");
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
StringBuffer buffer = new StringBuffer();
String line = "";
try {
while ((line = fileReader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
logger.error("读取文件失败,fileName:{}", fileName, e);
} finally {
fileReader.close();
}
Date date = new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String array[] = {"梅奥心磁","100",sdf.format(date),"serverId"};
//替换参数
String htmlText = MessageFormat.format(buffer.toString(), array);
return htmlText;
}
/**
* 邮件发送
* @param mailHost 邮件服务地址
* @param fromMail 发件人
* @param fromName 发件人名
* @param fromMailPwd 发件人密码
* @param toMails 收件人,多个用英文逗号分隔
* @param mailTitle 邮件标题
* @param mailContent 邮件内容
* @throws Exception
*/
public static AjaxResult sendMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
String toMails, String mailTitle, String mailContent) throws Exception {
String[] toMailArr = null;
if (toMails != null && !toMails.equals("")) {
toMailArr = toMails.split(",");
} else {
throw new Exception("邮件发送人不能为空");
}
// 邮件属性信息
Properties props = new Properties();
props.put("mail.host", mailHost);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props); // 根据属性新建一个邮件会话
//session.setDebug(true); // 是否打印调试信息
toMailArr = toMails.split(",");
for (String to : toMailArr) {
MimeMessage message = new MimeMessage(session); // 由邮件会话新建一个消息对象
message.setFrom(new InternetAddress(fromMail));// 设置发件人的地址
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to, fromName));// 设置收件人,并设置其接收类型为TO
message.setSubject(mailTitle);// 设置标题
message.setContent(mailContent, "text/html;charset=UTF-8"); // 设置邮件内容类型为html
message.setSentDate(new Date());// 设置发信时间
message.saveChanges();// 存储邮件信息
// 发送邮件
Transport transport = session.getTransport();
transport.connect(fromMail, fromMailPwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
return null;
}
/**
* 邮件发送(群发)
* @param mailHost 邮件服务地址
* @param fromMail 发件人
* @param fromName 发件人名
* @param fromMailPwd 发件人密码
* @param toMails 收件人,多个用英文逗号分隔
* @param mailTitle 邮件标题
* @param mailContent 邮件内容
* @throws Exception
*/
public static void sendGroupMail(String mailHost, String fromMail, String fromName, String fromMailPwd,
String toMails, String mailTitle, String mailContent) throws Exception {
String[] toMailArr = null;
if (toMails != null && !toMails.equals("")) {
toMailArr = toMails.split(",");
} else {
throw new Exception("邮件发送人不能为空");
}
// 邮件属性信息
Properties props = new Properties();
props.put("mail.host", mailHost);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props); // 根据属性新建一个邮件会话
//session.setDebug(true); // 是否打印调试信息
MimeMessage message = new MimeMessage(session); // 由邮件会话新建一个消息对象
message.setFrom(new InternetAddress(fromMail)); // 设置发件人的地址
InternetAddress[] sendTo = new InternetAddress[toMailArr.length];
for (int i = 0; i < toMailArr.length; i++) {
sendTo[i] = new InternetAddress(toMailArr[i], fromName);
}
message.setRecipients(Message.RecipientType.TO, sendTo); // 设置收件人,并设置其接收类型为TO
message.setSubject(mailTitle); // 设置标题
message.setContent(mailContent, "text/html;charset=UTF-8"); // 设置邮件内容类型为html
message.setSentDate(new Date()); // 设置发信时间
message.saveChanges(); // 存储邮件信息
// 发送邮件
Transport transport = session.getTransport();
transport.connect(fromMail, fromMailPwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
/**
* 读取html文件为String
* @param htmlFileName
* @return
* @throws Exception
*/
public static 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) {
logger.error("关闭io流异常", e);
}
try {
if (reader != null) {
reader.close();
}
} catch ( IOException e) {
logger.error("关闭io流异常", e);
}
}
}
}
bootstrap.yml文件配置
spring:
#邮箱基本配置
mail:
#配置smtp服务主机地址
# qq邮箱为smtp.qq.com 端口号465或587
# sina smtp.sina.cn
# aliyun smtp.aliyun.com
# 163 smtp.163.com 端口号465或994
mailHost : smtp.qq.com #发送者邮箱
fromMail : 1148586027@qq.com #发件人邮箱
mailTitle: 抖音:年仅二十开始养老 #邮箱标题
fromName: 年仅二十开始养老 #发件人
#配置密码,注意不是真正的密码,而是刚刚申请到的授权码
fromMailPwd : #授权码
#端口号465或587
port: 465
#默认的邮件编码为UTF-8
default-encoding: UTF-8
#其他参数
properties:
mail:
#配置SSL 加密工厂
smtp:
socketFactory:
class: javax.net.ssl.SSLSocketFactory
#开启debug模式,这样邮件发送过程的日志会在控制台打印出来,方便排查错误
debug: true
#
前端代码
uni.request({
//端口号前面是本地电脑地址
url: "http://192.168.x.xxx:6007/wtUser/sendemail", //本地地址和后端端口地址
data:{ //参数
toMails:this.email,
mailContent:xinxi
},
header: {
'Content-Type': 'application/json' //自定义请求头信息
},
sslVerify:false,
method: 'GET', //请求方式,必须为大写
success: (res) => {
console.log('接口返回------', res);
if (res.statusCode == 200) {
uni.navigateTo({
url: `../set/sendsucceed?email=${this.email}`
});
} else {
alert('!')
}
},
fail:res=>{
console.log(res);
}
})
pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>