<dependencies>
<dependency>
<groupId>com.sun.mailgroupId>
<artifactId>javax.mailartifactId>
<version>1.6.2version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.2version>
<scope>providedscope>
dependency>
dependencies>
package com.match.entry;
import lombok.Data;
import java.util.Date;
import java.util.List;
@Data
public class Mail {
private String userName;//用户名
private String password;//密码或授权码
private String host;//端口
private String protocol;//协议栈
private int port; //端口
private boolean SSL;//是否使用ssl
private boolean auth;//是否验证登录
private String socketFactory; //socket
private String fromEmail;//邮件发送者
private String recipient;//邮箱接收者
private String subject;//邮件主题
private Date date;//邮件日期
private List<MailAttach> mailContentList;//邮件正文
private List<MailAttach> mailAttachList;//邮件附件
}
package com.match.entry;
import lombok.Data;
@Data
public class MailAttach {
private String fileName;//附件名
private String content;//文字
private boolean pic;//是否是图片,true:是 false:否
private boolean excel;//是否是excel文件,true:是 false:否
}
package com.match;
import com.match.entry.Mail;
import com.match.entry.MailAttach;
import com.match.util.SendMailUtil;
import java.util.ArrayList;
import java.util.List;
public class SendMailDemo {
public static void main(String[] args) {
Mail mail = new Mail();
mail.setUserName("[email protected]");//用户名
mail.setPassword("xxxxxx");//授权码或密码
mail.setHost("smtp.aliyun.com");
mail.setProtocol("smtp");
mail.setAuth(true);
mail.setSocketFactory("javax.net.ssl.SSLSocketFactory");
mail.setPort(465);
mail.setFromEmail("[email protected]");//发送者
mail.setRecipient("[email protected]");//接收者
mail.setSubject("带附件和带图片的的邮件");
List<MailAttach> list = new ArrayList<>();
List<MailAttach> list1 = new ArrayList<>();
MailAttach attach1 = new MailAttach();
attach1.setContent("收到请回复,谢谢
");
attach1.setFileName("1.jpg");
attach1.setPic(true);
MailAttach attach2 = new MailAttach();
attach2.setFileName("1.zip");
list.add(attach1);
list.add(attach2);
list1.add(attach1);
mail.setMailAttachList(list);
mail.setMailContentList(list1);
SendMailUtil.sendMail(mail);
}
}
package com.match.util;
import com.match.entry.Mail;
import com.match.entry.MailAttach;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
public class SendMailUtil {
private final static String RESOURCE_URL = "src/main/resources/";
/**
* @param mail
* @throws Exception
*/
public static void sendMail(Mail mail) {
//使用JavaMail发送邮件的5个步骤
//1、创建session
Session session = MailSessionUtil.createSessionUtil(mail);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
// session.setDebug(false);
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = null;
try {
ts = session.getTransport();
//3、连上邮件服务器
ts.connect();
//4、创建邮件
Message message = createMixedMail(session, mail);
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
} catch (Exception e) {
try {
System.out.println(MimeUtility.encodeText(e.getMessage()));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
try {
if (ts != null) {
ts.close();
}
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @return
* @throws Exception
* @Method: createMixedMail
* @Description: 生成一封带附件和带图片的邮件
*/
private static MimeMessage createMixedMail(Session session, Mail mail) throws Exception {
//创建邮件
MimeMessage message = new MimeMessage(session);
//设置邮件的基本信息
message.setFrom(new InternetAddress(mail.getFromEmail()));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
message.setSubject(mail.getSubject());
//代表正文的bodypart
MimeBodyPart content = new MimeBodyPart();
//设置正文
MimeMultipart mp1 = setContent(mail);
//描述关系:正文和附件
MimeMultipart mp2 = setAttach(mail);
//添加正文
if(mp1 != null) {
content.setContent(mp1);
mp2.addBodyPart(content);
mp2.setSubType("mixed");
}
message.setContent(mp2);
message.saveChanges();
// message.writeTo(new FileOutputStream("E:\\MixedMail.eml"));
//返回创建好的的邮件
return message;
}
/**
* 设置邮件正文
* @param mail
* @return
* @throws MessagingException
*/
private static MimeMultipart setContent(Mail mail) throws MessagingException {
//正文内容
if (mail.getMailContentList() != null && !mail.getMailContentList().isEmpty()) {
//描述关系:正文和图片
MimeMultipart mp1 = new MimeMultipart();
mp1.setSubType("related");
for (MailAttach attach : mail.getMailContentList()) {
if (attach.getContent() != null) {
MimeBodyPart bodyPart = new MimeBodyPart();
//设置内容时需要设置图片链接
bodyPart.setContent(attach.getContent() + "", "text/html;charset=UTF-8");
mp1.addBodyPart(bodyPart);
}
if (attach.getFileName() != null) {
//设置图片附件
MimeBodyPart bodyPart = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource(RESOURCE_URL + attach.getFileName()));
bodyPart.setDataHandler(dh);
if (attach.isPic()) {
bodyPart.setContentID(attach.getFileName());
}
mp1.addBodyPart(bodyPart);
}
}
return mp1;
}
return null;
}
/**
* 设置附件
* @param mail
* @return
* @throws MessagingException
* @throws UnsupportedEncodingException
*/
private static MimeMultipart setAttach(Mail mail) throws MessagingException, UnsupportedEncodingException {
MimeMultipart mp2 = new MimeMultipart();
//添加附件
if (mail.getMailAttachList() != null && !mail.getMailAttachList().isEmpty()) {
for (MailAttach mailAttach : mail.getMailAttachList()) {
MimeBodyPart attach = new MimeBodyPart();
if (mailAttach.getFileName() != null) {
//附件
DataHandler dh = new DataHandler(new FileDataSource(RESOURCE_URL + mailAttach.getFileName()));
attach.setDataHandler(dh);
attach.setFileName(MimeUtility.encodeText(dh.getName()));
}
mp2.addBodyPart(attach);
}
}
return mp2;
}
}
package com.match.util;
import com.match.entry.Mail;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.util.Properties;
public class MailSessionUtil {
/**
* 生成mail的session
* @param mail
* @return
*/
public static Session createSessionUtil(Mail mail){
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
// 密码验证
return new PasswordAuthentication(mail.getUserName(), mail.getPassword());
}
};
/*
*Properties是一个属性对象,用来创建Session对象
*/
Properties properties = new Properties();
// properties.put("mail.pop3.ssl.enable", mail.isSSL());
// properties.put("mail.pop3.host", mail.getHost());
// properties.put("mail.pop3.port", mail.getPort());
properties.setProperty("mail.host", mail.getHost());
properties.setProperty("mail.transport.protocol", mail.getProtocol());
properties.setProperty("mail.smtp.auth", mail.isAuth() + "");
properties.setProperty("mail.smtp.socketFactory.class", mail.getSocketFactory());
properties.setProperty("mail.smtp.port", mail.getPort() + "");
properties.setProperty("mail.smtp.socketFactory.port", mail.getPort() + "");
/*
*Session类定义了一个基本的邮件对话。
*/
return Session.getInstance(properties, auth);
}
}
package com.match;
import com.match.entry.Mail;
import com.match.util.ReceiveMailUtil;
public class ReceiveMailDemo {
public static void main(String[] args) {
Mail mail = new Mail();
mail.setUserName("[email protected]");//用户名
mail.setPassword("xxxxxxxxxxxx");//授权码或密码
// mail.setPort(995);//端口
// mail.setHost("pop.qq.com");//QQ邮箱的pop3服务器
// mail.setProtocol("pop3");//使用pop3协议
mail.setPort(993);//端口
mail.setHost("imap.qq.com");//QQ邮箱的pop3服务器
mail.setProtocol("imap");//使用pop3协议
mail.setSSL(true);//使用SSL加密
mail.setAuth(true);
mail.setSocketFactory("javax.net.ssl.SSLSocketFactory");
//read 本地已经读过的邮件数,pop3与imap均不支持对邮件操作
ReceiveMailUtil.recipient(mail,1176);
}
}
package com.match.util;
import com.match.entry.Mail;
import com.match.entry.MailAttach;
import javax.mail.*;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class ReceiveMailUtil {
private final static String FILE_URL = "E:\\";
private final static String excel2003L = ".xls"; //2003- 版本的excel
private final static String excel2007U = ".xlsx"; //2007+ 版本的excel
/**
* @param mail
* @param read 已经读到的邮件数目
* @return
*/
public static List<Mail> recipient(Mail mail, Integer read) {
Session session = MailSessionUtil.createSessionUtil(mail);
session.setDebug(false);
/*
* Store类实现特定邮件协议上的读、写、监视、查找等操作。
* 通过Store类可以访问Folder类。
* Folder类用于分级组织邮件,并提供照Message格式访问email的能力。
*/
Store store = null;
Folder folder = null;
List<Mail> receiveList = new ArrayList<>();
try {
store = session.getStore(mail.getProtocol());
store.connect(mail.getUserName(), mail.getPassword());
folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);//打开收件箱
// folder.open(Folder.READ_ONLY);//打开收件箱
// 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
int unread = folder.getUnreadMessageCount();
System.out.println("未读邮件数: " + unread);
// // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
System.out.println("新邮件: " + folder.getNewMessageCount());
// // 获得收件箱中的邮件总数
System.out.println("邮件总数: " + folder.getMessageCount());
int size = folder.getMessageCount();//获取邮件数目
//获取邮件
for (int i = read + 1; i <= size; i++) {
Message message = folder.getMessage(i);
//解析邮件内容
String from = message.getFrom()[0].toString();
String subject = message.getSubject();
Date date = message.getSentDate();
Mail receiveMail = new Mail();
if (!(message.getContent() instanceof String)) {
parseMultipart((Multipart) message.getContent(), receiveMail);
}
receiveMail.setFromEmail(getSubChinese(from));
receiveMail.setSubject(subject);
receiveMail.setDate(date);
receiveList.add(receiveMail);
}
System.out.println("接收成功!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (folder != null) {
folder.close(false);
}
if (store != null) {
store.close();
}
} catch (Exception e) {
System.out.println("接收失败!");
e.printStackTrace();
}
}
System.out.println("接收完毕!");
return receiveList;
}
/**
* 对复杂邮件的解析
*
* @param multipart
* @param receiveMail
* @throws MessagingException
* @throws IOException
*/
private static Mail parseMultipart(Multipart multipart, Mail receiveMail) throws MessagingException, IOException {
List<MailAttach> contentList = new ArrayList<>();
List<MailAttach> attachList = new ArrayList<>();
int count = multipart.getCount();
// System.out.println("count = " + count);
for (int idx = 0; idx < count; idx++) {
BodyPart bodyPart = multipart.getBodyPart(idx);
MailAttach attach = new MailAttach();
// System.out.println(bodyPart.getContentType());
if (bodyPart.isMimeType("text/plain")) {
attach.setContent(bodyPart.getContent().toString());
contentList.add(attach);
// System.out.println("plain................." + bodyPart.getContent());
} else if (bodyPart.isMimeType("text/html")) {
attach.setContent(bodyPart.getContent().toString());
contentList.add(attach);
// System.out.println("html..................." + bodyPart.getContent());
} else if (bodyPart.isMimeType("multipart/*")) {
Multipart mpart = (Multipart) bodyPart.getContent();
parseMultipart(mpart, receiveMail);
} else if (bodyPart.isMimeType("application/octet-stream")) {
String disposition = bodyPart.getDisposition();
// System.out.println(disposition);
if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {
saveFile(bodyPart, attach);
attachList.add(attach);
}
} else if (bodyPart.isMimeType("image/jpeg")) {
saveFile(bodyPart, attach);
attach.setPic(true);
attachList.add(attach);
}
}
if (!contentList.isEmpty()) {
receiveMail.setMailContentList(contentList);
}
if (!attachList.isEmpty()) {
receiveMail.setMailAttachList(attachList);
}
return receiveMail;
}
/**
* 保存文件到本地
*
* @param bodyPart
* @param attach
* @throws MessagingException
* @throws IOException
*/
private static void saveFile(BodyPart bodyPart, MailAttach attach) throws MessagingException, IOException {
String fileName = getSubChinese(bodyPart.getFileName());
boolean flag = isExcelFile(fileName);
if (flag) {
fileName = newFileName(fileName);
InputStream is = bodyPart.getInputStream();
String fileUrl = FILE_URL + fileName;
copy(is, new FileOutputStream(fileUrl));
attach.setFileName(fileUrl);
} else {
attach.setFileName(fileName);
}
attach.setExcel(flag);
}
/**
* 转码
*
* @param str
* @return
*/
private static String getSubChinese(String str) {
String rtnStr;
try {
if(str==null)
return null;
rtnStr = new String(str.getBytes(StandardCharsets.ISO_8859_1));
if (rtnStr.contains("=")) {
rtnStr = MimeUtility.decodeText(str);
}
} catch (UnsupportedEncodingException e) {
rtnStr = str;
e.printStackTrace();
}
// System.out.println(rtnStr);
return rtnStr;
}
/**
* 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载
*
* @param is
* @param os
* @throws IOException
*/
private static void copy(InputStream is, OutputStream os) throws IOException {
byte[] bytes = new byte[1024];
int len;
while ((len = is.read(bytes)) != -1) {
os.write(bytes, 0, len);
}
if (os != null)
os.close();
is.close();
}
/**
* 判断是否为excel
*
* @param fileName
*/
private static boolean isExcelFile(String fileName) {
if(fileName==null)
return false;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if (excel2003L.equals(fileType) || excel2007U.equals(fileType)) {
return true;
}
return false;
}
/**
* 保存文件增加时间戳表示
*
* @param fileName
* @return
*/
private static String newFileName(String fileName) {
int index = fileName.lastIndexOf(".");
String fileType = fileName.substring(index);
fileName = fileName.substring(0, index);
fileName = fileName + Calendar.getInstance().getTimeInMillis() + fileType;
return fileName;
}
}
gitee代码地址:https://gitee.com/leftbehindmatches/javamail-demo.git