📄 mailutil.java
字号:
/*------------------------------------------------------------------------------ Name: MailUtil.java Project: xmlBlaster.org Copyright: xmlBlaster.org, see xmlBlaster-LICENSE file Copyright: Parts learned from javamail-demo: 1996-2003 Sun Microsystems, Inc. All Rights Reserved. Comment: Converter used to convert native data to protocol-specific data. ------------------------------------------------------------------------------*/package org.xmlBlaster.util.protocol.email;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.sql.Timestamp;import java.text.DateFormat;import java.util.ArrayList;import java.util.Date;import java.util.Enumeration;import java.util.Properties;import java.util.logging.Logger;import javax.mail.Address;import javax.mail.FetchProfile;import javax.mail.Flags;import javax.mail.Folder;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.Part;import javax.mail.Session;import javax.mail.Store;import javax.mail.URLName;import javax.mail.event.StoreEvent;import javax.mail.event.StoreListener;import javax.mail.internet.ContentType;import javax.mail.internet.InternetAddress;import javax.mail.internet.MailDateFormat;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.ParseException;import org.xmlBlaster.util.Base64;import org.xmlBlaster.util.Global;import org.xmlBlaster.util.XmlBlasterException;import org.xmlBlaster.util.def.Constants;import org.xmlBlaster.util.def.ErrorCode;import org.xmlBlaster.util.xbformat.ByteArray;/** * Utilities to dump mail messages. We provide a main() to play with POP3 * access. Show information about and contents of messages. * * @author John Mani * @author Bill Shannon * @author Marcel Ruff */public class MailUtil { private static Logger log = Logger.getLogger(MailUtil.class.getName()); static String url = null; static boolean verbose = false; static boolean debug = false; static boolean showStructure = false; static boolean showAlert = false; static boolean saveAttachments = false; static int attnum = 1; /** * Fixed name which is used for the normal email content / body */ static public final String BODY_NAME = "body.xml"; /** * Reading POP3 messages and dump them (for testing only). Usage:<br/> * <pre> *java org.xmlBlaster.util.protocol.email.MailUtil -L pop3://marcel:marcel@localhost/INBOX * </pre> * @param argv */ public static void main(String argv[]) { for (int i = 0; i < argv.length; i++) { if (argv[i].equals("-v")) { verbose = true; } else if (argv[i].equals("-D")) { debug = true; } else if (argv[i].equals("-L")) { url = argv[++i]; } else if (argv[i].equals("-s")) { showStructure = true; } else if (argv[i].equals("-S")) { saveAttachments = true; } else if (argv[i].equals("-a")) { showAlert = true; } else if (argv[i].equals("--")) { i++; break; } else if (argv[i].startsWith("-")) { System.out .println("Usage: java org.xmlBlaster.util.protocol.MailUtil [-L url]"); System.out .println("Example: java org.xmlBlaster.util.protocol.MailUtil -L pop3://marcel:marcel@localhost/INBOX"); System.exit(1); } else { break; } } testPOP3Read(); } /** * Transforms an email "date-time" string to a java.util.Date. * <pre> date-time = [ day "," ] date time ; dd mm yy ; hh:mm:ss zzz day = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" date = 1*2DIGIT month 2DIGIT ; day month year ; e.g. 20 Jun 82 month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" time = hour zone ; ANSI and Military hour = 2DIGIT ":" 2DIGIT [":" 2DIGIT] ; 00:00:00 - 23:59:59 zone = "UT" / "GMT" ; Universal Time ; North American : UT / "EST" / "EDT" ; Eastern: - 5/ - 4 / "CST" / "CDT" ; Central: - 6/ - 5 / "MST" / "MDT" ; Mountain: - 7/ - 6 / "PST" / "PDT" ; Pacific: - 8/ - 7 / 1ALPHA ; Military: Z = UT; ; A:-1; (J not used) ; M:-12; N:+1; Y:+12 / ( ("+" / "-") 4DIGIT ) ; Local differential ; hours+min. (HHMM) * </pre> * @param dateString The http://www.faqs.org/rfcs/rfc822.html "date-time" string * @return the date parsed * @see http://www.faqs.org/rfcs/rfc2156.html * @throws IllegalArgumentException on ParseException */ public static Date dateTime(String dateString) { DateFormat df = new MailDateFormat(); try { return df.parse(dateString); } catch (java.text.ParseException e) { throw new IllegalArgumentException("Can't parse date-time string '" + dateString + "', please check email RFC 822: " + e.toString()); } } /** * @param dateString The http://www.faqs.org/rfcs/rfc822.html "date-time" string * @return the timestamp parsed * @throws IllegalArgumentException on ParseException */ public static java.sql.Timestamp dateTimeTS(String dateString) { Date date = dateTime(dateString); return new Timestamp(date.getTime()); } /** * @param date * @return The http://www.faqs.org/rfcs/rfc822.html "date-time" string */ public static String dateTime(Date date) { DateFormat df = new MailDateFormat(); return df.format(date); } /** * @param ts * @return The http://www.faqs.org/rfcs/rfc822.html "date-time" string * @see org.xmlBlaster.util.IsoDateParser */ public static String dateTime(java.sql.Timestamp ts) { Date date = new Date(ts.getTime()); return dateTime(date); } private static void testPOP3Read() { try { final String mbox = "INBOX"; // Get a Properties object Properties props = System.getProperties(); // Get a Session object Session session = Session.getInstance(props, null); session.setDebug(debug); // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); if (showAlert) { store.addStoreListener(new StoreListener() { public void notification(StoreEvent e) { String s; if (e.getMessageType() == StoreEvent.ALERT) s = "ALERT: "; else s = "NOTICE: "; System.out.println(s + e.getMessage()); } }); } store.connect(); } Folder folder = store.getDefaultFolder(); if (folder == null) { System.out.println("No default folder"); System.exit(1); } folder = folder.getFolder(mbox); if (folder == null) { System.out.println("Invalid folder"); System.exit(1); } // try to open read/write and if that fails try read-only try { folder.open(Folder.READ_WRITE); } catch (MessagingException ex) { folder.open(Folder.READ_ONLY); } int totalMessages = folder.getMessageCount(); if (totalMessages == 0) { System.out.println("Empty folder"); folder.close(false); store.close(); System.exit(1); } if (verbose) { int newMessages = folder.getNewMessageCount(); System.out.println("Total messages = " + totalMessages); System.out.println("New messages = " + newMessages); System.out.println("==============================="); } // Attributes & Flags for all messages .. Message[] msgs = folder.getMessages(); // Use a suitable FetchProfile FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(msgs, fp); for (int i = 0; i < msgs.length; i++) { int level = 0; System.out.println("\n=========MESSAGE #" + (i + 1) + ":================="); dumpEnvelope(msgs[i], level); level = dumpPart(msgs[i], level); } folder.close(false); store.close(); } catch (Exception ex) { System.out.println("Oops, got exception! " + ex.getMessage()); ex.printStackTrace(); System.exit(1); } System.exit(0); } public static void dumpMessage(Message msg) throws Exception { int level = 0; dumpEnvelope(msg, level); level = dumpPart(msg, level); } public static void dumpMessages(Message[] msgs) throws Exception { for (int i = 0; i < msgs.length; i++) { int level = 0; System.out.println("\n=========MESSAGE #" + (i + 1) + ":================="); dumpEnvelope(msgs[i], level); level = dumpPart(msgs[i], level); } } /** * Access all attachments. * @param p * @return a list of AttachmentHolder instances * @throws Exception */ public static ArrayList accessAttachments(Part p) throws XmlBlasterException { ArrayList attachments = new ArrayList(); int level = 0; accessPart(p, level, attachments); return attachments; } public static int accessPart(Part p, int level, ArrayList attachments) throws XmlBlasterException { if (level > 0 && p instanceof Message) { log.warning("Unexpected Message type in level " + level); return level; } try { String ct = p.getContentType(); String fileName = p.getFileName(); if (fileName == null) fileName = BODY_NAME; /* * Using isMimeType to determine the content type avoids fetching the * actual content data until we need it. */ if (p.isMimeType("text/plain")) { // All "UTF-8" AttachmentHolder a = null; if (p instanceof MimeBodyPart && Constants.EMAIL_TRANSFER_ENCODING.equals(((MimeBodyPart)p).getEncoding())) { byte[] content = Base64.decode((String)p.getContent()); a = new AttachmentHolder(fileName, ct, content); } else { a = new AttachmentHolder(fileName, ct, ((String)p.getContent()).getBytes(Constants.UTF8_ENCODING)); } attachments.add(a); } else if (p.isMimeType("multipart/*")) { // Go one level deeper ... Multipart mp = (Multipart) p.getContent(); level++; int count = mp.getCount();
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -