SpringBoot javax獲取郵件內容,刪除郵件、根據時間段篩選郵件,篩選時間段+未讀郵件


導讀

  最近負責整個消息網關微服務,短信已經實現退訂功能(點我直達),客戶那要求郵件也要實現郵件退訂功能。因為郵件不能像短信一樣可以實時監聽,只能寫個定時任務,設計2套方案。

  方案一:操作完的郵件,將讀取到的內容,記錄到數據庫中,並將郵件刪掉

  方案二:根據時間段,比如只獲取24小時內未讀的郵件

添加依賴

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>
        <!--javax郵件依賴-->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>javax.mail-api</artifactId>
            <version>1.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.5.5</version>
        </dependency>

方案一(pop3)

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class StoreMail {
    final static String USER = "543210188@qq.com"; // 用戶名
    final static String PASSWORD = "xxxxx"; // 密碼
    public final static String MAIL_SERVER_HOST = "smtp.qq.com"; // 郵箱服務器

    public static void main(String[] args) throws Exception {
        // 創建一個有具體連接信息的Properties對象
        Properties prop = new Properties();
        prop.setProperty("mail.debug", "true");
        prop.setProperty("mail.store.protocol", "pop3");

        prop.setProperty("mail.pop3.host", MAIL_SERVER_HOST);
        // 1、創建session
        Session session = Session.getInstance(prop);
        // 2、通過session得到Store對象
        Store store = session.getStore();
        // 3、連上郵件服務器
        store.connect(MAIL_SERVER_HOST, USER, PASSWORD);
        // 4、獲得郵箱內的郵件夾
        Folder folder = store.getFolder("inbox");
        //只讀
//        folder.open(Folder.READ_ONLY);
        //讀寫
        folder.open(Folder.READ_WRITE);
        // 獲得郵件夾Folder內的所有郵件Message對象
        Message[] messages = folder.getMessages();
        // 解析所有郵件
        for (int i = 0, count = messages.length; i < count; i++) {
            MimeMessage msg = (MimeMessage) messages[i];
            System.out.println("------------------解析第" + msg.getMessageNumber() + "封郵件-------------------- ");
            System.out.println("主題: " + getSubject(msg));
            System.out.println("發件人: " + getFrom(msg));
            System.out.println("收件人:" + getReceiveAddress(msg, null));
            System.out.println("發送時間:" + getSentDate(msg, null));
            System.out.println("是否已讀:" + isSeen(msg));
            System.out.println("郵件優先級:" + getPriority(msg));
            System.out.println("是否需要回執:" + isReplySign(msg));
            System.out.println("郵件大小:" + msg.getSize() * 1024 + "kb");
            boolean isContainerAttachment = isContainAttachment(msg);
            System.out.println("是否包含附件:" + isContainerAttachment);
            if (isContainerAttachment) {
                saveAttachment(msg, "f:\\mailTest\\"+msg.getSubject() + "_"+i+"_"); //保存附件
            }
            if (i == 2) {
                //刪除郵件
                msg.setFlag(Flags.Flag.DELETED, true);
                System.out.println("刪除");
            }
            StringBuffer content = new StringBuffer(30);
            getMailTextContent(msg, content);
            System.out.println("郵件正文:" + content);
            System.out.println("------------------第" + msg.getMessageNumber() + "封郵件解析結束-------------------- ");
            System.out.println();

        }
        // 5、關閉
        folder.close(true);
        store.close();
    }

    /**
     * 刪除郵件
     *
     * @param messages 要解析的郵件列表
     */
    public static void deleteMessage(Message... messages) throws MessagingException, IOException {
        if (messages == null || messages.length < 1)
            throw new MessagingException("未找到要解析的郵件!");

        // 解析所有郵件
        for (int i = 0, count = messages.length; i < count; i++) {

            /**
             *   郵件刪除
             */
            Message message = messages[i];
            String subject = message.getSubject();
            // set the DELETE flag to true
            message.setFlag(Flags.Flag.DELETED, true);
            System.out.println("Marked DELETE for message: " + subject);


        }
    }

    /**
     * 獲得郵件主題
     *
     * @param msg 郵件內容
     * @return 解碼后的郵件主題
     */
    public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
        return MimeUtility.decodeText(msg.getSubject());
    }

    /**
     * 獲得郵件發件人
     *
     * @param msg 郵件內容
     * @return 姓名 <Email地址>
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
        String from = "";
        Address[] froms = msg.getFrom();
        if (froms.length < 1)
            throw new MessagingException("沒有發件人!");

        InternetAddress address = (InternetAddress) froms[0];
        String person = address.getPersonal();
        if (person != null) {
            person = MimeUtility.decodeText(person) + " ";
        } else {
            person = "";
        }
        from = person + "<" + address.getAddress() + ">";

        return from;
    }

    /**
     * 根據收件人類型,獲取郵件收件人、抄送和密送地址。如果收件人類型為空,則獲得所有的收件人
     * <p>Message.RecipientType.TO  收件人</p>
     * <p>Message.RecipientType.CC  抄送</p>
     * <p>Message.RecipientType.BCC 密送</p>
     *
     * @param msg  郵件內容
     * @param type 收件人類型
     * @return 收件人1 <郵件地址1>, 收件人2 <郵件地址2>, ...
     * @throws MessagingException
     */
    public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
        StringBuffer receiveAddress = new StringBuffer();
        Address[] addresss = null;
        if (type == null) {
            addresss = msg.getAllRecipients();
        } else {
            addresss = msg.getRecipients(type);
        }

        if (addresss == null || addresss.length < 1)
            throw new MessagingException("沒有收件人!");
        for (Address address : addresss) {
            InternetAddress internetAddress = (InternetAddress) address;
            receiveAddress.append(internetAddress.toUnicodeString()).append(",");
        }

        receiveAddress.deleteCharAt(receiveAddress.length() - 1); //刪除最后一個逗號

        return receiveAddress.toString();
    }

    /**
     * 獲得郵件發送時間
     *
     * @param msg 郵件內容
     * @return yyyy年mm月dd日 星期X HH:mm
     * @throws MessagingException
     */
    public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
        Date receivedDate = msg.getSentDate();
        if (receivedDate == null)
            return "";

        if (pattern == null || "".equals(pattern))
            pattern = "yyyy年MM月dd日 E HH:mm ";

        return new SimpleDateFormat(pattern).format(receivedDate);
    }

    /**
     * 判斷郵件中是否包含附件
     *
     * @return 郵件中存在附件返回true,不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
        boolean flag = false;
        if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("application") != -1) {
                        flag = true;
                    }

                    if (contentType.indexOf("name") != -1) {
                        flag = true;
                    }
                }

                if (flag) break;
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = isContainAttachment((Part) part.getContent());
        }
        return flag;
    }

    /**
     * 判斷郵件是否已讀
     *
     * @param msg 郵件內容
     * @return 如果郵件已讀返回true, 否則返回false
     * @throws MessagingException
     */
    public static boolean isSeen(MimeMessage msg) throws MessagingException {
        return msg.getFlags().contains(Flags.Flag.SEEN);
    }

    /**
     * 判斷郵件是否需要閱讀回執
     *
     * @param msg 郵件內容
     * @return 需要回執返回true, 否則返回false
     * @throws MessagingException
     */
    public static boolean isReplySign(MimeMessage msg) throws MessagingException {
        boolean replySign = false;
        String[] headers = msg.getHeader("Disposition-Notification-To");
        if (headers != null)
            replySign = true;
        return replySign;
    }

    /**
     * 獲得郵件的優先級
     *
     * @param msg 郵件內容
     * @return 1(High):緊急  3:普通(Normal)  5:低(Low)
     * @throws MessagingException
     */
    public static String getPriority(MimeMessage msg) throws MessagingException {
        String priority = "普通";
        String[] headers = msg.getHeader("X-Priority");
        if (headers != null) {
            String headerPriority = headers[0];
            if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1)
                priority = "緊急";
            else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1)
                priority = "低";
            else
                priority = "普通";
        }
        return priority;
    }

    /**
     * 獲得郵件文本內容
     *
     * @param part    郵件體
     * @param content 存儲郵件文本內容的字符串
     * @throws MessagingException
     * @throws IOException
     */
    public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
        //如果是文本類型的附件,通過getContent方法可以取到文本內容,但這不是我們需要的結果,所以在這里要做判斷
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part) part.getContent(), content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart, content);
            }
        }
    }

    /**
     * 保存附件
     *
     * @param part    郵件中多個組合體中的其中一個組合體
     * @param destDir 附件保存目錄
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
            FileNotFoundException, IOException {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //復雜體郵件
            //復雜體郵件包含多個郵件體
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                //獲得復雜體郵件中其中一個郵件體
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一個郵件體也有可能是由多個郵件體組成的復雜體
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();
                    saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart, destDir);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(), destDir);
        }
    }

    /**
     * 讀取輸入流中的數據保存至指定目錄
     *
     * @param is       輸入流
     * @param fileName 文件名
     * @param destDir  文件存儲目錄
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void saveFile(InputStream is, String destDir, String fileName)
            throws FileNotFoundException, IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(new File(destDir + fileName)));
        int len = -1;
        while ((len = bis.read()) != -1) {
            bos.write(len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }

    /**
     * 文本解碼
     *
     * @param encodeText 解碼MimeUtility.encodeText(String text)方法編碼后的文本
     * @return 解碼后的文本
     * @throws UnsupportedEncodingException
     */
    public static String decodeText(String encodeText) throws UnsupportedEncodingException {
        if (encodeText == null || "".equals(encodeText)) {
            return "";
        } else {
            return MimeUtility.decodeText(encodeText);
        }
    }
}

根據時間篩選

        DateTerm dateTerm = new DateTerm(3, new Date(1617869155000L)) {
            @Override
            public boolean match(Message msg) {
                try {
                    Date receivedDate = msg.getReceivedDate();
                    return this.date.before(msg.getSentDate());
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
                return false;
            }
        };
        Message[] messages = folder.search(dateTerm);

注意

  new DateTerm第一個參數,對應關系如下

方案二(imap)

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.search.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class StoreMail {
    final static String USER = "543210188@qq.com"; // 用戶名
    final static String PASSWORD = "xxxxx"; // 密碼
    public final static String MAIL_SERVER_HOST = "smtp.qq.com"; // 郵箱服務器

    public static void main(String[] args) throws Exception {
        // 創建一個有具體連接信息的Properties對象
        Properties prop = new Properties();
        prop.setProperty("mail.debug", "true");
        prop.setProperty("mail.store.protocol", "imap");
        prop.setProperty("mail.pop3.host", MAIL_SERVER_HOST);
        // 1、創建session
        Session session = Session.getInstance(prop);
        // 2、通過session得到Store對象
        Store store = session.getStore();
        // 3、連上郵件服務器
        store.connect(MAIL_SERVER_HOST, USER, PASSWORD);
        // 4、獲得郵箱內的郵件夾
        Folder folder = store.getFolder("inbox");
        //只讀
//        folder.open(Folder.READ_ONLY);
        //讀寫
        folder.open(Folder.READ_WRITE);
        // 獲得郵件夾Folder內的所有郵件Message對象
        //1617869155000  =====> 2021-04-08 16:05:55
        DateTerm dateTerm = new DateTerm(3, new Date(1617869155000L)) {
            @Override
            public boolean match(Message msg) {
                try {
                    return this.date.before(msg.getSentDate());
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
                return false;
            }
        };
        // FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); //false代表未讀,true代表已讀
        FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
        AndTerm andTerm = new AndTerm(dateTerm, flagTerm);
        //根據條件過濾
        Message[] messages = folder.search(andTerm);
//        Message[] messages = folder.getMessages();
        // 解析所有郵件
        for (int i = 0, count = messages.length; i < count; i++) {
            MimeMessage msg = (MimeMessage) messages[i];
            System.out.println("------------------解析第" + msg.getMessageNumber() + "封郵件-------------------- ");
            System.out.println("主題: " + getSubject(msg));
            System.out.println("發件人: " + getFrom(msg));
            System.out.println("收件人:" + getReceiveAddress(msg, null));
            System.out.println("發送時間:" + getSentDate(msg, null));
            System.out.println("是否已讀:" + isSeen(msg));
            System.out.println("郵件優先級:" + getPriority(msg));
            System.out.println("是否需要回執:" + isReplySign(msg));
            System.out.println("郵件大小:" + msg.getSize() * 1024 + "kb");
            boolean isContainerAttachment = isContainAttachment(msg);
            System.out.println("是否包含附件:" + isContainerAttachment);
            //設置當前郵件狀態為已讀
            msg.setFlag(Flags.Flag.SEEN, true);
            StringBuffer content = new StringBuffer(30);
            getMailTextContent(msg, content);
            System.out.println("郵件正文:" + content);
            System.out.println("------------------第" + msg.getMessageNumber() + "封郵件解析結束-------------------- ");
            System.out.println();

        }
        // 5、關閉
        folder.close(true);
        store.close();
    }

    /**
     * 刪除郵件
     *
     * @param messages 要解析的郵件列表
     */
    public static void deleteMessage(Message... messages) throws MessagingException, IOException {
        if (messages == null || messages.length < 1)
            throw new MessagingException("未找到要解析的郵件!");

        // 解析所有郵件
        for (int i = 0, count = messages.length; i < count; i++) {

            /**
             *   郵件刪除
             */
            Message message = messages[i];
            String subject = message.getSubject();
            // set the DELETE flag to true
            message.setFlag(Flags.Flag.DELETED, true);
            System.out.println("Marked DELETE for message: " + subject);


        }
    }

    /**
     * 獲得郵件主題
     *
     * @param msg 郵件內容
     * @return 解碼后的郵件主題
     */
    public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
        return MimeUtility.decodeText(msg.getSubject());
    }

    /**
     * 獲得郵件發件人
     *
     * @param msg 郵件內容
     * @return 姓名 <Email地址>
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
        String from = "";
        Address[] froms = msg.getFrom();
        if (froms.length < 1)
            throw new MessagingException("沒有發件人!");

        InternetAddress address = (InternetAddress) froms[0];
        String person = address.getPersonal();
        if (person != null) {
            person = MimeUtility.decodeText(person) + " ";
        } else {
            person = "";
        }
        from = person + "<" + address.getAddress() + ">";

        return from;
    }

    /**
     * 根據收件人類型,獲取郵件收件人、抄送和密送地址。如果收件人類型為空,則獲得所有的收件人
     * <p>Message.RecipientType.TO  收件人</p>
     * <p>Message.RecipientType.CC  抄送</p>
     * <p>Message.RecipientType.BCC 密送</p>
     *
     * @param msg  郵件內容
     * @param type 收件人類型
     * @return 收件人1 <郵件地址1>, 收件人2 <郵件地址2>, ...
     * @throws MessagingException
     */
    public static String getReceiveAddress(MimeMessage msg, Message.RecipientType type) throws MessagingException {
        StringBuffer receiveAddress = new StringBuffer();
        Address[] addresss = null;
        if (type == null) {
            addresss = msg.getAllRecipients();
        } else {
            addresss = msg.getRecipients(type);
        }

        if (addresss == null || addresss.length < 1)
            throw new MessagingException("沒有收件人!");
        for (Address address : addresss) {
            InternetAddress internetAddress = (InternetAddress) address;
            receiveAddress.append(internetAddress.toUnicodeString()).append(",");
        }

        receiveAddress.deleteCharAt(receiveAddress.length() - 1); //刪除最后一個逗號

        return receiveAddress.toString();
    }

    /**
     * 獲得郵件發送時間
     *
     * @param msg 郵件內容
     * @return yyyy年mm月dd日 星期X HH:mm
     * @throws MessagingException
     */
    public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
        Date receivedDate = msg.getSentDate();
        if (receivedDate == null)
            return "";

        if (pattern == null || "".equals(pattern))
            pattern = "yyyy年MM月dd日 E HH:mm ";

        return new SimpleDateFormat(pattern).format(receivedDate);
    }

    /**
     * 判斷郵件中是否包含附件
     *
     * @return 郵件中存在附件返回true,不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
        boolean flag = false;
        if (part.isMimeType("multipart/*")) {
            MimeMultipart multipart = (MimeMultipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    flag = true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    flag = isContainAttachment(bodyPart);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("application") != -1) {
                        flag = true;
                    }

                    if (contentType.indexOf("name") != -1) {
                        flag = true;
                    }
                }

                if (flag) break;
            }
        } else if (part.isMimeType("message/rfc822")) {
            flag = isContainAttachment((Part) part.getContent());
        }
        return flag;
    }

    /**
     * 判斷郵件是否已讀
     *
     * @param msg 郵件內容
     * @return 如果郵件已讀返回true, 否則返回false
     * @throws MessagingException
     */
    public static boolean isSeen(MimeMessage msg) throws MessagingException {
        return msg.getFlags().contains(Flags.Flag.SEEN);
    }

    /**
     * 判斷郵件是否需要閱讀回執
     *
     * @param msg 郵件內容
     * @return 需要回執返回true, 否則返回false
     * @throws MessagingException
     */
    public static boolean isReplySign(MimeMessage msg) throws MessagingException {
        boolean replySign = false;
        String[] headers = msg.getHeader("Disposition-Notification-To");
        if (headers != null)
            replySign = true;
        return replySign;
    }

    /**
     * 獲得郵件的優先級
     *
     * @param msg 郵件內容
     * @return 1(High):緊急  3:普通(Normal)  5:低(Low)
     * @throws MessagingException
     */
    public static String getPriority(MimeMessage msg) throws MessagingException {
        String priority = "普通";
        String[] headers = msg.getHeader("X-Priority");
        if (headers != null) {
            String headerPriority = headers[0];
            if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1)
                priority = "緊急";
            else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1)
                priority = "低";
            else
                priority = "普通";
        }
        return priority;
    }

    /**
     * 獲得郵件文本內容
     *
     * @param part    郵件體
     * @param content 存儲郵件文本內容的字符串
     * @throws MessagingException
     * @throws IOException
     */
    public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
        //如果是文本類型的附件,通過getContent方法可以取到文本內容,但這不是我們需要的結果,所以在這里要做判斷
        boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part) part.getContent(), content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart, content);
            }
        }
    }

    /**
     * 保存附件
     *
     * @param part    郵件中多個組合體中的其中一個組合體
     * @param destDir 附件保存目錄
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
            FileNotFoundException, IOException {
        if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();    //復雜體郵件
            //復雜體郵件包含多個郵件體
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                //獲得復雜體郵件中其中一個郵件體
                BodyPart bodyPart = multipart.getBodyPart(i);
                //某一個郵件體也有可能是由多個郵件體組成的復雜體
                String disp = bodyPart.getDisposition();
                if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                    InputStream is = bodyPart.getInputStream();
                    saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart, destDir);
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                        saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(), destDir);
        }
    }

    /**
     * 讀取輸入流中的數據保存至指定目錄
     *
     * @param is       輸入流
     * @param fileName 文件名
     * @param destDir  文件存儲目錄
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void saveFile(InputStream is, String destDir, String fileName)
            throws FileNotFoundException, IOException {
        BufferedInputStream bis = new BufferedInputStream(is);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(new File(destDir + fileName)));
        int len = -1;
        while ((len = bis.read()) != -1) {
            bos.write(len);
            bos.flush();
        }
        bos.close();
        bis.close();
    }

    /**
     * 文本解碼
     *
     * @param encodeText 解碼MimeUtility.encodeText(String text)方法編碼后的文本
     * @return 解碼后的文本
     * @throws UnsupportedEncodingException
     */
    public static String decodeText(String encodeText) throws UnsupportedEncodingException {
        if (encodeText == null || "".equals(encodeText)) {
            return "";
        } else {
            return MimeUtility.decodeText(encodeText);
        }
    }
}

pop3與imap區別

1)pop3允許電子郵件客戶端請求下載指定郵件服務器上指定用戶的郵件信息,但是在用戶的客戶端所做的任何操作都是不會反饋到服務器上的,也就是說,你已讀了郵件在郵件服務器上的狀態還是未讀取的,這在很多情況下對用戶來說是不方便的。這是因為pop3協議是單向協議

2)IAMP協議,雙向協議,用戶在客戶端的操作可以實時的反饋到服務器上,用戶對郵件的任何操作,服務器也會做出相應的操作。

    同時:IMAP還可以指定下載郵件的某些內容。

  所以POP3協議無法獲取郵件狀態(已讀或未讀)
  IMAP協議不支持 中文主題 或 中文內容 郵件過濾,而POP3完全支持

篩選條件

  JavaMail在javax.mail.search包中定義了一個用於創建搜索條件的SearchTerm類,應用程序創建SearchTerm類的實例對象后,就可以調用Folder.Search(SearchTerm st)方法搜索郵件夾中符合搜索條件的所有郵件。SearchTerm是一個抽象類,JavaMail提供了22個實現子類以幫助應用程序創建不同的搜索條件,這22個類可分為兩大類型,如下所示:

1、用於創建邏輯組合關系的類

AND條件(AndTerm類)
OR條件(OrTerm類)
NOT條件(NotTerm類)
Comparison條件(ComparisonTerm類)
2、用於創建具體搜索條件的類

DATE條件(SentDateTerm、ReceivedDateTerm類)
CONTENT條件(BodyTerm類)
HEADER條件(FromStringTerm、RecipientStringTerm、SubjectTerm類等)
下面通過實現來說明以上類的用法及含義:

1、搜索發件人為“智聯招聘“,而且郵件正文包含“Java工程師“的所有郵件

SearchTerm andTerm = new AndTerm( new FromStringTerm("智聯招聘"), new BodyTerm("java工程師"));

Message[] messages = folder.search(andTerm); 

2、搜索發件人為“智聯招聘“或主題包含“最新職位信息“的所有郵件

SearchTerm orTerm = new OrTerm( new FromStringTerm("智聯招聘"), new SubjectTerm("最新職位信息"));

Message[] messages = folder.search(orTerm); 

3、搜索周一到今天收到的的所有郵件

Calendar calendar = Calendar.getInstance();  
calendar.set(Calendar.DAY_OF_WEEK, calendar.get(Calendar.DAY_OF_WEEK - (Calendar.DAY_OF_WEEK - 1)) - 1); 
Date mondayDate = calendar.getTime(); 
SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, mondayDate); 
SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, new Date()); 
SearchTerm comparisonAndTerm = new AndTerm(comparisonTermGe, comparisonTermLe); 
Message[] messages = folder.search(comparisonAndTerm); 

4、搜索大於或等100KB的所有郵件

int mailSize = 1024 * 100; SearchTerm intComparisonTerm = new SizeTerm(IntegerComparisonTerm.GE, mailSize); 
Message[] messages = folder.search(intComparisonTerm); 

ComparisonTerm類常用於日期和數字比較中,它使用六個常量EQ(=)、GE(>=)、GT(>)、LE(<=)、LT(<)、NE(!=)來表示六種不同的比較操作。

 

//如果需要在取得郵件數后將郵件置為已讀則這里需要使用READ_WRITE,否則READ_ONLY就可以
    inbox.open(Folder.READ_WRITE); 
    // Message messages[] = inbox.getMessages(); //獲取所有郵件

    //建立搜索條件FlagTerm,這里FlagTerm繼承自SearchTerm,也就是說除了獲取未讀郵
    //件的條件還有很多其他條件同樣繼承了SearchTerm的條件類,像根據發件人,主題搜索等,
    // 還有復雜的邏輯搜索類似:
    //     
    //    SearchTerm orTerm = new OrTerm(   
    //            new FromStringTerm(from),   
    //            new SubjectTerm(subject)   
    //            ); 
    //  

    FlagTerm ft = 
        new FlagTerm(new Flags(Flags.Flag.SEEN), false); //false代表未讀,true代表已讀

    /**
    * Flag 類型列舉如下
    * Flags.Flag.ANSWERED 郵件回復標記,標識郵件是否已回復。
    * Flags.Flag.DELETED 郵件刪除標記,標識郵件是否需要刪除。
    * Flags.Flag.DRAFT 草稿郵件標記,標識郵件是否為草稿。
    * Flags.Flag.FLAGGED 表示郵件是否為回收站中的郵件。
    * Flags.Flag.RECENT 新郵件標記,表示郵件是否為新郵件。
    * Flags.Flag.SEEN 郵件閱讀標記,標識郵件是否已被閱讀。
    * Flags.Flag.USER 底層系統是否支持用戶自定義標記,只讀。
    */


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM