JavaMail详解(四)——邮件验证和读取 - 高飞网
137 人阅读

JavaMail详解(四)——邮件验证和读取

2016-11-22 15:00:56

    在学习本节之前,要先了解两个概念:验证(Check)和读取(Fetch)。

    在JavaMail中验证邮件,是在打开邮件各个文件夹并获取各个消息的一个过程。这时我们仅仅验证每个邮件消息的头部,如From、To、Subject。而内容不会读取。

    在JavaMail中读取邮件,是在打开各个文件夹并获取消息的过程,除了邮件的头部,还会根据识别的邮件类型来读取邮件内容。

    在JavaMail API中,验证或读取邮件,我们需要使用POP和IMAP服务。要验证和读取邮件,需要使用Folder和Store类。这里使用163的POP3服务。先学习用JavaMail如何验证邮件。

  1. 获取会话(Session)
  2. 创建pop3 Store对象和到pop服务的连接
  3. 创建Folder对象,打开邮件中相应的文件夹。
  4. 获取消息
  5. 关闭Store和Folder对象。


import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class CheckingMails {
    public static void check(String host, String storeType, String user, String password) {
        try {

            Properties properties = new Properties();

            properties.put("mail.pop3.host", host);
            properties.put("mail.pop3.port", "995");
            properties.put("mail.pop3.starttls.enable", "true");
            Session emailSession = Session.getDefaultInstance(properties);

            // 创建POP3 Sotre对象并连接到pop服务
            Store store = emailSession.getStore("pop3s");

            store.connect(host, user, password);

            // 创建Folder对象并打开它
            Folder emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_ONLY);

            // 从文件夹中以数组的形式读取消息并打印出来
            Message[] messages = emailFolder.getMessages();
            System.out.println("messages.length---" + messages.length);

            for (int i = 0, n = messages.length; i < n; i++) {
                Message message = messages[i];
                System.out.println("---------------------------------");
                System.out.println("Email Number " + (i + 1));
                System.out.println("Subject: " + message.getSubject());
                System.out.println("From: " + message.getFrom()[0]);
                System.out.println("Text: " + message.getContent().toString());

            }

            //关闭Store和Folder对象
            emailFolder.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        String host = "pop.163.com";// change accordingly
        String mailStoreType = "pop3";
        String username = "xxxxxxxt@163.com";// change accordingly
        String password = "xxxxxxx";// change accordingly

        check(host, mailStoreType, username, password);

    }
}


    接下来看如何读取每个邮件内容,下面的示例将展示怎么读取简单邮件、含附件的邮件和内嵌图片的邮件。

    基本的步骤有:

  1. 获取会话Session对象
  2. 创建POP3 Store对象并连接到服务
  3. 创建Folder对象并打开邮件的各个文件夹
  4. 读取消息
  5. 关闭folder和store对象


import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
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;

public class FetchingEmail {
    public static void fetch(String pop3Host, String storeType, String user, String password) {
        try {
            // create properties field
            Properties properties = new Properties();
            properties.put("mail.store.protocol", "pop3");
            properties.put("mail.pop3.host", pop3Host);
            properties.put("mail.pop3.port", "995");
            properties.put("mail.pop3.starttls.enable", "true");
            Session emailSession = Session.getDefaultInstance(properties);
            // emailSession.setDebug(true);

            // 创建POP3 Sotre对象并连接到pop服务
            Store store = emailSession.getStore("pop3s");

            store.connect(pop3Host, user, password);

            // 创建Folder对象并打开它
            Folder emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_ONLY);

            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

            // 从文件夹中以数组的形式读取消息并打印出来
            Message[] messages = emailFolder.getMessages();
            System.out.println("messages.length---" + messages.length);

            for (int i = 0; i < messages.length; i++) {
                Message message = messages[i];
                System.out.println("---------------------------------");
                writePart(message);
                String line = reader.readLine();
                if ("YES".equals(line)) {
                    message.writeTo(System.out);
                } else if ("QUIT".equals(line)) {
                    break;
                }
            }

            // 关闭Store和Folder对象
            emailFolder.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        String host = "pop.163.com";// change accordingly
        String mailStoreType = "pop3";
        String username = "xxxxxxx@163.com";// change accordingly
        String password = "xxxxxxx";// change accordingly

        // Call method fetch
        fetch(host, mailStoreType, username, password);

    }

    /*
     * 该方法基本每个邮件的内容类型来检查,处理和读取消息内容
     */
    public static void writePart(Part p) throws Exception {
            if (p instanceof Message)
               writeEnvelope((Message) p);

            System.out.println("----------------------------");
            System.out.println("CONTENT-TYPE: " + p.getContentType());

            //检查内容是否为纯文本
            if (p.isMimeType("text/plain")) {
               System.out.println("This is plain text");
               System.out.println("---------------------------");
               System.out.println((String) p.getContent());
            } 
            //检查内容是否含有附件
            else if (p.isMimeType("multipart/*")) {
               System.out.println("This is a Multipart");
               System.out.println("---------------------------");
               Multipart mp = (Multipart) p.getContent();
               int count = mp.getCount();
               for (int i = 0; i < count; i++)
                  writePart(mp.getBodyPart(i));
            } 
            //检查内容是否含有嵌套消息
            else if (p.isMimeType("message/rfc822")) {
               System.out.println("This is a Nested Message");
               System.out.println("---------------------------");
               writePart((Part) p.getContent());
            } 
            //检查内容是否为内嵌图片
            else if (p.isMimeType("image/jpeg")) {
               System.out.println("--------> image/jpeg");
               Object o = p.getContent();

               InputStream x = (InputStream) o;
               // Construct the required byte array
               System.out.println("x.length = " + x.available());
               int i = 0;
               byte[] bArray = new byte[x.available()];
               while ((i = (int) ((InputStream) x).available()) > 0) {
                  int result = (int) (((InputStream) x).read(bArray));
                  if (result == -1)
                  break;
               }
               FileOutputStream f2 = new FileOutputStream("/tmp/image.jpg");
               f2.write(bArray);
               f2.close();
               x.close();
            } 
            else if (p.getContentType().contains("image/")) {
               System.out.println("content type" + p.getContentType());
               File f = new File("image" + new Date().getTime() + ".jpg");
               DataOutputStream output = new DataOutputStream(
                  new BufferedOutputStream(new FileOutputStream(f)));
                  com.sun.mail.util.BASE64DecoderStream test = 
                       (com.sun.mail.util.BASE64DecoderStream) p
                        .getContent();
               byte[] buffer = new byte[1024];
               int bytesRead;
               while ((bytesRead = test.read(buffer)) != -1) {
                  output.write(buffer, 0, bytesRead);
               }
            } 
            else {
               Object o = p.getContent();
               if (o instanceof String) {
                  System.out.println("This is a string");
                  System.out.println("---------------------------");
                  System.out.println((String) o);
               } 
               else if (o instanceof InputStream) {
                  System.out.println("This is just an input stream");
                  System.out.println("---------------------------");
                  InputStream is = (InputStream) o;
                  int c;
                  while ((c = is.read()) != -1){
                      System.out.write(c);
                  }
                  is.close();
               } 
               else {
                  System.out.println("This is an unknown type");
                  System.out.println("---------------------------");
                  System.out.println(o.toString());
               }
            }

         }

    /*
     * 该方法打印消息信封,如发信人FROM、收信人TO和主题SUBJECT
     */
    public static void writeEnvelope(Message m) throws Exception {
        System.out.println("This is the message envelope");
        System.out.println("---------------------------");
        Address[] a;

        // FROM
        if ((a = m.getFrom()) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("FROM: " + a[j].toString());
        }

        // TO
        if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++)
                System.out.println("TO: " + a[j].toString());
        }

        // SUBJECT
        if (m.getSubject() != null)
            System.out.println("SUBJECT: " + m.getSubject());

    }
}



还没有评论!
54.147.247.194