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
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 {
spring怎么读英文怎么读
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="" />
<div>
<h2>邮件消息通知</h2>
<table id="customers">
<tr>
<th>MessageCode</th>
<th>MessageStatus</th>
<th>Cause</th>
</tr>
<tr>
<td>${(ssageCode)!""}</td>
<td>${(ssageStatus)!""}</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) {
}
public String getMessageStatus() {
return messageStatus;
}
public void setMessageStatus(String 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; plate.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 = ateMimeMessage();
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 + "-" + w() + " " + w().withNano(0) + "】");//邮件标题
Map<String, Object> model = new HashMap<>();
model.put("params", params);
Template template = Configuration().getTemplate(templateName);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
helper.setText(text, true);
System.out.ContentID());
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", 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");
props.setProperty("mail.imap.port", "143");
// 创建Session实例对象
Session session = Instance(props);
// 创建IMAP协议的Store对象
Store store = Store("imap");
// 连接邮件服务器
/
/ 获得收件箱
Folder folder = Folder("INBOX");
// 以读写模式打开收件箱
folder.open(Folder.READ_WRITE);
// 获得收件箱的邮件列表
Message[] messages = Messages();
// 打印不同状态的邮件数量
System.out.println("收件箱中共" + messages.length + "封邮件!");
System.out.println("收件箱中共" + UnreadMessageCount() + "封未读邮件!");
System.out.println("收件箱中共" + NewMessageCount() + "封新邮件!");
System.out.println("收件箱中共" + DeletedMessageCount() + "封已删除邮件!");
System.out.println("------------------------开始解析邮件----------------------------------");
int total = MessageCount();
System.out.println("-----------------您的邮箱共有邮件:" + total + " 封--------------");
// 得到收件箱⽂件夹信息,获取邮件列表
Message[] msgs = Messages();
System.out.println("\t收件箱的总邮件数:" + msgs.length);
for (int i = 0; i < total; i++) {
Message a = msgs[i];
//  获取邮箱邮件名字及时间
System.out.ReplyTo());
System.out.println("==============");
/
/                System.out.Subject() + "  接收时间:" + a.getReceivedDate().toLocaleString()+"  contentType()" +a.getContentType());            }
System.out.println("\t未读邮件数:" + UnreadMessageCount());
System.out.println("\t新邮件数:" + NewMessageCount());
System.out.println("----------------End------------------");
// 关闭资源
folder.close(false);
store.close();
}
}
ssl⽅式读取邮件
import java.security.Security;
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.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.ssl.SSLSocketFactory";
Properties props = Properties();
props.setProperty("mail.imap.host", "imap.partner.outlook");
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 = Instance(props, null);
//设置连接邮件仓库的环境
URLName url = new URLName("imap", "imap.partner.outlook", 993, null, "username", "password");
Store store = null;
Folder inbox = null;
try {
/
/得到邮件仓库并连接
store = Store(url);
//得到收件箱并抓取邮件
inbox = Folder("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 = Messages();
inbox.fetch(messages, profile);
int length = messages.length;
System.out.println("收件箱的邮件数:" + length);
System.out.println("-------------------------------------------\n");
       //遍历收件箱、垃圾箱等名称
Folder defaultFolder = DefaultFolder();
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 底层系统是否⽀持⽤户⾃定义标记,只读。
*/

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。