- package com.skycn.pop3;
-
- import java.io.File;
- import java.util.Properties;
-
-
-
-
-
- public class MailReceiverInfo {
-
- private String mailServerHost;
- private String mailServerPost;
- private String protpcal = "pop3";
-
- private String userName;
- private String passWord;
-
- private String attchmentDir = "";
- private String emailDir = "";
- private String emailFileSuffix = ".eml";
-
- private boolean vaildate = true;
-
- public Properties getProperties() {
- Properties properties = new Properties();
- properties.put("mail.pop3.host", mailServerHost);
- properties.put("mail.pop3.port", mailServerPost);
- properties.put("mail.pop3.auth", vaildate ? "true" : "false");
- return properties;
- }
-
- public String getMailServerHost() {
- return mailServerHost;
- }
-
- public void setMailServerHost(String mailServerHost) {
- this.mailServerHost = mailServerHost;
- }
-
- public String getMailServerPost() {
- return mailServerPost;
- }
-
- public void setMailServerPost(String mailServerPost) {
- this.mailServerPost = mailServerPost;
- }
-
- public String getProtpcal() {
- return protpcal;
- }
-
- public void setProtpcal(String protpcal) {
- this.protpcal = protpcal;
- }
-
- public String getUserName() {
- return userName;
- }
-
- public void setUserName(String userName) {
- this.userName = userName;
- }
-
- public String getPassWord() {
- return passWord;
- }
-
- public void setPassWord(String passWord) {
- this.passWord = passWord;
- }
-
- public String getAttchmentDir() {
- return attchmentDir;
- }
-
- public void setAttchmentDir(String attchmentDir) {
- if (!attchmentDir.endsWith(File.separator)) {
- attchmentDir = attchmentDir + File.separator;
- }
- this.attchmentDir = attchmentDir;
- }
-
- public String getEmailDir() {
- return emailDir;
- }
-
- public void setEmailDir(String emailDir) {
- if (!emailDir.endsWith(File.separator)) {
- emailDir = emailDir + File.separator;
- }
- this.emailDir = emailDir;
- }
-
- public String getEmailFileSuffix() {
- return emailFileSuffix;
- }
-
- public void setEmailFileSuffix(String emailFileSuffix) {
- if (!emailFileSuffix.endsWith(File.separator)) {
- emailFileSuffix = emailFileSuffix + File.separator;
- }
- this.emailFileSuffix = emailFileSuffix;
- }
-
- public boolean isVaildate() {
- return vaildate;
- }
-
- public void setVaildate(boolean vaildate) {
- this.vaildate = vaildate;
- }
-
- }
- package com.skycn.pop3;
-
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.Reader;
- import java.io.StringReader;
- import java.io.UnsupportedEncodingException;
-
- import javax.mail.BodyPart;
- import javax.mail.Flags;
- import javax.mail.Folder;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.Multipart;
- import javax.mail.NoSuchProviderException;
- import javax.mail.Part;
- import javax.mail.Session;
- import javax.mail.Store;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeUtility;
- import javax.xml.crypto.Data;
-
- import com.skycn.helper.MyAuthenticator;
-
-
-
-
-
-
- @SuppressWarnings("unused")
- public class MailReceiver {
-
- private MailReceiverInfo receiverInfo;
- private Store store;
- private Folder folder;
- private Message[] messages;
- private Message currentMessage;
- private String currentEmailFileName;
-
- public MailReceiver(MailReceiverInfo receiverInfo) {
- this.receiverInfo = receiverInfo;
- }
-
-
-
-
- public void receiveAllMail() throws Exception {
- if (this.receiverInfo == null) {
- throw new Exception("必须提供收邮件的参数");
- }
-
- if (this.connectToServer()) {
-
- if (this.openInBoxFolder()) {
-
- this.getAllMail();
- this.closeConnection();
- } else {
- throw new Exception("打开连接失败");
- }
- } else {
- throw new Exception("打开连接失败");
- }
-
- }
-
-
-
-
- @SuppressWarnings("unused")
- private boolean connectToServer() {
-
- MyAuthenticator authenticator = null;
- if (this.receiverInfo.isVaildate()) {
-
- authenticator = new MyAuthenticator(
- this.receiverInfo.getUserName(), this.receiverInfo
- .getPassWord());
- }
-
- Session mailSession = Session.getInstance(this.receiverInfo
- .getProperties());
- try {
-
- this.store = mailSession.getStore(this.receiverInfo.getProtpcal());
- } catch (NoSuchProviderException e) {
- System.out.println("链接服务器失败");
- return false;
- }
- System.out.println("connecting");
- try {
- this.store.connect();
- } catch (MessagingException e) {
-
- System.out.println("链接服务器失败");
- return false;
- }
- return true;
- }
-
-
-
-
-
- private boolean openInBoxFolder() {
- try {
- this.folder = this.store.getFolder("inbox");
- folder.open(Folder.READ_ONLY);
- return true;
- } catch (MessagingException e) {
-
- e.printStackTrace();
- }
- return false;
- }
-
-
-
-
-
-
- private boolean closeConnection() {
- try {
- if (this.folder.isOpen()) {
- this.folder.close(true);
- }
- this.store.close();
- System.out.println("关闭链接成功 ");
- return true;
- } catch (MessagingException e) {
-
- e.printStackTrace();
- }
- return false;
- }
-
- private void getAllMail() throws Exception {
-
- this.messages = this.folder.getMessages();
- System.out.println("总邮件数目:" + messages.length);
- System.out.println("新邮件数目:" + this.getNewMessageCount());
- System.out.println("未读邮件数目:" + this.getUnreadMessageConunt());
-
- int mailArrayLength = this.getMessageCount();
- System.out.println("一共有邮件" + mailArrayLength + "封");
- int errorCounter = 0;
- int successCounter = 0;
- for (int index = 0; index < mailArrayLength; index++) {
- this.currentMessage = messages[index];
- System.out.println("正在获取第" + index + "封邮件~~~~~~~~~~~~~~");
- this.showMailBasicInfo();
- }
-
- }
-
- private void showMailBasicInfo() throws Exception {
-
- showMailBasicInfo(this.currentMessage);
- }
-
-
-
-
-
-
-
- private void showMailBasicInfo(Message message) throws Exception {
-
- System.out.println("~~~~~~~~~~~邮件ID:" + this.getMessageId()
- + "~~~~~~~~~~~~~~~~~~~~~~~ ");
- System.out.println("From:" + this.getFrom());
- System.out.println("To:" + this.getToAddress());
- System.out.println("CC:" + this.getCCAddress());
- System.out.println("BCC:" + this.getBCCAddress());
- System.out.println("Subject:" + this.getSubject());
- System.out.println("发送时间:" + this.getSentDate());
- System.out.println("是新邮件?:" + this.isNew());
- System.out.println("是否回执:" + this.getReplySign());
- System.out.println("包涵附件:" + this.isContainAttch());
- System.out
- .println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
- }
-
- private boolean isContainAttch() throws Exception {
-
- return isContainAttch(this.currentMessage);
- }
-
-
-
-
-
-
-
-
- private boolean isContainAttch(Part part) throws Exception {
- boolean attachflag = false;
- if (part.isMimeType("multipart/*")) {
-
- Multipart mp = (Multipart) part.getContent();
-
- for (int i = 0; i < mp.getCount(); i++) {
- BodyPart bodyPart = mp.getBodyPart(i);
- String disposition = bodyPart.getDisposition();
- if ((disposition != null)
- && ((disposition.equals(Part.ATTACHMENT) || (disposition
- .equals(Part.INLINE))))) {
- attachflag = true;
- } else if (bodyPart.isMimeType("Multipart/*")) {
- attachflag = isContainAttch((Part) bodyPart);
- } else {
- String contype = bodyPart.getContentType();
- if (contype.toLowerCase().indexOf("applcation") != -1) {
- attachflag = true;
- }
- if (contype.toLowerCase().indexOf("name") != -1) {
- attachflag = true;
- }
- }
- }
- } else if (part.isMimeType("message/rfc822")) {
- attachflag = isContainAttch((Part) part.getContent());
- }
- return attachflag;
- }
-
- private String getMessageId() throws Exception {
-
- return getMessageId(this.currentMessage);
- }
-
- /***************************************************************************
- * 获得Message - Id
- *
- * @param mimeMessage
- * @return
- * @throws Exception
- */
- private String getMessageId(Message mimeMessage) throws Exception {
- MimeMessage message = (MimeMessage) mimeMessage;
- return message.getMessageID();
- }
-
- private boolean getReplySign() throws Exception {
-
- return getReplySign(this.currentMessage);
- }
-
-
-
-
-
-
-
-
- private boolean getReplySign(Message mimeMessage) throws Exception {
-
- boolean replaysign = false;
- String[] needreply = (String[]) mimeMessage
- .getHeader("Disposition-Notification-To");
- if (needreply != null) {
- replaysign = true;
- }
- return replaysign;
- }
-
- private boolean isNew() throws Exception {
-
- return isNew(this.currentMessage);
- }
-
-
-
-
-
-
-
-
- private boolean isNew(Message mimeMessage) throws Exception {
-
- boolean isnew = false;
- Flags flags = mimeMessage.getFlags();
- Flags.Flag[] flag = flags.getSystemFlags();
- for (int i = 0; i < flag.length; i++) {
- if (flag[i] == Flags.Flag.SEEN) {
- isnew = true;
- break;
- }
- }
- return false;
- }
-
- private Data getSentDate() throws Exception {
-
- return getSetDate(this.currentMessage);
- }
-
-
-
-
-
-
-
-
- private Data getSetDate(Message mimeMessage) throws Exception {
-
- return (Data) mimeMessage.getSentDate();
- }
-
-
-
-
-
-
-
- private String getSubject() throws Exception {
- return getSubject(this.currentMessage);
- }
-
- private String getSubject(Message mimeMessage) throws Exception {
-
- String subject = "";
- try {
- subject = MimeUtility.decodeText(mimeMessage.getSubject());
- if (subject == null) {
- subject = "";
- }
- } catch (Exception e) {
- }
- return subject;
- }
-
-
-
-
-
-
-
- private String getFrom() throws Exception {
- return getFrom(this.currentMessage);
- }
-
-
-
-
-
-
-
- private String getFrom(Message mimeMessage) throws Exception {
- InternetAddress[] address = (InternetAddress[]) mimeMessage.getFrom();
-
- String from = address[0].getAddress();
- if (from == null) {
- from = "";
- }
-
- String personal = address[0].getPersonal();
- if (personal == null) {
- personal = "";
- }
- String fromaddr = personal + "<" + from + ">";
- return fromaddr;
- }
-
-
-
-
-
-
-
- private String getBCCAddress() throws Exception {
-
- return getMailAddress("BCC", this.currentMessage);
- }
-
- private String getCCAddress() throws Exception {
-
- return getMailAddress("CC", this.currentMessage);
- }
-
- private String getToAddress() throws Exception {
-
- return getMailAddress("TO", this.currentMessage);
- }
-
-
-
-
-
-
-
-
-
-
-
- private String getMailAddress(String type, Message mimeMessage)
- throws Exception {
- String mailaddr = "";
- String addtype = type.toUpperCase();
- InternetAddress[] address = null;
- if (addtype.equals("TO") || addtype.equals("CC")
- || addtype.equals("BCC")) {
- if (addtype.equals("TO")) {
- address = (InternetAddress[]) mimeMessage
- .getRecipients(Message.RecipientType.TO);
- }
- if (addtype.equals("CC")) {
- address = (InternetAddress[]) mimeMessage
- .getRecipients(Message.RecipientType.CC);
- }
- if (addtype.equals("BCC")) {
- address = (InternetAddress[]) mimeMessage
- .getRecipients(Message.RecipientType.BCC);
- }
- if (address != null) {
- for (int i = 0; i < address.length; i++) {
-
- String email = address[i].getAddress();
- if (email == null) {
- email = "";
- } else {
- email = MimeUtility.decodeText(email);
- }
-
- String personal = address[i].getPersonal();
- if (personal == null) {
- personal = "";
- } else {
- personal = MimeUtility.decodeText(personal);
- }
-
- String compostiteto = personal + "<" + email + ">";
-
- mailaddr += "," + compostiteto;
- }
- mailaddr = mailaddr.substring(1);
- }
- } else {
- throw new Exception("错误的地址类型");
- }
- return mailaddr;
- }
-
-
-
-
-
-
- private int getMessageCount() {
-
- return this.messages.length;
- }
-
-
-
-
-
-
-
- private int getUnreadMessageConunt() throws MessagingException {
-
- return this.folder.getUnreadMessageCount();
- }
-
-
-
-
-
-
-
- private int getNewMessageCount() throws MessagingException {
-
- return this.folder.getNewMessageCount();
- }
-
-
-
-
-
-
-
- private void getMail() throws Exception {
- this.saveMessageAsFile(this.currentMessage);
- this.parseMessage(this.currentMessage);
- }
-
-
-
-
-
-
-
-
- private void parseMessage(Message message) throws IOException,
- MessagingException {
- Object content = message.getContent();
- if (content instanceof Multipart) {
- handleMultipart((Multipart) content);
- } else {
- handlePart(message);
- }
-
- }
-
-
-
-
-
-
-
-
- private void handleMultipart(Multipart multipart)
- throws MessagingException, IOException {
- for (int i = 0, n = multipart.getCount(); i < n; i++) {
- handlePart(multipart.getBodyPart(i));
- }
-
- }
-
-
-
-
-
-
-
- private void handlePart(Part part) throws MessagingException, IOException {
- String dispostion = part.getDisposition();
- String contentType = part.getContentType();
- String fileNameWidthExtension = "";
-
- InputStreamReader sbis = new InputStreamReader(part.getInputStream());
-
- if (dispostion == null) {
- if ((contentType.length() >= 10)
- && (contentType.toLowerCase().substring(0, 10)
- .equals("text/plain"))) {
- fileNameWidthExtension = this.receiverInfo.getAttchmentDir()
- + this.currentEmailFileName + ".txt";
- } else if ((contentType.length() >= 9)
- && (contentType.toLowerCase().substring(0, 9)
- .equals("text/html"))) {
- fileNameWidthExtension = this.receiverInfo.getAttchmentDir()
- + this.currentEmailFileName + ".html";
- } else if ((contentType.length() >= 9)
- && (contentType.toLowerCase().substring(0, 9)
- .equals("text/gif"))) {
- fileNameWidthExtension = this.receiverInfo.getAttchmentDir()
- + this.currentEmailFileName + ".gif";
- } else if ((contentType.length() >= 9)
- && (contentType.toLowerCase().substring(0, 9)
- .equals("multipart/*"))) {
- handleMultipart((Multipart) part.getContent());
- } else {
- fileNameWidthExtension = this.receiverInfo.getAttchmentDir()
- + this.currentEmailFileName + ".txt";
- }
- System.out.println("保存邮件内容到:" + fileNameWidthExtension);
- saveFile(fileNameWidthExtension, sbis);
- return;
- }
-
- String name = "";
- if (dispostion.equalsIgnoreCase(Part.ATTACHMENT)) {
- name = getFileName(part);
- fileNameWidthExtension = this.receiverInfo.getAttchmentDir() + name;
- } else if (dispostion.equalsIgnoreCase(Part.INLINE)) {
- name = getFileName(part);
- fileNameWidthExtension = this.receiverInfo.getAttchmentDir() + name;
- } else {
-
- }
-
-
- if (!fileNameWidthExtension.equals("")) {
- System.out.println("保存邮件附件到:" + fileNameWidthExtension);
- saveFile(fileNameWidthExtension, sbis);
- }
-
- }
-
- private String getFileName(Part part) throws UnsupportedEncodingException,
- MessagingException {
- String fileName = part.getFileName();
- fileName = MimeUtility.decodeText(fileName);
- String name = fileName;
- if (fileName != null) {
- int index = fileName.lastIndexOf("/");
- if (index != -1) {
- name = fileName.substring(index + 1);
- }
- }
- return name;
- }
-
- /***************************************************************************
- * 保存邮件源文件
- *
- * @param currentMessage2
- */
- private void saveMessageAsFile(Message message) {
- try {
-
- String oriFileName = getInfoBetweenBrackets(this.getMessageId(
- message).toString());
-
- String emlName = oriFileName;
- String fileNameWidthExtension = this.receiverInfo.getEmailDir()
- + oriFileName + this.receiverInfo.getEmailFileSuffix();
- File storeFile = new File(fileNameWidthExtension);
- for (int i = 0; storeFile.exists(); i++) {
- emlName = oriFileName + i;
- fileNameWidthExtension = this.receiverInfo.getEmailDir()
- + emlName + this.receiverInfo.getEmailFileSuffix();
- storeFile = new File(fileNameWidthExtension);
- }
- this.currentEmailFileName = emlName;
- System.out.println("邮件消息的存储路径:" + fileNameWidthExtension);
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- message.writeTo(baos);
- StringReader in = new StringReader(baos.toString());
- saveFile(fileNameWidthExtension, in);
-
- } catch (Exception e) {
-
- e.printStackTrace();
- }
-
- }
-
-
-
-
-
-
-
-
- private void saveFile(String fileName, Reader in) throws IOException {
-
- File file = new File(fileName);
-
- int lastDot = fileName.lastIndexOf(".");
- String extension = fileName.substring(lastDot);
- fileName = fileName.substring(0, lastDot);
- for (int i = 0; file.exists(); i++) {
- file = new File(fileName + i + extension);
- }
-
- FileWriter fos = new FileWriter(file);
- BufferedWriter bos = new BufferedWriter(fos);
- BufferedReader bis = new BufferedReader(in);
- int aByte;
- while ((aByte = bis.read()) != -1) {
- bos.write(aByte);
- }
- bos.flush();
- bos.close();
- bis.close();
- }
-
-
-
-
-
-
-
- private String getInfoBetweenBrackets(String str) {
- int i, j;
- if (str == null) {
- str = "error";
- return str;
- }
- i = str.lastIndexOf("<");
- j = str.lastIndexOf(">");
- if (i != 1 && j != -1) {
- str = str.substring(i + 1, j);
- }
- return str;
- }
-
- public static void main(String[] args) throws Exception {
- MailReceiverInfo info = new MailReceiverInfo();
- info.setMailServerHost("pop.163.com");
- info.setMailServerPost("110");
- info.setVaildate(true);
- info.setUserName("*************");
- info.setPassWord("*************");
- info.setAttchmentDir("F:/mails");
- info.setEmailDir("F:/mails");
-
- MailReceiver receiver = new MailReceiver(info);
-
- receiver.receiveAllMail();
- }
- }
|