提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 邮箱效果图
- 一、pom配置
- 二、页面编写
- 三、配置yml
- 四、邮件工具类
- 五、测试发送
邮箱效果图
1.可以利用在出现问题进行邮箱提醒
2.编写html 用于在邮箱中展示的样式
提示:以下是本篇文章正文内容,下面案例可供参考
一、pom配置
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--邮件--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId></dependency><dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.10.3</version></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.28</version><scope>compile</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version></dependency>
二、页面编写
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>系统通知邮件模板-纯文本型</title>
</head><body>
<div style="font-size: 14px;"><br><br><br><br><div style="width: 600px; margin: 0 auto; background-color: #00838a; border-radius: 3px;"><div style="padding: 0 15px; padding-bottom: 20px;"><div style="height: 72px;"><div><a href="https://www.lplovemm.love/" target="_blank" rel="noopener"style="text-decoration: none;"><img src="http://mall.bydauto.com.cn/pc/_nuxt/img/logo.97a8e60.svg" style="height: 72px;"alt="BYD" title="BYD"></a></div></div><div style="background: #fff; padding: 20px 15px; border-radius: 3px;"><div><span style="font-size: 16px; font-weight: bold;">待办通知:</span><div style="line-height: 24px; margin-top: 10px;"><div>您有一条新的“<span style="font-weight: bold;">订单询价</span>待办,编号为“<span style="font-weight: bold;" id="ip"></span>”,收到信息后请尽快<a style="color: #006eff;font-weight: bold;" href="https://mall.bydauto.com.cn/"target="_blank" rel="noopener">登录MALL系统</a>处理!</div></div></div><div style="margin-top: 30px;"><div><spanstyle="font-size: 15px; font-weight: bold; position: relative; top: -4px;">流程信息</span></div><tablestyle="width: 400px; border-spacing: 0px; border-collapse: collapse; border: none; margin-top: 20px;"><tbody><tr style="height: 45px;"><tdstyle="width: 150px; height: 40px; background: #F6F6F6;border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">上一节点</td><tdstyle="width: 250px;height: 40px; border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">订单咨询</td></tr><tr style="height: 45px;"><tdstyle="width: 150px;height: 40px; background: #F6F6F6;border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">处理人</td><tdstyle="width: 250px;height: 40px; border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">张先生</td></tr><tr style="height: 45px;"><tdstyle="width: 150px; height: 40px; background: #F6F6F6;border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;">当前节点</td><tdstyle="width: 250px;height: 40px; border: 1px solid #DBDBDB; font-size: 14px; font-weight: normal; text-align: left; padding-left: 14px;"><a style="color: #006eff;" href="https://mall.bydauto.com.cn/" target="_blank"rel="noopener">订单询价</a></td></tr></tbody></table></div><div style="margin-top: 60px;margin-bottom: 10px;"><spanstyle="font-size: 13px; font-weight: bold; color: #666;">温馨提醒</span><div style="line-height: 24px; margin-top: 10px;"><div style="font-size: 13px; color: #666;">使用过程中如有任何问题,请联系LIMS系统管理员。</div></div></div></div></div></div><divstyle="width: 600px; margin: 0 auto; margin-top: 50px; font-size: 12px; -webkit-font-smoothing: subpixel-antialiased; text-size-adjust: 100%;"><pstyle="text-align: center; line-height: 20.4px; text-size-adjust: 100%; font-family: 'Microsoft YaHei'!important; padding: 0px !important; margin: 0px !important; color: #7e8890 !important;"><span class="appleLinks">Copyright © 2023-2024 北京XXXX科技股份有限公司. 保留所有权利。</span></p><pstyle="text-align: center;line-height: 20.4px; text-size-adjust: 100%; font-family: 'Microsoft YaHei'!important; padding: 0px !important; margin: 0px; color: #7e8890 !important; margin-top: 10px;"><span class="appleLinks">邮件由系统自动发送,请勿直接回复本邮件!</span></p></div>
</div>
</body></html>
三、配置yml
#配置日志logging:level:root: infoapplication:name: spring-boot-emailmvc.async.request-timeout: 20000#配置邮箱mail:default-encoding: UTF-8host: smtp.163.compassword: **********port: 465username: **********@163.comproperties:mail:smtp:auth: truesocketFactory:class: javax.net.ssl.SSLSocketFactorystarttls:enable: true
四、邮件工具类
package com.information.utils;import java.io.*;
import java.util.Date;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;/*** 发送邮件工具类*/
public class MailUtil {private final static Logger logger = LoggerFactory.getLogger(MailUtil.class);/*** 邮件发送* @param mailHost 邮件服务地址* @param fromMail 发件人* @param fromName 发件人名* @param fromMailPwd 发件人密码* @param toMails 收件人,多个用英文逗号分隔* @param mailTitle 邮件标题* @param mailContent 邮件内容* @throws Exception*/public static void 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,fromName));message.setRecipient(Message.RecipientType.TO, new InternetAddress(to, fromName));// 设置收件人,并设置其接收类型为TOmessage.setSubject(mailTitle);// 设置标题message.setContent(mailContent, "text/html;charset=UTF-8"); // 设置邮件内容类型为htmlmessage.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);}}}}
五、测试发送
@Autowiredprivate JavaMailSender mailSender;/*** 发送者邮箱*/@Value("${spring.mail.username}")public String MAIL_USERNAME;/*** 发送者host*/@Value("${spring.mail.host}")public String MAIL_HOST;/*** 发送者秘钥*/@Value("${spring.mail.password}")public String PASSWORD;@RequestMapping("/ip")@ResponseBodypublic String bc(HttpServletRequest request){try {List<String> list = new LinkedList<>();Enumeration enumeration = NetworkInterface.getNetworkInterfaces();while (enumeration.hasMoreElements()) {NetworkInterface network = (NetworkInterface) enumeration.nextElement();if (network.isVirtual() || !network.isUp()) {continue;} else {Enumeration addresses = network.getInetAddresses();while (addresses.hasMoreElements()) {InetAddress address = (InetAddress) addresses.nextElement();if (address != null && (address instanceof Inet4Address || address instanceof Inet6Address)) {list.add(address.getHostAddress());}}}}//获取id地址String ip= InetAddress.getLocalHost().getHostAddress();// 创建 HttpClient 实例CloseableHttpClient httpClient = HttpClientBuilder.create().build();//根据ip地址和百度ip普通定位的ak,去获取具体位置String url = "https://api.map.baidu.com/location/ip?ip="+ip+"&coor=bd09ll&ak=***********";// 创建 HttpGet 请求HttpGet httpGet = new HttpGet(url);HttpResponse response = httpClient.execute(httpGet);HttpEntity entity = response.getEntity();// 转换为字符串String json = EntityUtils.toString(entity);Map map = (Map) JSONObject.parse(json); Map content = (Map) map.get("content");Map point = (Map) content.get("point");JSONObject jsonObject = JSONObject.parseObject(point.toString());String x = jsonObject.getString("x");String y = jsonObject.getString("y");// 读取html模板String html = MailUtil.readHtmlToString("mailTemplate.html");// 将拿到的x和y的经纬度写入模板内容Document doc = Jsoup.parse(html);doc.getElementById("ip").html(ip);doc.getElementById("x").html(x);doc.getElementById("y").html(y);String result = doc.toString();String fromName = "小扎仙森";String toMails = "1046406274@qq.com";String mailTitle = "hello java mail";String mailContent = result;/*** 邮件发送* @param mailHost 邮件服务地址* @param fromMail 发件人* @param fromName 发件人名* @param fromMailPwd 发件人密码* @param toMails 收件人,多个用英文逗号分隔* @param mailTitle 邮件标题* @param mailContent 邮件内容* @throws Exception*/// 发送邮件MailUtil.sendMail(MAIL_HOST, MAIL_USERNAME,fromName, PASSWORD, toMails, mailTitle, mailContent);return "邮箱发送成功";} catch (IOException e) {e.printStackTrace();} catch (Exception e) {throw new RuntimeException(e);}return "发送失败";}