📄 emaildata.java
字号:
/*------------------------------------------------------------------------------ Name: EmailData.java Project: xmlBlaster.org Copyright: xmlBlaster.org, see xmlBlaster-LICENSE file Comment: javac EmailData.java SmtpClient.java ------------------------------------------------------------------------------*/package org.xmlBlaster.util.protocol.email;import java.sql.Timestamp;import java.util.ArrayList;import java.util.Date;import java.util.logging.Level;import java.util.logging.Logger;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import org.xmlBlaster.util.IsoDateParser;import org.xmlBlaster.util.ReplaceVariable;import org.xmlBlaster.util.StringPairTokenizer;import org.xmlBlaster.util.XmlNotPortable;import org.xmlBlaster.util.def.Constants;import org.xmlBlaster.util.def.MethodName;import org.xmlBlaster.util.xbformat.MsgInfoParserFactory;/** * Value object holding the most commonly used email fields. * <p> * Add/access/delete attachments is not simultaneous possible (not thread save) * </p> * Example: * <pre>From: demo@localhostTo: xmlBlaster@localhostSubject: Hello Worldattachement { fileName: messageId.mid content: <messageId><sessionId>abcd</sessionId><requestId>5</requestId></messageId>}attachement { fileName: xmlBlaster.xbf content: [the binary xmlBlaster format similar to that used with SOCKET]} * </pre> * <p> * Note on max. header length from RFC 2822: * <p> * "There are two limits that this standard places on the number of characters in a line. Each line of characters MUST be no more than 998 characters, and SHOULD be no more than 78 characters, excluding the CRLF." * @author <a href="mailto:xmlBlaster@marcelruff.info">Marcel Ruff</a> * @see http://www.faqs.org/rfcs/rfc2822.html */public class EmailData { private static Logger log = Logger.getLogger(EmailData.class.getName()); protected String encoding = Constants.UTF8_ENCODING; // "text/plain; charset=UTF-8" protected InternetAddress[] recipients; protected InternetAddress[] cc; protected InternetAddress[] bcc; protected InternetAddress from; protected String subject; protected String content; /** Containts AttachmentHolder instances */ protected ArrayList attachments; /** Contains sessionId * */ protected String sessionId; /** Contains requestId * */ protected String requestId; protected Timestamp expiryTime; /** The origination date from the email header, this field exists always for incoming emails */ protected Date sentDate; /** Remember if we got an explicit requestId or if we extracted it from the sentDate */ protected boolean requestIdFromSentDate; //Currently not supported protected InternetAddress[] replyTo; /** The root tag <messageId> */ public static final String MESSAGEID_TAG = "messageId"; public static final String METHODNAME_TAG = "methodName"; public static final String REQUESTID_TAG = "requestId"; public static final String SESSIONID_TAG = "sessionId"; public static final String EXPIRES_TAG = "expires"; /* * The value has the format <code>yyyy-mm-dd hh:mm:ss.fffffffff</code>, * the .f* are optional */ //public static final String EXPIRES_HEADER = "X-xmlBlaster-ExpiryDate"; /** * Expiry Date Indication * Supported as new RFC 822 header (Expires:). In general, no * automatic action can be expected. * @see http://www.faqs.org/rfcs/rfc2156.html */ public static final String EXPIRES_HEADER_RFC2156 = "Expires"; /** Holding the relevant email meta info like a request identifier */ public static final String MESSAGEID_EXTENSION = ".mid"; /** * Create a simple message. * * @param recipient * For example "jack@gmx.net" * @param from * For example "sue@gmx.net" * @param subject * For example "Hi" * @param content * For example "Best regards, Sue" */ public EmailData(String recipient, String from, String subject, String content) { this.recipients = new InternetAddress[recipient == null ? 0 : 1]; if (recipient != null) this.recipients[0] = toInternetAddress(recipient); this.from = toInternetAddress(from); this.subject = subject; this.content = content; } /** * Create a simple message for any number of recipients. * * @see #EmailData(String, String, String, String) */ public EmailData(String[] recipients, String from, String subject, String content) { if (recipients == null) { this.recipients = new InternetAddress[0]; } else { this.recipients = new InternetAddress[recipients.length]; for (int i=0; i<recipients.length; i++) this.recipients[i] = toInternetAddress(recipients[i]); } this.from = toInternetAddress(from); this.subject = subject; this.content = content; } public EmailData(InternetAddress recipient, InternetAddress from, String subject) { if (recipient == null) { this.recipients = new InternetAddress[0]; } else { this.recipients = new InternetAddress[1]; this.recipients[0] = recipient; } this.from = from; this.subject = subject; this.content = null; } private InternetAddress toInternetAddress(String address) throws IllegalArgumentException { try { return new InternetAddress(address); } catch (AddressException e) { throw new IllegalArgumentException("Illegal email address '" + address + "': " + e.toString()); } } public void addAttachment(AttachmentHolder attachmentHolder) { if (this.attachments == null) this.attachments = new ArrayList(); this.attachments.add(attachmentHolder); } public void setAttachments(ArrayList attachmentHolders) { this.attachments = attachmentHolders; } /** * Access all attachements. * @return Never null */ public AttachmentHolder[] getAttachments() { if (this.attachments == null) return new AttachmentHolder[0]; return (AttachmentHolder[]) this.attachments .toArray(new AttachmentHolder[this.attachments.size()]); } /** * Lookup attachment. * @param extension For example XbfParser.XBFORMAT_EXTENSION=".xbf" * @return null if no such attachment was found */ public byte[] getContentByExtension(String extension) { AttachmentHolder[] atts = getAttachments(); for (int j = 0; j < atts.length; j++) { if (atts[j].hasExtension(extension)) { return atts[j].getContent(); } } return null; } /** * Lookup attachment. * If extension is not found try to find extensionBackup. * @param extension For example XbfParser.XBFORMAT_EXTENSION=".xbf" * @param extensionZ For example XbfParser.XBFORMAT_ZLIB_EXTENSION=".xbfz" * @param extensionBackup For example ".xml" * @return null if no such attachment was found */// public AttachmentHolder getEncodedMsgUnitByExtension(String extension, String extensionZ, String extensionBackup) { public AttachmentHolder getMsgUnitAttachment() { MsgInfoParserFactory fac = MsgInfoParserFactory.instance(); AttachmentHolder[] atts = getAttachments(); for (int j = 0; j < atts.length; j++) { if (fac.parserExists(atts[j].getFileName(), atts[j].getContentType())) { return atts[j]; } } return null; } public boolean isMsgUnitAttachment(AttachmentHolder holder) { AttachmentHolder msgUnitHolder = getMsgUnitAttachment(); if (msgUnitHolder == null) return false; return msgUnitHolder.equals(holder); } /** * Comma separated value list of all attachment file names (unquoted) for logging. * @return For example "a.xbf, b.xml, m.mid" */ public String getFileNameList() { StringBuffer buf = new StringBuffer(); AttachmentHolder[] atts = getAttachments(); for (int j = 0; j < atts.length; j++) { if (j > 0) buf.append(","); buf.append(atts[j].getFileName()); } return buf.toString(); } /** * Comma separated value list of all recipient email addresses for logging. * @return For example "joe@locahost,demo@localhost" */ public String getRecipientsList() { if (this.recipients == null) return ""; StringBuffer buf = new StringBuffer(); for (int j = 0; j < this.recipients.length; j++) { if (j > 0) buf.append(","); buf.append(this.recipients[j]); } return buf.toString(); } /** * @see #getEncoding() */ public void setEncoding(String aEncoding) { if (aEncoding != null) { this.encoding = aEncoding; } } /** * Encoding (charset) for example "UTF-8". To support Japanese, English and * German, use "UTF-8", this sets for example the mail header: * * <pre> * Content-Type: text/plain; charset=UTF-8 * </pre> * * "ISO-8859-1" is good enough for German and English * * @return Never null, defaults to "ISO-8859-1" */ public String getEncoding() { return this.encoding; } /** * @return All destinations of the message, never null */ public String[] getAllRecipients() { String[] ret = new String[this.recipients.length]; for (int i=0; i<this.recipients.length; i++) ret[i] = this.recipients[i].toString(); return ret; } /** * @return The from of the message, never null */ public String getFrom() { return (this.from == null) ? "" : this.from.getAddress(); } /** * @return Never null */ public InternetAddress getFromAddress() { return this.from; } public InternetAddress[] getToAddresses() { return this.recipients; } /** * @return The subject of the message, never null */ public String getSubject() { return (this.subject == null) ? "" : this.subject; } /** * @param subject The subject to set. */ public void setSubject(String subject) { this.subject = subject; } /** * @return The content of the message, never null */ public String getContent() { if (this.content == null || this.content.length() == 0) { AttachmentHolder h = getAttachment(MailUtil.BODY_NAME); if (h != null) this.content = new String(h.getContent()); } return (this.content == null) ? "" : this.content; } public AttachmentHolder getAttachment(String fileName) { if (fileName == null) return null; AttachmentHolder[] arr = getAttachments(); for (int i=0; i<arr.length; i++) if (fileName.equals(arr[i].getFileName())) return arr[i]; return null; } /** * Dumps message to xml. * @param readable If true '\0' are replaced by '*' */ public String toXml(boolean readable) { String offset = "\n"; StringBuffer sb = new StringBuffer(1024); sb.append(offset).append("<message>"); if (getExpiryTime() != null) sb.append(offset).append(" ").append(createMessageId(null, getExpiryTime())); sb.append(offset).append(" <from>").append(XmlNotPortable.escape(getFrom())).append( "</from>"); for (int i = 0; i < this.recipients.length; i++) { sb.append(offset).append(" <to>").append(XmlNotPortable.escape(this.recipients[i].toString())) .append("</to>"); } if (this.recipients.length == 0) { sb.append(offset).append(" <to></to>"); } for (int i = 0; this.cc!=null && i < this.cc.length; i++) { sb.append(offset).append(" <cc>").append(XmlNotPortable.escape(this.cc[i].toString())) .append("</cc>"); } for (int i = 0; this.bcc!=null && i < this.bcc.length; i++) { sb.append(offset).append(" <bcc>").append(XmlNotPortable.escape(this.bcc[i].toString())) .append("</bcc>"); } sb.append(offset).append(" <subject>").append(XmlNotPortable.escape(getSubject())) .append("</subject>"); if (this.content != null && this.content.length() > 0) { String con = this.content; /* if (this.content instanceof javax.mail.internet.MimeMultipart) { MimeMultipart part = (MimeMultipart)this.content; if (part.getCount() > 0) con = part.getBodyPart(0).getContent(); } */ sb.append(offset).append(" <content>").append(XmlNotPortable.escape(con)).append("</content>"); } AttachmentHolder[] att = getAttachments(); for (int i = 0; i < att.length; i++) sb.append(att[i].toXml(readable)); sb.append(offset).append("</message>"); return sb.toString(); } /** * Internal helper for parsing. * * @param startIndex >= * 0 * @param value * The wanted text between the tags * @return The current start position and -1 if not found */ private static int parseTag(int startIndex, String startToken, String endToken, String xml, StringBuffer value) { value.setLength(0); int start = xml.indexOf(startToken, startIndex); if (start == -1) { return start; }
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -