admin管理员组文章数量:1559106
1,邮箱协议设置
1,邮箱的读取需要先配置邮箱协议,主要有两种,第一个是pop3协议,第二个是imap协议,两者之间的区别在于imap是可以区分邮件是否已读取,而pop可以通过searchterm查询条件过滤邮件,关于两者的配置qq邮箱可以直接点下方qq官方链接设置,
https://service.mail.qq/cgi-bin/help?subtype=1&&id=28&&no=1001256
2,腾讯企业邮箱到不需要配置,因为他默认是已经开启了pop3、imap协议的,可以直接通过账号以及密码登录连接的,但是你也可以配置专用密码进行连接,方法如下图
1,开启前
2,开启后
2,java代码实现
1,两者之前的代码实际上都差不多,区别在于邮箱服务器的配置
imap
1,qq邮箱服务器:imap.qq.com
2,腾讯企业邮箱服务器:imap.exmail.qq.com
pop
1,qq邮箱服务器:pop.qq.com
2,腾讯企业邮箱服务器:pop.exmail.qq.com
//涉及pom jar
<dependency>
<groupid>javax.mail</groupid>
<artifactid>mail</artifactid>
<version>1.4.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupid>org.apache.commons</groupid>
<artifactid>commons-lang3</artifactid>
<version>3.12.0</version>
</dependency>
package com.example.demo.utils;
import org.apache.commons.lang3.stringutils;
import javax.mail.*;
import javax.mail.internet.internetaddress;
import javax.mail.internet.mimemessage;
import javax.mail.internet.mimemultipart;
import javax.mail.internet.mimeutility;
import java.io.*;
import java.text.simpledateformat;
import java.util.date;
import java.util.properties;
/**
* @author:deng
* @date: 2021-04-14 17:30
* @remark: 腾讯邮件读取
*/
public class emailutils {
public static void reademail() {
properties props = new properties();
props.put("mail.imap.host", "imap.exmail.qq");//qq邮箱为:imap.qq
props.put("mail.imap.auth", "true");
props.setproperty("mail.store.protocol", "imap");
props.put("mail.imap.starttls.enable", "true");
session session = session.getinstance(props);
try {
store store = session.getstore();
//企业邮箱如果开启了安全登录,密码需要使用专用密码,没有开启使用账号密码即可
store.connect("imap.exmail.qq", "xxx@xx", "xxxxx");
//store.connect("imap.qq", "xxx@xx", "授权码");//qq邮箱需要设置授权码
folder folder = store.getfolder("inbox");
//邮箱打开方式
folder.open(folder.read_write);
//收取未读邮件
message[] messages = folder.getmessages(folder.getmessagecount() - folder.getunreadmessagecount() 1, folder.getmessagecount());
system.out.println("邮件总数: " folder.getmessagecount());
//解析的邮件的方法,就粘贴了网上的了,有需要的直接点击参考文档的链接
parsefilemessage(messages);
folder.setflags(messages, new flags(flags.flag.seen), true);
}catch (exception e){
system.out.println("异常: " e);
}
}
public static void reademailpop() throws exception {
properties props = new properties();
props.put("mail.pop3.host", "pop.exmail.qq");
props.put("mail.pop3.auth", "true");
props.setproperty("mail.store.protocol", "pop3");
props.put("mail.pop3.starttls.enable", "true");
session session = session.getinstance(props);
store store = session.getstore("pop3");
store.connect("pop.exmail.qq", "xxx@xxx", "xxxx");
folder folder = store.getfolder("inbox");
//邮箱打开方式
folder.open(folder.read_write);
//昨天零点时间
calendar cal = calendar.getinstance();
cal.add(calendar.date, -1);
cal.set(calendar.hour_of_day, 0);
cal.set(calendar.minute, 0);
cal.set(calendar.second, 0);
cal.set(calendar.millisecond, 0);
date mondaydate = cal.gettime();
//昨天零点到当前时间的邮件
searchterm comparisontermge = new sentdateterm(comparisonterm.ge, mondaydate);
searchterm comparisontermle = new sentdateterm(comparisonterm.le, new date());
searchterm comparisonandterm = new andterm(comparisontermge, comparisontermle);
//条件查询只能通过pop协议的方式才生效
message[] messages = folder.search(comparisonandterm);
// message[] messages = folder.getmessages();
system.out.println("读取的邮件总数: " messages.length);
parsefilemessage(messages);
// folder.setflags(messages, new flags(flags.flag.seen), true);
system.out.println("邮件解析任务执行完毕");
}
public static void parsefilemessage(message... messages) throws exception {
if (messages == null || messages.length < 1){
system.out.println("没有可读取邮件");
return;
}
// 解析读取到的邮件
for (message message : messages) {
mimemessage msg = (mimemessage) message;
system.out.println("------------------解析第" msg.getmessagenumber() "封邮件-------------------- ");
system.out.println("主题: " mimeutility.decodetext(msg.getsubject()));
system.out.println("发件人: " getfrom(msg));
system.out.println("收件人:" getreceiveaddress(msg, null));
system.out.println("发送时间:" getsentdate(msg, null));
system.out.println("是否已读:" isseen(msg));
system.out.println("邮件优先级:" getpriority(msg));
system.out.println("是否需要回执:" isreplysign(msg));
system.out.println("邮件大小:" msg.getsize() * 1024 "kb");
stringbuffer content = new stringbuffer(30);
getmailtextcontent(msg, content);
system.out.println("邮件正文:" (content.length() > 100 ? content.substring(0,100) "..." : content));
system.out.println();
boolean iscontainerattachment = iscontainattachment(msg);
system.out.println("是否包含附件:" iscontainerattachment);
if (iscontainerattachment) {
saveattachment(msg, "d:\\data\\emailfile\\", msg.getfilename()); //保存附件
}
system.out.println("------------------第" msg.getmessagenumber() "封邮件解析结束-------------------- ");
}
}
/**
* 获得邮件发件人
* @param msg 邮件内容
* @return 姓名
* @throws messagingexception
* @throws unsupportedencodingexception
*/
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;
}
/**
* 获得邮件发送时间
* @param msg 邮件内容
* @return yyyy年mm月dd日 星期x hh:mm
* @throws messagingexception
*/
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);
}
/**
* 判断邮件是否已读
* @param msg 邮件内容
* @return 如果邮件已读返回true,否则返回false
* @throws messagingexception
*/
public static boolean isseen(mimemessage msg) throws messagingexception {
return msg.getflags().contains(flags.flag.seen);
}
/**
* 判断邮件是否需要阅读回执
* @param msg 邮件内容
* @return 需要回执返回true,否则返回false
* @throws messagingexception
*/
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;
}
/**
* 获得邮件的优先级
* @param msg 邮件内容
* @return 1(high):紧急 3:普通(normal) 5:低(low)
* @throws messagingexception
*/
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.contains("1") || headerpriority.contains("high"))
priority = "紧急";
else if (headerpriority.contains("5") || headerpriority.contains("low"))
priority = "低";
else
priority = "普通";
}
return priority;
}
/**
* 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
* message.recipienttype.to 收件人
* message.recipienttype.cc 抄送
* message.recipienttype.bcc 密送
* @param msg 邮件内容
* @param type 收件人类型
* @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
* @throws messagingexception
*/
public static string getreceiveaddress(mimemessage msg, message.recipienttype type) throws messagingexception {
stringbuilder receiveaddress = new stringbuilder();
address[] addresss;
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();
}
/**
* 判断邮件中是否包含附件
*
* @return 存在附件返回true,不存在返回false
*/
public static boolean iscontainattachment(part part) throws exception {
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.contains("application")) {
flag = true;
}
if (contenttype.contains("name")) {
flag = true;
}
}
if (flag) break;
}
} else if (part.ismimetype("message/rfc822")) {
flag = iscontainattachment((part) part.getcontent());
}
return flag;
}
/**
* 保存文件
*
* @param destdir 文件目录
* @param filename 文件名
* @throws exception 异常
*/
public static void saveattachment(part part, string destdir, string filename) throws exception {
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();
string decodename = decodetext(bodypart.getfilename());
decodename = stringutils.isempty(decodename) ? filename : decodename;
if (disp != null && (disp.equalsignorecase(part.attachment) || disp.equalsignorecase(part.inline))) {
savefile(bodypart.getinputstream(), destdir, decodename);
} else if (bodypart.ismimetype("multipart/*")) {
saveattachment(bodypart, destdir, filename);
} else {
string contenttype = bodypart.getcontenttype();
if (contenttype.contains("name") || contenttype.contains("application")) {
savefile(bodypart.getinputstream(), destdir, decodename);
}
}
}
} else if (part.ismimetype("message/rfc822")) {
saveattachment((part) part.getcontent(), destdir, filename);
}
}
/**
* 获得邮件文本内容
* @param part 邮件体
* @param content 存储邮件文本内容的字符串
* @throws messagingexception
* @throws ioexception
*/
public static void getmailtextcontent(part part, stringbuffer content) throws messagingexception, ioexception {
//如果是文本类型的附件,通过getcontent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
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);
}
}
}
/**
* 读取输入流中的数据保存至指定目录
*
* @param is 输入流
* @param filename 文件名
* @param destdir 文件存储目录
*/
private static void savefile(inputstream is, string destdir, string filename)
throws exception {
createemptydirectory(destdir);
bufferedinputstream bis = new bufferedinputstream(is);
bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream(new file(destdir filename)));
int len;
while ((len = bis.read()) != -1) {
bos.write(len);
bos.flush();
}
bos.close();
bis.close();
}
/**
* 创建一个空目录
*/
public static void createemptydirectory(string directorypath) {
file file = new file(directorypath);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* 文本解码
*/
public static string decodetext(string encodetext) throws exception {
if (encodetext == null || "".equals(encodetext)) {
return "";
} else {
return mimeutility.decodetext(encodetext);
}
}
}
3,测试结果
imap测试结果:
pop测试结果
没限制查询条件结果
限制条件查询结果
4,存在问题
存在一个问题,就是在邮箱中已经设置只接收近30天的邮件,但是在imap方式中并没有生效,而pop方式是生效了,为什么imap的方式不生效呢?待解决
5,参考文档
[https://blog.csdn/qq_39006919/article/details/109115343]
https://blog.csdn/hj7jay/article/details/84062650
j9九游会老哥俱乐部交流区的版权声明:本文标题:java腾讯邮箱读取邮件(包含企业邮箱) 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1727421823a1113666.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论