
// 从EML文件得到MimeMessage对象
MimeMessage message = new MimeMessage(session, new FileInputStream(emlFile));
public static String getMailSubject(Message message) throws Exception {
return MimeUtilitydecodeText(messagegetSubject());
}
public static String getMailSender(Message message) throws Exception {
String emailSender = null;
Address[] addresses = messagegetFrom();
if (addresses == null || addresseslength < 1) {
throw new IllegalArgumentException("该邮件没有发件人");
}
// 获得发件人
InternetAddress address = (InternetAddress) addresses[0];
String senderName = addressgetPersonal();
if (senderName != null) {
senderName = MimeUtilitydecodeText(senderName);
emailSender = senderName + "<" + addressgetAddress() + ">";
} else {
senderName = addressgetAddress();
}
return emailSender;
}
public static String getMailRecipients(Message message, MessageRecipientType recipientType) throws Exception {
StringBuilder builder = new StringBuilder();
Address[] addresses = null;
if (recipientType == null) {
addresses = messagegetAllRecipients();
} else {
addresses = messagegetRecipients(recipientType);
}
if (addresses == null || addresseslength < 1) {
throw new IllegalArgumentException("该邮件没有收件人");
}
for (Address address : addresses) {
InternetAddress iAddress = (InternetAddress) address;
builderappend(iAddresstoUnicodeString())append(", ");
}
return builderdeleteCharAt(builderlength() - 1)toString();
}
public static String getMailSendDate(Message message, String pattern) throws Exception {
String sendDateString = null;
if (pattern == null || ""equals(patterntrim())) {
pattern = "yyyy年MM月dd日 E HH:mm";
}
Date sendDate = messagegetSentDate();
sendDateString = new SimpleDateFormat(pattern)format(sendDate);
return sendDateString;
}
public static boolean containsAttachment(Part part) throws Exception {
boolean flag = false;
if (part != null) {
if (partisMimeType("multipart/")) {
MimeMultipart mp = (MimeMultipart) partgetContent();
for (int i = 0; i < mpgetCount(); i++) {
BodyPart bodyPart = mpgetBodyPart(i);
String disposition = bodyPartgetDisposition();
if (disposition != null && (PartATTACHMENTequalsIgnoreCase(disposition)
|| PartINLINEequalsIgnoreCase(disposition))) {
flag = true;
} else if (bodyPartisMimeType("multipart/")) {
flag = containsAttachment(bodyPart);
} else {
String contentType = bodyPartgetContentType();
if (contentTypeindexOf("application") != -1) {
flag = true;
}
if (contentTypeindexOf("name") != -1) {
flag = true;
}
}
if (flag)
break;
}
} else if (partisMimeType("message/rfc822")) {
flag = containsAttachment((Part) partgetContent());
}
}
return flag;
}
public static boolean isSeen(Message message) throws Exception {
if (message == null) {
throw new MessagingException("Message is empty");
}
return messagegetFlags()contains(FlagsFlagSEEN);
}
public static boolean isReplaySign(Message message) throws Exception {
if (message == null) {
throw new MessagingException("Message is empty");
}
boolean replaySign = false;
String[] headers = messagegetHeader("Disposition-Notification-To");
if (headers != null && headerslength > 0) {
replaySign = true;
}
return replaySign;
}
public static String getMailPriority(Message message) throws Exception {
if (message == null) {
throw new MessagingException("Message is empty");
}
String priority = "普通";
String[] headers = messagegetHeader("X-Priority");
if (headers != null && headerslength > 0) {
String mailPriority = headers[0];
if (mailPriorityindexOf("1") != -1 || mailPriorityindexOf("High") != -1) {
priority = "紧急";
} else if (mailPriorityindexOf("5") != -1 || mailPriorityindexOf("Low") != -1) {
priority = "低";
} else {
priority = "普通"; // 3或者Normal;
}
}
return priority;
}
public static void getMailTextContent(Part part, StringBuilder content) throws Exception {
if (part == null) {
throw new MessagingException("Message content is empty");
}
boolean containsTextInAttachment = partgetContentType()indexOf("name") > 0;
if (partisMimeType("text/") && containsTextInAttachment) {
contentappend(partgetContent()toString());
} else if (partisMimeType("message/rfc822")) {
getMailTextContent((Part) partgetContent(), content);
} else if (partisMimeType("multipart/")) {
Multipart mp = (Multipart) partgetContent();
for (int i = 0; i < mpgetCount(); i++) {
BodyPart bodyPart = mpgetBodyPart(i);
getMailTextContent(bodyPart, content);
}
} else if (partisMimeType("image/")) {
// TODO partgetInputStream()获得输入流然后输出到指定的目录
} else {
// TODO 其它类型的contentType, 未做处理, 直接输出
contentappend(partgetContent()toString());
}
}
public static void saveAttachment(Part part, String destDir) throws Exception {
if (part == null) {
throw new MessagingException("part is empty");
}
// 复杂的邮件包含多个邮件体
if (partisMimeType("multipart/")) {
Multipart mp = (Multipart) partgetContent();
// 遍历每一个邮件体
for (int i = 0; i < mpgetCount(); i++) {
BodyPart bodyPart = mpgetBodyPart(i);
// bodyPart也可能有多个邮件体组成
String disposition = bodyPartgetDisposition();
if (disposition == null && (PartATTACHMENTequalsIgnoreCase(disposition)
|| PartINLINEequalsIgnoreCase(disposition))) {
InputStream in = bodyPartgetInputStream();
saveFile(in, destDir, decodeText(bodyPartgetFileName()));
} else if (bodyPartisMimeType("multipart/")) {
saveAttachment(bodyPart, destDir);
} else {
String contentType = bodyPartgetContentType();
if (contentTypeindexOf("name") != -1 || contentTypeindexOf("application") != -1) {
saveFile(bodyPartgetInputStream(), destDir, decodeText(bodyPartgetFileName()));
}
}
}
} else if (partisMimeType("message/rfc822")) {
saveAttachment((Part) partgetContent(), destDir);
}
}
public static void saveFile(InputStream in, String destDir, String fileName) throws Exception {
FileOutputStream out = new FileOutputStream(new File(destDir + fileName));
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inread(buffer)) != -1) {
outwrite(buffer, 0, length);
}
outclose();
inclose();
}
public static String decodeText(String encodedText) throws Exception {
if (encodedText == null || ""equals(encodedTexttrim())) {
return "";
} else {
return MimeUtilitydecodeText(encodedText);
}
}
package comghyutil;
import javaioBufferedInputStream;
import javaioBufferedOutputStream;
import javaioFile;
import javaioFileOutputStream;
import javaioIOException;
import javaioInputStream;
import javatextSimpleDateFormat;
import javautilDate;
import javautilProperties;
import javaxmailBodyPart;
import javaxmailFlags;
import javaxmailFolder;
import javaxmailMessage;
import javaxmailMessagingException;
import javaxmailMultipart;
import javaxmailPart;
import javaxmailSession;
import javaxmailStore;
import javaxmailinternetInternetAddress;
import javaxmailinternetMimeMessage;
import javaxmailinternetMimeUtility;
public class PraseMimeMessage{
private MimeMessage mimeMessage=null;
private String saveAttachPath="";//附件下载后的存放目录
private StringBuffer bodytext=new StringBuffer();
//存放邮件内容的StringBuffer对象
private String dateformat="yy-MM-dd HH:mm";//默认的日前显示格式
/
构造函数,初始化一个MimeMessage对象
/
public PraseMimeMessage() {
}
public PraseMimeMessage(MimeMessage mimeMessage) {
thismimeMessage=mimeMessage;
}
public void setMimeMessage(MimeMessage mimeMessage){
thismimeMessage=mimeMessage;
}
/
获得发件人的地址和姓名
/
public String getFrom1()throws Exception{
InternetAddress address[]=(InternetAddress[])mimeMessagegetFrom();
String from=address[0]getAddress();
if(from==null){
from="";
}
String personal=address[0]getPersonal();
if(personal==null){
personal="";
}
String fromaddr=personal+"<"+from+">";
return fromaddr;
}
/
获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同
"to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
@throws Exception /
public String getMailAddress(String type){
String mailaddr="";
try {
String addtype=typetoUpperCase();
InternetAddress []address=null;
if(addtypeequals("TO")||addtypeequals("CC")||addtypeequals("BBC")){
if(addtypeequals("TO")){
address=(InternetAddress[])mimeMessagegetRecipients(MessageRecipientTypeTO);
}
else if(addtypeequals("CC")){
address=(InternetAddress[])mimeMessagegetRecipients(MessageRecipientTypeCC);
}
else{
address=(InternetAddress[])mimeMessagegetRecipients(MessageRecipientTypeBCC);
}
if(address!=null){
for (int i = 0; i < addresslength; i++) {
String email=address[i]getAddress();
if(email==null)email="";
else{
email=MimeUtilitydecodeText(email);
}
String personal=address[i]getPersonal();
if(personal==null)personal="";
else{
personal=MimeUtilitydecodeText(personal);
}
String compositeto=personal+"<"+email+">";
mailaddr+=","+compositeto;
}
mailaddr=mailaddrsubstring(1);
}
}
else{
}
} catch (Exception e) {
// TODO: handle exception
}
return mailaddr;
}
/
获得邮件主题
/
public String getSubject()
{
String subject="";
try {
subject=MimeUtilitydecodeText(mimeMessagegetSubject());
if(subject==null)subject="";
} catch (Exception e) {
// TODO: handle exception
}
return subject;
}
/
获得邮件发送日期
/
public String getSendDate()throws Exception{
Date senddate=mimeMessagegetSentDate();
SimpleDateFormat format=new SimpleDateFormat(dateformat);
return formatformat(senddate);
}
/
解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件
主要是根据MimeType类型的不同执行不同的 *** 作,一步一步的解析
/
public void getMailContent(Part part)throws Exception{
String contenttype=partgetContentType();
int nameindex=contenttypeindexOf("name");
boolean conname=false;
if(nameindex!=-1)conname=true;
if(partisMimeType("text/plain")&&!conname){
bodytextappend((String)partgetContent());
}else if(partisMimeType("text/html")&&!conname){
bodytextappend((String)partgetContent());
}
else if(partisMimeType("multipart/")){
Multipart multipart=(Multipart)partgetContent();
int counts=multipartgetCount();
for(int i=0;i<counts;i++){
getMailContent(multipartgetBodyPart(i));
}
}else if(partisMimeType("message/rfc822")){
getMailContent((Part)partgetContent());
}
else{}
}
/
获得邮件正文内容
/
public String getBodyText(){
return bodytexttoString();
}
/
判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
@throws MessagingException /
public boolean getReplySign() throws MessagingException{
boolean replysign=false;
String needreply[]=mimeMessagegetHeader("Disposition-Notification-To");
if(needreply!=null){
replysign=true;
}
return replysign;
}
/
获得此邮件的Message-ID
@throws MessagingException /
public String getMessageId() throws MessagingException{
return mimeMessagegetMessageID();
}
/
判断此邮件是否已读,如果未读返回返回false,反之返回true
@throws MessagingException /
public boolean isNew() throws MessagingException{
boolean isnew =false;
Flags flags=((Message)mimeMessage)getFlags();
FlagsFlag[]flag=flagsgetSystemFlags();
for (int i = 0; i < flaglength; i++) {
if(flag[i]==FlagsFlagSEEN){
isnew=true;
break;
}
}
return isnew;
}
/
判断此邮件是否包含附件
@throws MessagingException /
public boolean isContainAttach(Part part) throws Exception{
boolean attachflag=false;
String contentType=partgetContentType();
if(partisMimeType("multipart/")){
Multipart mp=(Multipart)partgetContent();
//获取附件名称可能包含多个附件
for(int j=0;j<mpgetCount();j++){
BodyPart mpart=mpgetBodyPart(j);
String disposition=mpartgetDescription();
if((disposition!=null)&&((dispositionequals(PartATTACHMENT))||(dispositionequals(PartINLINE)))){
attachflag=true;
}else if(mpartisMimeType("multipart/")){
attachflag=isContainAttach((Part)mpart);
}else{
String contype=mpartgetContentType();
if(contypetoLowerCase()indexOf("application")!=-1) attachflag=true;
if(contypetoLowerCase()indexOf("name")!=-1) attachflag=true;
}
}
}else if(partisMimeType("message/rfc822")){
attachflag=isContainAttach((Part)partgetContent());
}
return attachflag;
}
/
保存附件
@throws Exception
@throws IOException
@throws MessagingException
@throws Exception /
public void saveAttachMent(Part part) throws Exception {
String fileName="";
if(partisMimeType("multipart/")){
Multipart mp=(Multipart)partgetContent();
for(int j=0;j<mpgetCount();j++){
BodyPart mpart=mpgetBodyPart(j);
String disposition=mpartgetDescription();
if((disposition!=null)&&((dispositionequals(PartATTACHMENT))||(dispositionequals(PartINLINE)))){
fileName=mpartgetFileName();
if(fileNametoLowerCase()indexOf("GBK")!=-1){
fileName=MimeUtilitydecodeText(fileName);
}
saveFile(fileName,mpartgetInputStream());
}
else if(mpartisMimeType("multipart/")){
fileName=mpartgetFileName();
}
else{
fileName=mpartgetFileName();
if((fileName!=null)){
fileName=MimeUtilitydecodeText(fileName);
saveFile(fileName,mpartgetInputStream());
}
}
}
}
else if(partisMimeType("message/rfc822")){
saveAttachMent((Part)partgetContent());
}
}
/
设置附件存放路径
/
public void setAttachPath(String attachpath){
thissaveAttachPath=attachpath;
}
/
设置日期显示格式
/
public void setDateFormat(String format){
thisdateformat=format;
}
/
获得附件存放路径
/
public String getAttachPath()
{
return saveAttachPath;
}
/
真正的保存附件到指定目录里
/
private void saveFile(String fileName,InputStream in)throws Exception{
String osName=SystemgetProperty("osname");
String storedir=getAttachPath();
String separator="";
if(osName==null)osName="";
if(osNametoLowerCase()indexOf("win")!=-1){
//如果是window *** 作系统
separator="/";
if(storedir==null||storedirequals(""))storedir="c:\tmp";
}
else{
//如果是其他的系统
separator="/";
storedir="/tmp";
}
File strorefile=new File(storedir+separator+fileName);
BufferedOutputStream bos=null;
BufferedInputStream bis=null;
try {
bos=new BufferedOutputStream(new FileOutputStream(strorefile));
bis=new BufferedInputStream(in);
int c;
while((c=bisread())!=-1){
boswrite(c);
bosflush();
}
} catch (Exception e) {
// TODO: handle exception
}finally{
bosclose();
bisclose();
}
}
/
PraseMimeMessage类测试
@throws Exception /
public static void main(String[] args) throws Exception {
String host="pop3sinacomcn";
String username="guohuaiyong70345";
String password="071120";
Properties props=new Properties();
Session session=SessiongetDefaultInstance(props,null);
Store store=sessiongetStore("pop3");
storeconnect(host,username,password);
Folder folder=storegetFolder("INBOX");
folderopen(FolderREAD_ONLY);
Message message[]=foldergetMessages();
PraseMimeMessage pmm=null;
for (int i = 0; i < messagelength; i++) {
Systemoutprintln("第"+(i+1)+"封邮件");
pmm=new PraseMimeMessage((MimeMessage)message[i]);
Systemoutprintln("主题 :"+pmmgetSubject());
pmmsetDateFormat("yy年MM月dd日 HH:mm");
Systemoutprintln("发送时间 :"+pmmgetSendDate());
Systemoutprintln("是否回执 :"+pmmgetReplySign());
Systemoutprintln("是否包含附件 :"+pmmisContainAttach((Part)message[i]));
Systemoutprintln("发件人 :"+pmmgetFrom1());
Systemoutprintln("收件人 :"+pmmgetMailAddress("TO"));
Systemoutprintln("抄送地址 :"+pmmgetMailAddress("CC"));
Systemoutprintln("密送地址 :"+pmmgetMailAddress("BCC"));
Systemoutprintln("邮件ID :"+i+":"+pmmgetMessageId());
pmmgetMailContent((Part)message[i]); //根据内容的不同解析邮件
pmmsetAttachPath("c:/tmp/mail"); //设置邮件附件的保存路径
pmmsaveAttachMent((Part)message[i]); //保存附件
Systemoutprintln("邮件正文 :"+pmmgetBodyText());
Systemoutprintln("第"+(i+1)+"封邮件结束");
}
}
}
我也出现这个问题,我出这个问题是附件名称生成时,使用的整个文件目录,导致文件名称过长,设置的文件名称的时候只截取最后一个就好
// 获取附件名称,并将名称赋予filename
String affixName = null;// 附件名称因为要有后缀名,否则将无法读取和下载,所以要从affix_url中获取!
if(affix_urlcontains("/")) {
int i = affix_urllastIndexOf("/");
affixName = affix_urlsubstring(i + 1);
}else {
affixName = affix_url;
}
java mail发带附近件的程序,你搜一下,有例子
这个不是上传到邮件服务器,是发送邮件时,包含在邮件中,
而你在网页邮箱里看到的,是用后台程序解析完邮件,将文件提取出来,放到服务器上,提供下载。
以上就是关于java 解析 eml的源代码全部的内容,包括:java 解析 eml的源代码、javamail接收邮件怎么解析内容、邮件发送的时候,自带附件发送的时候文件,变成了 ATT00002.bin。这是神马原因等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)