📄 maildirmessage.java
字号:
/*
* MaildirMessage.java
* Copyright (C) 1999 fengyun <fengyun@gbsource.net>
*/
package fengyun.Fastmail.Maildir;
import java.io.*;
import java.util.*;
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
import fengyun.Fastmail.util.ToolKit;
/**
* Maildir形式的消息
* @author fengyun@gbsource.net
* @version 1.01
*/
public class MaildirMessage extends MimeMessage {
public static final char flagMessageNew = 'N'; //新消息标志
public static final char flagMessageRead = 'R'; //消息已读
public static final char flagMessageDelete = 'D'; //消息被删除
public static final char flagMessageSource = 'S'; //消息原稿
public static final char flagMessageSent = 'T'; //消息以发送
public static final char flagMessagePoint = 'P'; //重要消息
public static final String DefaultCharSet = "ISO-8859-1"; //默认字符集
protected MaildirMessageSummary summary = null; //消息摘要
private boolean hasAttachment = false;
protected long contentOffset = -1; //消息体的起始偏址
/**
* 返回标志位
* @return char 标志位
*/
public char getFlag() {
return summary.getFlag();
}
/**
* 返回消息大小
* @return long 消息大小
*/
public int getSize() {
if (summary.getSize() <= 0) {
File file = new File(folder.getFullName() + File.separator + summary.getMessageID());
summary.setSize(file.length());
}
return (int)summary.getSize();
}
/**
* 返回接收时间
* @return long 接收时间
*/
public long getReceiveTime() {
return summary.getReceiveTime();
}
/**
* 返回消息名称
* @return String 消息名称
*/
public String getMessageID() throws MessagingException {
return summary.getMessageID();
}
/**
* 是否是新消息
*/
public boolean isNewMessage() {
return summary.isNewMessage();
}
public boolean hasAttachment() {
return hasAttachment;
}
public void hasAttachment(boolean has) {
hasAttachment = has;
}
/**
* 消息是否存在
* @return boolean 是否存在
*/
public boolean exists() throws MessagingException {
File file = new File(folder.getFullName() + folder.getSeparator() + getMessageID());
if (file.exists() && file.isFile()) return true;
else return false;
}
/**
* 设置标志位
* @param flag 新标志位
*/
public void setFlag(char flag) throws MessagingException {
String MessageID = getMessageID();
int cur = MessageID.indexOf(".");
if (cur <= 0) throw new MessagingException("Error Message name");
File file = new File(folder.getFullName() + folder.getSeparator() + MessageID);
if (file.exists() && file.isFile()) {
MessageID = String.valueOf(getReceiveTime()) + '.' + flag + MessageID.substring(cur+2);
if (isNewMessage()) ((MaildirFolder)folder).summary.decNewMessageCount();
summary.setFlag(flag);
summary.setMessageID(MessageID);
file.renameTo(new File(folder.getFullName() + folder.getSeparator() + MessageID));
}
}
/**
* 根据消息名称构造消息
* @param folder 所在邮件夹
* @param messageid 消息名称
* @param msgnum 消息号
*/
public MaildirMessage(Folder folder,String messageid,int msgnum) throws MessagingException {
super(folder,msgnum);
RandomAccessFile raf = null;
try {
int cur = messageid.indexOf(".");
long ReceiveTime = Long.valueOf(messageid.substring(0,cur)).longValue() ;
char Flag = messageid.substring(cur+1,cur+2).charAt(0);
raf = new RandomAccessFile(folder.getFullName() + folder.getSeparator() + messageid,"r");
long Size = raf.length();
summary = new MaildirMessageSummary(messageid,ReceiveTime,Flag,Size);
headers = new InternetHeaders();
String line;
while ((line = raf.readLine())!=null) {
int len = line.length();
if (len==0 || (len==1 && line.charAt(0)=='\r'))
break;
headers.addHeaderLine(line);
}
contentOffset = raf.getFilePointer();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
if (raf !=null) {
try {
raf.close();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
raf = null;
}
}
}
}
/**
* 根据消息摘要构造消息
* @param folder 所在邮件夹
* @param summary 对应的消息摘要
* @param msgnum 消息号
*/
public MaildirMessage(Folder folder,MaildirMessageSummary summary,int msgnum) throws MessagingException {
super(folder,msgnum);
this.summary = summary;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(folder.getFullName() + folder.getSeparator() + getMessageID(),"r");
headers = new InternetHeaders();
String line;
while ((line=raf.readLine())!=null) {
int len = line.length();
if (len==0 || (len==1 && line.charAt(0)=='\r'))
break;
headers.addHeaderLine(line);
}
contentOffset = raf.getFilePointer();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
if (raf !=null) {
try {
raf.close();
}
catch(Exception e) {
e.printStackTrace();
}
finally {
raf = null;
}
}
}
}
/**
* 返回消息体
* @return Object 消息体
*/
public Object getContent() throws MessagingException, IOException {
if (content==null)
retrieveContent();
return super.getContent();
}
/**
* 返回消息体输入流
* @return InputStream 消息体输入流
*/
public InputStream getContentStream() throws MessagingException {
if (content==null)
try {
retrieveContent();
} catch (IOException e) {
throw new MessagingException("I/O error", e);
}
return super.getContentStream();
}
/**
* 返回消息输入流
* @return InputStream 消息输入流
*/
public InputStream getInputStream() throws MessagingException, IOException {
if (content==null)
retrieveContent();
return super.getInputStream();
}
/**
* 返回消息行数
* @return int 消息行数
*/
public int getLineCount() throws MessagingException {
if (content==null)
try {
retrieveContent();
} catch (IOException e) {
throw new MessagingException("I/O error", e);
}
return super.getLineCount();
}
/**
* 获得消息体
*/
protected void retrieveContent() throws MessagingException,IOException {
if (contentOffset < 0 || content!=null) return;
int fetchsize = MaildirStore.fetchsize;
byte bytes[];
RandomAccessFile file =
new RandomAccessFile(folder.getFullName() + File.separator + getMessageID(), "r");
file.seek(contentOffset);
String line;
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (line = file.readLine(); line!=null; line = file.readLine()) {
out.write(line.getBytes());
out.write('\n');
}
content = out.toByteArray();
if (isNewMessage()) this.setFlag(this.flagMessageRead);
}
/**
* 返回主题
* @return String 主题
*/
public String getSubject() throws MessagingException {
String rawvalue = getHeader("Subject", null);
if (rawvalue == null)
return null;
try {
String charset = ToolKit.getCharSet(rawvalue);
String decodevalue = MimeUtility.decodeText(rawvalue);
if (charset != null && !DefaultCharSet.equals(charset)) {
decodevalue = new String(decodevalue.getBytes(charset),DefaultCharSet);
}
return decodevalue;
}
catch (UnsupportedEncodingException ex) {
return rawvalue;
}
}
/**
* 返回消息From地址
* @return Address[] From地址
*/
public Address[] getFrom() throws MessagingException {
Address[] a = getAddressHeader("From");
if (a==null) a = getAddressHeader("Sender");
return a;
}
/**
* 返回收件人相关信息
* @param type 收件人相关参数
* @return Address[] 地址数组
*/
public Address[] getRecipients(RecipientType type) throws MessagingException {
return getAddressHeader(getHeaderKey(type));
}
/**
* 返回返回地址
* @return Address[] 返回地址
*/
public Address[] getReplyTo() throws MessagingException {
Address[] a = getAddressHeader("Reply-To");
if (a==null) a = getFrom();
return a;
}
/**
* 返回对应健的头地址
* @param key 键
* @return Address[] 对应的地址
*/
protected Address[] getAddressHeader(String key) throws MessagingException {
String header = getHeader(key, ",");
if (header==null) return null;
try {
return InternetAddress.parse(header);
} catch (AddressException e) {
String message = e.getMessage();
if (message!=null && message.indexOf("@domain")>-1)
try {
return parseAddress(header, "localhost");
} catch (AddressException e2) {
throw new MessagingException("Invalid address: "+header, e);
}
throw e;
}
}
/**
* 解析地址
* @param in 头信息行
* @param defhost 默认主机名
* @return Address[] 地址信息
*/
protected Address[] parseAddress(String in, String defhost) throws AddressException {
Vector v = new Vector();
for (StringTokenizer st = new StringTokenizer(in, ","); st.hasMoreTokens(); ) {
String s = st.nextToken().trim();
try {
v.addElement(new InternetAddress(s));
} catch (AddressException e) {
int index = s.indexOf('>');
if (index>-1) { // name <address>
StringBuffer buffer = new StringBuffer();
buffer.append(s.substring(0, index));
buffer.append('@');
buffer.append(defhost);
buffer.append(s.substring(index));
v.addElement(new InternetAddress(buffer.toString()));
} else {
index = s.indexOf(" (");
if (index>-1) { // address (name)
StringBuffer buffer = new StringBuffer();
buffer.append(s.substring(0, index));
buffer.append('@');
buffer.append(defhost);
buffer.append(s.substring(index));
v.addElement(new InternetAddress(buffer.toString()));
} else // address
v.addElement(new InternetAddress(s+"@"+defhost));
}
}
}
Address[] a = new Address[v.size()]; v.copyInto(a);
return a;
}
/**
* 返回收件人键的相应头键
* @param type 收件人键
* @return String 头键
*/
protected String getHeaderKey(RecipientType type) throws MessagingException {
if (type==RecipientType.TO)
return "To";
if (type==RecipientType.CC)
return "Cc";
if (type==RecipientType.BCC)
return "Bcc";
if (type==RecipientType.NEWSGROUPS)
return "Newsgroups";
throw new MessagingException("Invalid recipient type: "+type);
}
/**
* 返回附件体
* @param attachment 附件名
*/
public BodyPart getAttachment(String attachment) throws MessagingException,IOException{
Object o = this.getContent();
if (!(o instanceof Multipart)) throw new MessagingException("Attachment not found");
Multipart mp = (Multipart)o;
int count = mp.getCount();
BodyPart bp = null;
for(int i=0;i<count;i++) {
if (mp.getBodyPart(i)!=null) {
try {
bp = dumpPart(mp.getBodyPart(i),attachment);
}
catch(Exception e) {
e.printStackTrace();
}
}
if (bp!=null) break;
}
if (bp==null) throw new MessagingException("Attachment not found");
return bp;
}
private static int level = 0;
/**
* DumpPart
* @param p Part
* @param attachment 附件名
*/
public static BodyPart dumpPart(Part p,String attachment) throws MessagingException,IOException {
if(p==null) return null;
if (p.isMimeType("multipart/*")) {
Multipart mp = (Multipart)p.getContent();
if (mp == null) return null;
level++;
int count = mp.getCount();
for (int i = 0; i < count; i++) {
BodyPart bp = dumpPart((Part)mp.getBodyPart(i),attachment);
if (bp != null) return bp;
}
level--;
}
else if (p instanceof BodyPart && p!=null) {
String strFileName = p.getFileName();
if (strFileName != null) {
String charset = ToolKit.getCharSet(strFileName);
if (charset != null) {
strFileName = ToolKit.getDecodeText(strFileName);
}
if (attachment.equals(strFileName)) {
p.setFileName(strFileName);
return (BodyPart)p;
}
}
else if (p.isMimeType("text/html") && "unknown.html".equals(attachment)) {
p.setFileName("unknown.html");
return (BodyPart)p;
}
}
return null;
}
/**
* 消息只读异常
*/
public void setFrom(Address address) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void addFrom(Address aaddress[]) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void setRecipients(javax.mail.Message.RecipientType recipienttype, Address aaddress[]) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void addRecipients(javax.mail.Message.RecipientType recipienttype, Address aaddress[]) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void setReplyTo(Address aaddress[]) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void setSubject(String s, String s1) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void setSentDate(Date date) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void setDisposition(String s) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void setContentID(String s) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void setContentMD5(String s) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void setDescription(String s, String s1) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 消息只读异常
*/
public void setDataHandler(DataHandler datahandler) throws MessagingException {
throw new IllegalWriteException("MaildirMessage is read-only");
}
/**
* 是否是同一消息
*/
public boolean equals(Object other) {
if (other instanceof MaildirMessage) {
MaildirMessage message = (MaildirMessage)other;
return (getFolder().equals(message.getFolder()) && summary.getMessageID().equals(message.summary.getMessageID()));
}
return false;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -