1 <!--发邮件--> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-mail</artifactId> 5 </dependency> 6 7 <dependency> 8 <groupId>javax.mail</groupId> 9 <artifactId>mail</artifactId> 10 <version>1.4.5</version> 11 </dependency>
1 package com.example.demo.tools; 2 3 import com.alibaba.fastjson.JSONObject; 4 import org.springframework.web.bind.annotation.*; 5 6 import java.util.LinkedHashMap; 7 import java.util.Map; 8 import java.util.Properties; 9 import javax.mail.Message; 10 import javax.mail.Session; 11 import javax.mail.Transport; 12 import javax.mail.internet.InternetAddress; 13 import javax.mail.internet.MimeMessage; 14 15 /** 16 * 邮件预警 17 * 18 * @author liuwenlong 19 * @create 2021-10-14 12:46:19 20 */ 21 22 @RestController 23 @RequestMapping("tools") 24 @SuppressWarnings("all") 25 public class Mail { 26 27 @GetMapping("test") 28 public String PermitAll() { 29 return "Success"; 30 } 31 32 /** 33 * 发送邮件功能 34 * 35 * @param recipient 收件人 36 * @param Subject 主题 37 * @param content 内容 38 * @throws Exception 39 40 */ 41 @PostMapping(value = "SendMail", produces = "application/json;charset=UTF-8") 42 public Map<String, String> SendMail(@RequestBody JSONObject body) throws Exception { 43 44 String recipient = body.getJSONObject("data").getString("recipient"); 45 String Subject = body.getJSONObject("data").getString("Subject"); 46 String content = body.getJSONObject("data").getString("content"); 47 48 Properties prop = new Properties(); 49 prop.setProperty("mail.host", "smtp.163.com"); 50 prop.setProperty("mail.transport.protocol", "smtp"); 51 prop.setProperty("mail.smtp.auth", "true"); 52 //使用JavaMail发送邮件的5个步骤 53 //1、创建session 54 Session session = Session.getInstance(prop); 55 //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态 56 session.setDebug(true); 57 //2、通过session得到transport对象 58 Transport ts = session.getTransport(); 59 //3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。 60 ts.connect("smtp.163.com", "×××××××××××@163.com", "×××××××××××"); 61 //4、创建邮件 62 //创建邮件对象 63 MimeMessage message = new MimeMessage(session); 64 //指明邮件的发件人 65 message.setFrom(new InternetAddress("×××××××××××@163.com")); 66 //指明邮件的收件人 67 message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); 68 //邮件的标题 69 message.setSubject(Subject); 70 //邮件的文本内容 71 message.setContent(content, "text/html;charset=UTF-8"); 72 73 //5、发送邮件 74 ts.sendMessage(message, message.getAllRecipients()); 75 ts.close(); 76 77 Map<String, String> map = new LinkedHashMap<>(); 78 map.put("sign", "0"); 79 map.put("message", "成功"); 80 return map; 81 } 82 83 }
调用
邮件接收
标签:java,rest,session,import,mail,message,com,邮件 From: https://www.cnblogs.com/lwl80/p/17496065.html