工作记录 400行代码实现 获取指定邮箱账户内的所有信息 包括附件

package com.fwtest;
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;
import java.util.Scanner;
public class EmailUtil {
    public static void main(String[] args) throws Exception {
        System.out.println(""
                + " _______.___________. ___ .______ .___________.\n"
                + " / | | / \\ | _ \\ | |\n"
                + " | (----`---| |----` / ^ \\ | |_) | `---| |----`\n"
                + " \\ \\ | | / /_\\ \\ | / | | \n"
                + ".----) | | | / _____ \\ | |\\ \\----. | | \n"
                + "|_______/ |__| /__/ \\__\\ | _| `._____| |__| \n");
        receive("emailAddress", "password");
    }
    public static void receive(String emailAddress, String password) throws Exception {
        String port = "110";
        String servicePath = "192.168.10.100";
        // 准备连接服务器的会话信息
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "pop3");
        props.setProperty("mail.pop3.port", port);
        props.setProperty("mail.pop3.host", servicePath); // pop3服务器
        // 创建Session实例对象
        Session session = Session.getInstance(props);
        Store store = session.getStore("pop3");
        store.connect(emailAddress, password);
        // 获得收件箱
        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_WRITE); //打开收件箱
        System.out.println("账户: " + emailAddress);
        System.out.println("未读邮件数: " + folder.getUnreadMessageCount());
        System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
        System.out.println("新邮件: " + folder.getNewMessageCount());
        System.out.println("邮件总数: " + folder.getMessageCount());
        Message[] messages = folder.getMessages(); // 所有邮件
        //解析
        parseMessage(messages);
        //释放
        folder.close(true);
        store.close();
    }
    /**
     * 解析邮件
     *
     * @param messages 要解析的邮件列表
     */
    public static void parseMessage(Message... messages) {
        try {
            if (messages == null || messages.length < 1) {
                throw new MessagingException("未找到要解析的邮件!");
            }
            // 解析所有邮件
            for (int i = 0; i < messages.length; i++) {
                MimeMessage msg = (MimeMessage) messages[i];
                System.out.println("------------------解析第" + msg.getMessageNumber() + "/" + messages.length + "封邮件--------------------");
                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) {
                    String name = saveAttachment(msg, "D:\\pop3test\\" + msg.getSubject() + "_" + i + "_"); //保存附件
                    System.out.println("附件名:" + name);
                }
                StringBuffer content = new StringBuffer(30);
                //解析邮件正文
                getMailTextContent(msg, content);
                System.out.println("邮件正文:{" + content + "}");
                System.out.println("------------------第" + msg.getMessageNumber() + "/" + messages.length + "封邮件解析结束--------------------");
                System.out.println();
            }
        } catch (MessagingException | IOException e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     * 获得邮件主题
     *
     * @param msg 邮件内容
     * @return 解码后的邮件主题
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     */
    public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
        if (msg == null) {
            throw new MessagingException("未找到要解析的邮件!");
        }
        String subject = msg.getSubject();
        if (subject != null) {
            subject = MimeUtility.decodeText(subject);
        }
        return subject != null ? subject : "";
    }
    /**
     * 获得邮件发件人
     *
     * @param msg 邮件内容
     * @return 姓名 <Email地址>
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
        if (msg == null) {
            throw new MessagingException("未找到要解析的邮件!");
        }
        String from = "";
        Address[] froms = msg.getFrom();
        if (froms == null || froms.length <= 0) {
            throw new MessagingException("没有发件人!");
        }
        InternetAddress address = (InternetAddress) froms[0];
        String person = address.getPersonal();
        if (person != null) {
            person = MimeUtility.decodeText(person) + " ";
        } else {
            person = "null";
        }
        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 {
        if (msg == null) {
            throw new 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日 E HH:mm
     * @throws MessagingException
     */
    public static String getSentDate(MimeMessage msg, String pattern) throws MessagingException {
        if (msg == null) {
            throw new 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);
    }
    /**
     * 判断邮件中是否包含附件
     *
     * @param part 邮件内容
     * @return 邮件中存在附件返回true,不存在返回false
     * @throws MessagingException
     * @throws IOException
     */
    public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
        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))) {
                    return true;
                } else if (bodyPart.isMimeType("multipart/*")) {
                    if (isContainAttachment(bodyPart)) {
                        return true;
                    }
                } else {
                    String contentType = bodyPart.getContentType();
                    if (contentType.contains("application") || contentType.contains("name")) {
                        return true;
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            return isContainAttachment((Part) part.getContent());
        }
        return false;
    }
    /**
     * 判断邮件是否已读
     *
     * @param msg 邮件内容
     * @return 如果邮件已读返回true, 否则返回false
     * @throws MessagingException
     */
    public static boolean isSeen(MimeMessage msg) throws MessagingException {
        if (msg == null) {
            throw new MessagingException("未找到要解析的邮件!");
        }
        boolean isSeen = false;
        Flags flags = msg.getFlags();
        Flags.Flag[] flagArray = flags.getSystemFlags();
        for (Flags.Flag flag : flagArray) {
            if (flag == Flags.Flag.SEEN) {
                isSeen = true;
                break;
            }
        }
        return isSeen;
    }
    /**
     * 判断邮件是否需要回执
     *
     * @param msg 邮件内容
     * @return 需要回执返回true, 否则返回false
     * @throws MessagingException
     */
    public static boolean isReplySign(MimeMessage msg) throws MessagingException {
        if (msg == null) {
            throw new 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 {
        if (msg == null) {
            throw new MessagingException("未找到要解析的邮件!");
        }
        String priority = "普通";
        String[] headers = msg.getHeader("X-Priority");
        if (headers != null && headers.length > 0) {
            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 {
        if (part == null) {
            throw new MessagingException("未找到要解析的邮件!");
        }
        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  附件保存目录
     * @return         文件名
     * @throws UnsupportedEncodingException
     * @throws MessagingException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static String saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException, FileNotFoundException, IOException {
        if (part == null) {
            throw new MessagingException("未找到要解析的邮件!");
        }
        String fileName = "";
        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))) {
                    fileName = MimeUtility.decodeText(bodyPart.getFileName());
                    saveFile(fileName, bodyPart.getInputStream(), destDir);
                } else if (bodyPart.isMimeType("multipart/*")) {
                    saveAttachment(bodyPart, destDir);
                } else {
                    fileName = bodyPart.getFileName();
                    if (fileName != null && fileName.toLowerCase().indexOf("GB2312") != -1) {
                        fileName = MimeUtility.decodeText(fileName);
                        saveFile(fileName, bodyPart.getInputStream(), destDir);
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            saveAttachment((Part) part.getContent(), destDir);
        }
        return fileName;
    }
    /**
     * 读取输入流中的数据保存至指定目录
     *
     * @param fileName 文件名
     * @param in       输入流
     * @param destDir  文件存储目录
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void saveFile(String fileName, InputStream in, String destDir) throws FileNotFoundException, IOException {
        if (fileName == null || destDir == null) {
            throw new IOException("文件名或存储目录不能为空!");
        }
        File file = new File(destDir + fileName);
        BufferedInputStream bis = new BufferedInputStream(in);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
        // 获取文件的总大小
        int fileSize = in.available();
        byte[] buffer = new byte[1024];
        int bytesRead;
        int totalBytesRead = 0;
        System.out.print("保存进度: [");
        while ((bytesRead = bis.read(buffer)) != -1) {
            bos.write(buffer, 0, bytesRead);
            totalBytesRead += bytesRead;
            // 计算当前进度
            int progress = (int) (totalBytesRead * 100.0 / fileSize);
            // 打印进度条
            System.out.print("\r保存进度: [");
            for (int i = 0; i < 50; i++) {
                if (i < progress / 2) {
                    System.out.print("#");
                } else {
                    System.out.print(" ");
                }
            }
            System.out.print("] " + progress + "%");
        }
        // 保证最后显示 100%
        System.out.print("\r保存进度: [##################################################] 100%\n");
        bos.close();
        bis.close();
    }
}

 

 

Jinming

95后典型金牛座,强迫症。

相关推荐

暂无评论

小程序 小程序
小程序