实现功能:
- Java实现 QQ邮箱 给网易邮箱发送邮件
- 获取邮件信息并下载邮件的附件
前置功能
案例以QQ邮箱为例说明:
- 首先登录QQ邮箱将SMTP服务开启,会得到一个授权码。
- 创建一个Springboot项目【mail-demo】
- 引入依赖
<dependencies>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
- 工具类
package com.siro.mp.constant;
public class MailConstant {
public static final String qq_from = "xxxx";
public static final String qq_from_password = "xxxx";
public static final String wy_from = "xxxx";
public static final String wy_from_password = "xxxx";
public static final String qq_to = "xxxx";
public static final String wy_to = "xxxx";
public static String smtphost_wy = "smtp.163.com";
public static String smtphost_qq = "smtp.qq.com";
public static String protocol_smtp = "smtp";
public static final String proteocol_pop3 = "pop3";
public static final String port = "110";
public static final String servicePath = "pop.163.com";
}
- 实现代码如下
1. 发送邮件
package com.siro.mp.utils;
import com.siro.mp.constant.MailConstant;
import lombok.extern.slf4j.Slf4j;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import java.util.Properties;
@Slf4j
public class SendMailUtils {
public static void sendSimpleMail(String from, String fromPwd, String to, String subject, String content, boolean isIncludeMail, String[] fileList) {
log.info("Start .....");
Properties props = new Properties();
props.setProperty("mail.transport.protocol", MailConstant.protocol_smtp);
props.setProperty("mail.smtp.host", MailConstant.smtphost_qq);
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.port", "465");
Session session = Session.getInstance(props);
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSentDate(new Date());
message.setSubject(subject);
BodyPart bp = new MimeBodyPart();
bp.setContent(content, "text/html;charset=utf-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bp);
if (isIncludeMail) {
if (fileList != null && fileList.length > 0) {
for (int i = 0; i < fileList.length; i++) {
bp = new MimeBodyPart();
DataSource source = new FileDataSource(fileList[i]);
DataHandler dh = new DataHandler(source);
bp.setDataHandler(dh);
bp.setFileName(MimeUtility.encodeText(source.getName(),"UTF-8", "B"));
multipart.addBodyPart(bp);
}
}
}
message.setContent(multipart);
message.saveChanges();
Transport transport = session.getTransport();
transport.connect(MailConstant.smtphost_qq, 25, from, fromPwd);
transport.sendMessage(message, new Address[]{new InternetAddress(to)});
transport.close();
log.info("End .....");
} catch (Exception e) {
log.error("发送邮件失败:{}", e);
}
}
}
测试
@Test
public void sendMail() throws Exception {
String subject = "测试工具类包含邮件";
String content = "这是包含邮件的正文.....";
String[] fileList = new String[2];
fileList[0] = "C:\\Users\\GH\\Desktop\\狗子.docx";
fileList[1] = "C:\\Users\\GH\\Desktop\\测试流程.docx";
SendMailUtils.sendSimpleMail(MailConstant.qq_from, MailConstant.qq_from_password,
MailConstant.wy_to, subject, content, true, fileList);
}
2. 获取邮件信息并下载对应附件
package com.siro.mp.utils;
import com.siro.mp.constant.MailConstant;
import lombok.extern.slf4j.Slf4j;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
@Slf4j
public class ReceiveEmailUtils {
public static void receive(String emailAddress, String password, String projectName) throws Exception {
Properties props = new Properties();
props.setProperty("mail.store.protocol", MailConstant.proteocol_pop3);
props.setProperty("mail.pop3.port", MailConstant.port);
props.setProperty("mail.pop3.host", MailConstant.servicePath);
Session session = Session.getInstance(props);
Store store = session.getStore(MailConstant.proteocol_pop3);
store.connect(emailAddress, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
log.warn("邮件总数: {}", folder.getMessageCount());
SearchTerm st = new SubjectTerm(projectName);
Message[] messages = folder.search(st);
parseMessage(messages);
folder.close(true);
store.close();
}
public static void parseMessage(Message... messages) throws MessagingException, IOException {
if (messages == null || messages.length < 1) {
throw new MessagingException("未找到要解析的邮件!");
}
for (int i = 0, count = messages.length; i < count; i++) {
MimeMessage msg = (MimeMessage) messages[i];
log.info("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
log.warn("主题: {}", getSubject(msg));
log.warn("发件人: {}", getFrom(msg));
log.warn("收件人:{}", getReceiveAddress(msg, null));
log.warn("发送时间:{}", getSentDate(msg, null));
log.warn("是否已读:{}", isSeen(msg));
log.warn("邮件优先级:{}", getPriority(msg));
log.warn("是否需要回执:{}", isReplySign(msg));
log.warn("邮件大小:{}", msg.getSize() * 1024 + "kb");
boolean isContainerAttachment = isContainAttachment(msg);
log.warn("是否包含附件:{}", isContainerAttachment);
if (isContainerAttachment) {
saveAttachment(msg, "D:\\" + msg.getSubject() + "_" + i + "_");
}
StringBuffer content = new StringBuffer(30);
getMailTextContent(msg, content);
log.warn("邮件正文:{}", content);
log.info("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
System.out.println();
}
}
public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
return MimeUtility.decodeText(msg.getSubject());
}
public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
String from = "";
Address[] froms = msg.getFrom();
if (froms.length < 1) {
throw new MessagingException("没有发件人!");
}
InternetAddress address = (InternetAddress) froms[0];
String person = address.getPersonal();
if (person != null) {
person = MimeUtility.decodeText(person) + " ";
} else {
person = "";
}
from = person + "<" + address.getAddress() + ">";
return from;
}
public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
StringBuffer receiveAddress = new StringBuffer();
Address[] addresss = null;
if (type == null) {
addresss = msg.getAllRecipients();
} else {
addresss = msg.getRecipients(type);
}
if (addresss == null || addresss.length < 1) {
throw new MessagingException("没有收件人!");
}
for (Address address : addresss) {
InternetAddress internetAddress = (InternetAddress) address;
receiveAddress.append(internetAddress.toUnicodeString()).append(",");
}
receiveAddress.deleteCharAt(receiveAddress.length() - 1);
return receiveAddress.toString();
}
public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
Date receivedDate = msg.getSentDate();
if (receivedDate == null) {
return "";
}
if (pattern == null || "".equals(pattern)) {
pattern = "yyyy年MM月dd日 E HH:mm ";
}
return new SimpleDateFormat(pattern).format(receivedDate);
}
public static boolean isSeen(MimeMessage msg) throws MessagingException {
return msg.getFlags().contains(Flags.Flag.SEEN);
}
public static String getPriority(MimeMessage msg) throws MessagingException {
String priority = "普通";
String[] headers = msg.getHeader("X-Priority");
if (headers != null) {
String headerPriority = headers[0];
if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1) {
priority = "紧急";
} else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1) {
priority = "低";
} else {
priority = "普通";
}
}
return priority;
}
public static boolean isReplySign(MimeMessage msg) throws MessagingException {
boolean replySign = false;
String[] headers = msg.getHeader("Disposition-Notification-To");
if (headers != null) {
replySign = true;
}
return replySign;
}
public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
boolean flag = false;
if (part.isMimeType("multipart/*")) {
MimeMultipart multipart = (MimeMultipart) part.getContent();
int partCount = multipart.getCount();
for (int i = 0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
String disp = bodyPart.getDisposition();
if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
flag = true;
} else if (bodyPart.isMimeType("multipart/*")) {
flag = isContainAttachment(bodyPart);
} else {
String contentType = bodyPart.getContentType();
if (contentType.indexOf("application") != -1) {
flag = true;
}
if (contentType.indexOf("name") != -1) {
flag = true;
}
}
if (flag) {
break;
}
}
} else if (part.isMimeType("message/rfc822")) {
flag = isContainAttachment((Part) part.getContent());
}
return flag;
}
public static String decodeText(String encodeText) throws UnsupportedEncodingException {
if (encodeText == null || "".equals(encodeText)) {
return "";
} else {
return MimeUtility.decodeText(encodeText);
}
}
public static void saveAttachment(Part part, String destDir) throws MessagingException, IOException {
if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int partCount = multipart.getCount();
for (int i = 0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
String disp = bodyPart.getDisposition();
if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
InputStream is = bodyPart.getInputStream();
saveFile(is, destDir, decodeText(bodyPart.getFileName()));
} else if (bodyPart.isMimeType("multipart/*")) {
saveAttachment(bodyPart, destDir);
} else {
String contentType = bodyPart.getContentType();
if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
}
}
}
} else if (part.isMimeType("message/rfc822")) {
saveAttachment((Part) part.getContent(), destDir);
}
}
private static void saveFile(InputStream is, String destDir, String fileName) throws FileNotFoundException, IOException {
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(new File(destDir + fileName)));
int len = -1;
while ((len = bis.read()) != -1) {
bos.write(len);
bos.flush();
}
bos.close();
bis.close();
}
public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
if (part.isMimeType("text/*") && !isContainTextAttach) {
content.append(part.getContent().toString());
} else if (part.isMimeType("message/rfc822")) {
getMailTextContent((Part) part.getContent(), content);
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int partCount = multipart.getCount();
for (int i = 0; i < partCount; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
getMailTextContent(bodyPart, content);
}
}
}
public static void deleteMessage(Message... messages) throws MessagingException, IOException {
if (messages == null || messages.length < 1) {
throw new MessagingException("未找到要解析的邮件!");
}
for (int i = 0, count = messages.length; i < count; i++) {
Message message = messages[i];
String subject = message.getSubject();
message.setFlag(Flags.Flag.DELETED, true);
System.out.println("Marked DELETE for message: " + subject);
}
}
}
测试
@Test
public void sendReceiveEmail() throws Exception {
ReceiveEmailUtils.receive(MailConstant.wy_from, MailConstant.wy_from_password, "测试工具类发送简单邮件");
}
如果有收获! 希望老铁们来个三连,点赞、收藏、转发。
创作不易,别忘点个赞,可以让更多的人看到这篇文章,顺便鼓励我写出更好的博客
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)