springboot邮件发送与接收读取(真实使用)
发送邮件
<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
邮件模板
<!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>
模板实体类
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); } }
测试发送
@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(); } }
读取邮件
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());
}
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 底层系统是否支持用户自定义标记,只读。
*/
camera_shade_message.ftl
<!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);
看完打开支付宝扫一扫领个红包吧!