發送郵件 css
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
spring: mail: port: 25 username: **** password: **** protocol: smtp default-encoding: utf-8 host: smtp.partner.outlook.cn properties: mail: smtp: auth: true starttls: enable: true required: true
郵件模板html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>消息通知</title> </head> <style type="text/css"> table { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; width: 100%; border-collapse: collapse; } td, th { font-size: 1em; border: 1px solid #5B4A42; padding: 3px 7px 2px 7px; } th { font-size: 1.1em; text-align: center; padding-top: 5px; padding-bottom: 4px; background-color: #24A9E1; color: #ffffff; } </style> <body> <img src="" alt="" style="display: inline-block;width: 0;height: 0"/> <div> <h2>郵件消息通知</h2> <table id="customers"> <tr> <th>MessageCode</th> <th>MessageStatus</th> <th>Cause</th> </tr> <tr> <td>${(params.messageCode)!""}</td> <td>${(params.messageStatus)!""}</td> <td>${(params.cause)!""}</td> </tr> </table> </div> </body> </html>
模板實體類java
public class MailMessage { private String messageCode; private String messageStatus; private String cause; public String getMessageCode() { return messageCode; } public void setMessageCode(String messageCode) { this.messageCode = messageCode; } public String getMessageStatus() { return messageStatus; } public void setMessageStatus(String messageStatus) { this.messageStatus = messageStatus; } public String getCause() { return cause; } public void setCause(String cause) { this.cause = cause; } }
import java.time.LocalDate; import java.time.LocalTime; import java.util.HashMap; import java.util.Map; import javax.mail.MessagingException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import freemarker.template.Template; @Service public class MailService { //郵件的發送者 @Value("${spring.mail.username}") private String from; //注入MailSender @Autowired private JavaMailSender mailSender; //發送郵件的模板引擎 @Autowired private FreeMarkerConfigurer configurer; /** * @param params 發送郵件的主題對象 object * @param title 郵件標題 * @param templateName 模板名稱 * @param to 收件人地址 * @param receipt 是否須要回執 * @throws MessagingException * @throws Exception */ public void sendMessageMail(Object params, String title, String templateName, String to, boolean receipt) throws Exception{ MimeMessage mimeMessage = mailSender.createMimeMessage(); if(receipt) { mimeMessage.setHeader("Disposition-Notification-To", "1"); } mimeMessage.setContentID(System.currentTimeMillis()+""); MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setFrom(from); helper.setTo(InternetAddress.parse(to)); helper.setSubject("【" + title + "-" + LocalDate.now() + " " + LocalTime.now().withNano(0) + "】");//郵件標題 Map<String, Object> model = new HashMap<>(); model.put("params", params); Template template = configurer.getConfiguration().getTemplate(templateName); String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); helper.setText(text, true); System.out.println(mimeMessage.getContentID()); mailSender.send(mimeMessage); } }
測試發送web
@RequestMapping(value = "/sendMessage", method = RequestMethod.GET) public void sendMailMessage() { MailMessage message = new MailMessage(); message.setMessageCode("MissingParameter"); message.setMessageStatus("Failed"); message.setCause("缺乏參數,請確認"); try { mailService.sendMessageMail(message, "測試消息通知", "message.ftl", "aaaaa@qq.com", true); } catch (Exception e) { e.printStackTrace(); } }
讀取郵件spring
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeUtility; import com.sun.mail.imap.IMAPMessage; public class ReciveIMAPmail { public static void main(String[] args) throws Exception { // 準備鏈接服務器的會話信息 Properties props = new Properties(); props.setProperty("mail.store.protocol", "imap"); props.setProperty("mail.imap.host", "imap.163.com"); props.setProperty("mail.imap.port", "143"); // 建立Session實例對象 Session session = Session.getInstance(props); // 建立IMAP協議的Store對象 Store store = session.getStore("imap"); // 鏈接郵件服務器 store.connect("username***", "password***"); // 得到收件箱 Folder folder = store.getFolder("INBOX"); // 以讀寫模式打開收件箱 folder.open(Folder.READ_WRITE); // 得到收件箱的郵件列表 Message[] messages = folder.getMessages(); // 打印不一樣狀態的郵件數量 System.out.println("收件箱中共" + messages.length + "封郵件!"); System.out.println("收件箱中共" + folder.getUnreadMessageCount() + "封未讀郵件!"); System.out.println("收件箱中共" + folder.getNewMessageCount() + "封新郵件!"); System.out.println("收件箱中共" + folder.getDeletedMessageCount() + "封已刪除郵件!"); System.out.println("------------------------開始解析郵件----------------------------------"); int total = folder.getMessageCount(); System.out.println("-----------------您的郵箱共有郵件:" + total + " 封--------------"); // 獲得收件箱文件夾信息,獲取郵件列表 Message[] msgs = folder.getMessages(); System.out.println("\t收件箱的總郵件數:" + msgs.length); for (int i = 0; i < total; i++) { Message a = msgs[i]; // 獲取郵箱郵件名字及時間 System.out.println(a.getReplyTo()); System.out.println("=============="); // System.out.println(a.getSubject() + " 接收時間:" + a.getReceivedDate().toLocaleString()+" contentType()" +a.getContentType()); } System.out.println("\t未讀郵件數:" + folder.getUnreadMessageCount()); System.out.println("\t新郵件數:" + folder.getNewMessageCount()); System.out.println("----------------End------------------"); // 關閉資源 folder.close(false); store.close(); } }
ssl方式讀取郵件服務器
import java.security.Security; import java.text.SimpleDateFormat; import java.util.Properties; import javax.mail.FetchProfile; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; import javax.mail.URLName; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeUtility; import javax.mail.search.FlagTerm; //查看收件箱郵件 public class ReadMailUtil { public static void main(String[] args) { //設置SSL鏈接、郵件環境 Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.imap.host", "imap.partner.outlook.cn"); props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY); props.setProperty("mail.imap.socketFactory.fallback", "false"); props.setProperty("mail.imap.port", "993"); props.setProperty("mail.imap.socketFactory.port", "993"); props.setProperty("mail.imap.auth", "true"); //創建郵件會話 Session session = Session.getInstance(props, null); //設置鏈接郵件倉庫的環境 URLName url = new URLName("imap", "imap.partner.outlook.cn", 993, null, "username", "password"); Store store = null; Folder inbox = null; try { //獲得郵件倉庫並鏈接 store = session.getStore(url); store.connect(); //獲得收件箱並抓取郵件 inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.ENVELOPE); //false表明未讀,true表明已讀 FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); //根據設置好的條件獲取message Message[] messages = inbox.search(ft); // Message[] messages = inbox.getMessages(); inbox.fetch(messages, profile); int length = messages.length; System.out.println("收件箱的郵件數:" + length); System.out.println("-------------------------------------------\n");
//遍歷收件箱、垃圾箱等名稱
Folder defaultFolder = store.getDefaultFolder();
Folder[] folders = defaultFolder.list();
for (int i = 0; i < folders.length; i++) {
System.out.println("名稱:"+folders[i].getName());
}session
for (int i = 0; i < length; i++) { String from = MimeUtility.decodeText(messages[i].getFrom()[0].toString()); InternetAddress ia = new InternetAddress(from); System.out.println("發件人:" + ia.getPersonal() + '(' + ia.getAddress() + ')'); System.out.println("主題:" + messages[i].getSubject()); System.out.println("郵件發送時間:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(messages[i].getSentDate())); System.out.println("-------------------------------------------\n"); messages[i].setFlag(Flags.Flag.SEEN, true); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(inbox != null) { inbox.close(false); } } catch (MessagingException e) { e.printStackTrace(); } try { if(store != null) { store.close(); } } catch (MessagingException e) { e.printStackTrace(); } } } }
/**
* Flag 類型列舉以下
* Flags.Flag.ANSWERED 郵件回覆標記,標識郵件是否已回覆。
* Flags.Flag.DELETED 郵件刪除標記,標識郵件是否須要刪除。
* Flags.Flag.DRAFT 草稿郵件標記,標識郵件是否爲草稿。
* Flags.Flag.FLAGGED 表示郵件是否爲回收站中的郵件。
* Flags.Flag.RECENT 新郵件標記,表示郵件是否爲新郵件。
* Flags.Flag.SEEN 郵件閱讀標記,標識郵件是否已被閱讀。
* Flags.Flag.USER 底層系統是否支持用戶自定義標記,只讀。
*/app
camera_shade_message.ftlsocket
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>監控通知</title> </head> <style type="text/css"> table { font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; width: 100%; border-collapse: collapse; } td, th { font-size: 1em; border: 1px solid #5B4A42; padding: 3px 7px 2px 7px; } th { font-size: 1.1em; text-align: center; padding-top: 5px; padding-bottom: 4px; background-color: #24A9E1; color: #ffffff; } </style> <body> <p>${userName!""},您好!</p> <p> 如下爲${cusnames!""},${dataCycle!""} 明細: </p> </br> <div> <table id="customers"> <tr> <th>車牌號</th> <th>設備號</th> <th>監控週期</th> <th>客戶名稱</th> </tr> <#list datas as item> <tr> <td>${item.carnum!""}</td> <td>${item.gpsno!""}</td> <td>${item.dataCycle!""}</td> <td>${item.cusname!""}</td> </tr> </#list> </table> </div> <p>請查收</p> </body> </html>
Map<String, Object> map = new HashMap<>(); map.put("datas", list);
map.put("controllerName", mailNoticeReq.getControllerName()); mailService.sendMessageMail(map, mailNoticeDetail.getTitle(), "camera_shade_message.ftl", mailNoticeDetail.getReceiver(), true);