【Email】邮件发送
前言
项目主要是通过Java进行Email的发送,需要注意邮件发送的频率、内容,不然会被识别成垃圾邮件。
正文
1.前端代码:
Ps:需要注意引用layui的文件,并且需要注意引用的路径问题。
# spring mvc
spring.mvc.static-path-pattern=/static/**
# resources
spring.resources.static-locations=classpath:/static
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <title>SendEmail</title> <link rel="stylesheet" type="text/css" href="../../static/layui/css/layui.css"/> <style type="text/css"> form { margin-top: 20px; } .layui-input { width: 300px; } .layui-textarea { width: 300px; height: 150px; } </style> </head> <body> <form class="layui-form" action="/sendEmail/send" enctype="multipart/form-data" method="post"> <div class="layui-form-item"> <label class="layui-form-label">From</label> <div class="layui-input-block"> <input type="text" name="from" class="layui-input" value="" /> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">To</label> <div class="layui-input-block"> <input type="text" name="to" class="layui-input" value="" /> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">Subject</label> <div class="layui-input-block"> <input type="text" name="subject" class="layui-input" autocomplete="off"/> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">Affix</label> <div class="layui-input-block"> <button type="button" class="layui-btn" name="file" id="affix"> <i class="layui-icon"></i>附件 </button> </div> </div> <div class="layui-form-item"> <label class="layui-form-label">Content</label> <div class="layui-input-block"> <textarea class="layui-textarea" name="content"></textarea> </div> </div> <div class="layui-form-item"> <div class="layui-input-block"> <button id="send" class="layui-btn" lay-submit lay-filter="formDemo">Send</button> </div> </div> </form> <span th:text="${msg}"></span> </body> </html> <script type="text/javascript" src="../../static/layui/layui.js"></script> <script type="text/javascript"> layui.use('upload', function () { var upload = layui.upload; upload.render({ elem: '#affix', auto: false, accept: 'file', bindAction: '#send', error: function (index, upload) { upload.preventDefault(); } }); }); </script>
2.工具类EmailUtil
package com.example.utils; import org.springframework.web.multipart.MultipartFile; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.File; import java.io.IOException; import java.util.Properties; public class EmailUtil { /** * 保存附件并返回附件路径字符串 * * @param file * @return */ public static String saveFile(MultipartFile file, String fileName) { //文件保存路径 File filePath = new File("src/main/resources/file" + File.separator + fileName); // 路径字符串 String path = filePath.getAbsolutePath(); if (!filePath.exists()) { try { file.transferTo(new File(path)); } catch (IOException e) { e.printStackTrace(); } } return path; } /** * 发送邮件 * * @param fileName * @param from * @param to * @param subject * @param content * @param path * @return */ public static String send(String fileName, String from, String to, String subject, String content, String path) { // 消息 String msg = ""; // 服务器 String host = "smtp.163.com"; // 用户名 String user = "**********"; // 密码(授权码) String pwd = "**********"; Properties prop = new Properties(); // 发送服务器属性 prop.put("mail.smtp.host", host); // 验证 prop.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(prop); // debug session.setDebug(true); // 定义消息对象 MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); Multipart multipart = new MimeMultipart(); BodyPart contentPart = new MimeBodyPart(); contentPart.setText(content); multipart.addBodyPart(contentPart); if (path != null && path != "") { BodyPart affixPart = new MimeBodyPart(); DataSource dataSource = new FileDataSource(path); affixPart.setDataHandler(new DataHandler(dataSource)); affixPart.setFileName(MimeUtility.encodeText(fileName)); multipart.addBodyPart(affixPart); } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(host, user, pwd); transport.sendMessage(message, message.getAllRecipients()); transport.close(); msg = "发送成功!"; } catch (Exception e) { msg = "发送失败!"; e.printStackTrace(); } return msg; } }
3.Controller
package com.example.controller; import com.example.utils.EmailUtil; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/sendEmail") public class SendEmailController { /** * 初始化页面 * @return */ @RequestMapping(value = "/initIndexPage", method = RequestMethod.GET) public String initIndexPage() { return "email/index"; } /** * 发送邮件 * @param from * @param to * @param subject * @param file * @param content * @param model * @return * @throws Exception */ @RequestMapping(value = "/send", method = RequestMethod.POST) public String send(@RequestParam("from") String from, @RequestParam("to") String to, @RequestParam("subject") String subject, @RequestParam("file") MultipartFile file, @RequestParam("content") String content, Model model) throws Exception { String fileName = ""; String path = ""; if (file.getSize()>0) { fileName = file.getOriginalFilename(); path = EmailUtil.saveFile(file, fileName); } String msg = EmailUtil.send(fileName, from, to, subject, content, path); model.addAttribute("msg", msg); return "email/index"; } }
4.前端及测试效果如下:
页面
效果
附件内容预览