Java實現讀取163郵箱,qq郵箱的郵件內容

通過使用java mail來實現讀取163郵箱,qq郵箱的郵件內容。

1.代碼實現

創建springboot項目,引入依賴包

 <!--mail-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

實現類

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.protocol.IMAPProtocol;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.ObjectUtils;
 
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
 
public class ShowMail {
 
    public static String NORM_DATETIME_PATTERN = "yyyy-MM-dd hh:mm:ss";
    private MimeMessage mimeMessage;
    /**
     * 附件下載後的存放目錄
     */
    private String saveAttachPath = "";
    /**
     * 存放郵件內容的StringBuffer對象
     */
    private StringBuffer bodyText = new StringBuffer();
 
    /**
     * 構造函數,初始化一個MimeMessage對象
     *
     * @param mimeMessage
     */
    public ShowMail(MimeMessage mimeMessage) {
        this.mimeMessage = mimeMessage;
    }
 
    /**
     * 獲得發件人的地址和姓名
     *
     * @return
     * @throws MessagingException
     */
    public String getFrom() throws MessagingException {
        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 = null;
        if (personal != null || from != null) {
            fromAddr = personal + "<" + from + ">";
        }
        return fromAddr;
    }
 
    /**
     * 獲得郵件的收件人,抄送,和密送的地址和姓名,根據所傳遞的參數的不同
     *
     * @param type "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
     * @return
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public String getMailAddress(String type) throws MessagingException, UnsupportedEncodingException {
        if (ObjectUtils.isEmpty(type)) {
            return "";
        }
 
        String addType = type.toUpperCase();
 
        if (!addType.equals("TO") && !addType.equals("CC") && !addType.equals("BCC")) {
            return "";
        }
        InternetAddress[] address;
 
        if (addType.equals("TO")) {
            address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
        } else if (addType.equals("CC")) {
            address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
        } else {
            address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
        }
 
        if (ObjectUtils.isEmpty(address)) {
            return "";
        }
        StringBuilder mailAddr = new StringBuilder();
        String emailAddr;
        String personal;
        for (int i = 0; i < address.length; i++) {
            emailAddr = address[i].getAddress();
            if (emailAddr == null) {
                emailAddr = "";
            } else {
                emailAddr = MimeUtility.decodeText(emailAddr);
            }
            personal = address[i].getPersonal();
            if (personal == null) {
                personal = "";
            } else {
                personal = MimeUtility.decodeText(personal);
            }
            mailAddr.append(",").append(personal).append("<").append(emailAddr).append(">");
        }
        return mailAddr.toString().substring(1);
    }
 
    /**
     * 獲得郵件主題
     *
     * @return
     * @throws MessagingException
     * @throws UnsupportedEncodingException
     */
    public String getSubject() throws MessagingException, UnsupportedEncodingException {
        String subject = MimeUtility.decodeText(mimeMessage.getSubject());
        if (subject == null) {
            subject = "";
        }
        return subject;
    }
 
    /**
     * 獲得郵件發送日期
     *
     * @return
     * @throws MessagingException
     */
    public String getSentDate() throws MessagingException {
        Date sentDate = mimeMessage.getSentDate();
        SimpleDateFormat format = new SimpleDateFormat(NORM_DATETIME_PATTERN);
        return format.format(sentDate);
    }
 
    /**
     * 獲得郵件正文內容
     *
     * @return
     */
    public String getBodyText() {
        return bodyText.toString();
    }
 
    /**
     * 解析郵件,把得到的郵件內容保存到一個StringBuffer對象中,解析郵件
     * 主要是根據MimeType類型的不同執行不同的操作,一步一步的解析
     * @param part
     * @throws MessagingException
     * @throws IOException
     */
    public void getMailContent(Part part) throws MessagingException, IOException {
 
        String contentType = part.getContentType();
 
        int nameIndex = contentType.indexOf("name");
 
        boolean conName = false;
 
        if (nameIndex != -1) {
            conName = true;
        }
 
        if (part.isMimeType("text/plain") && conName == false) {
            bodyText.append((String) part.getContent());
        } else if (part.isMimeType("text/html") && conName == false) {
            bodyText.append((String) part.getContent());
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int counts = multipart.getCount();
            for (int i = 0; i < counts; i++) {
                this.getMailContent(multipart.getBodyPart(i));
            }
        } else if (part.isMimeType("message/rfc822")) {
            this.getMailContent((Part) part.getContent());
        }
    }
 
    /**
     * 判斷此郵件是否需要回執,如果需要回執返回"true",否則返回"false"
     *
     * @return
     * @throws MessagingException
     */
    public boolean getReplySign() throws MessagingException {
 
        boolean replySign = false;
 
        String needReply[] = mimeMessage.getHeader("Disposition-Notification-To");
 
        if (needReply != null) {
            replySign = true;
        }
        return replySign;
    }
 
    /**
     * 判斷此郵件是否已讀,如果未讀返回false,反之返回true
     *
     * @return
     * @throws MessagingException
     */
    public boolean isNew() throws MessagingException {
        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;
            }
        }
        return isNew;
    }
 
    /**
     * 判斷此郵件是否包含附件
     *
     * @param part
     * @return
     * @throws MessagingException
     * @throws IOException
     */
    public boolean isContainAttach(Part part) throws MessagingException, IOException {
        boolean attachFlag = false;
        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            BodyPart mPart;
            String conType;
            for (int i = 0; i < mp.getCount(); i++) {
                mPart = mp.getBodyPart(i);
                String disposition = mPart.getDisposition();
                if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {
                    attachFlag = true;
                } else if (mPart.isMimeType("multipart/*")) {
                    attachFlag = this.isContainAttach(mPart);
                } else {
                    conType = mPart.getContentType();
                    if (conType.toLowerCase().indexOf("application") != -1 || conType.toLowerCase().indexOf("name") != -1){
                        attachFlag = true;
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            attachFlag = isContainAttach((Part) part.getContent());
        }
        return attachFlag;
    }
 
    /**
     * 保存附件
     *
     * @param part
     * @throws MessagingException
     * @throws IOException
     */
    public void saveAttachMent(Part part) throws MessagingException, IOException {
        String fileName;
        if (part.isMimeType("multipart/*")) {
            Multipart mp = (Multipart) part.getContent();
            BodyPart mPart;
            for (int i = 0; i < mp.getCount(); i++) {
                mPart = mp.getBodyPart(i);
                String disposition = mPart.getDisposition();
                if (Part.ATTACHMENT.equals(disposition) || Part.INLINE.equals(disposition)) {
                    fileName = mPart.getFileName();
                    if (null != fileName && fileName.toLowerCase().indexOf("gb2312") != -1) {
                        fileName = MimeUtility.decodeText(fileName);
                    }
                    this.saveFile(fileName, mPart.getInputStream());
                } else if (mPart.isMimeType("multipart/*")) {
                    this.saveAttachMent(mPart);
                } else {
                    fileName = mPart.getFileName();
                    if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) {
                        fileName = MimeUtility.decodeText(fileName);
                        this.saveFile(fileName, mPart.getInputStream());
                    }
                }
            }
        } else if (part.isMimeType("message/rfc822")) {
            this.saveAttachMent((Part) part.getContent());
        }
    }
 
    /**
     * 設置附件存放路徑
     *
     * @param attachPath
     */
    public void setAttachPath(String attachPath) {
        this.saveAttachPath = attachPath;
    }
 
    /**
     * 獲得附件存放路徑
     *
     * @return
     */
    public String getAttachPath() {
        return saveAttachPath;
    }
 
    /**
     * 真正的保存附件到指定目錄裡
     *
     * @param fileName
     * @param in
     * @throws IOException
     */
    private void saveFile(String fileName, InputStream in) throws IOException {
        String osName = System.getProperty("os.name");
        String storeDir = this.getAttachPath();
        if (null == osName) {
            osName = "";
        }
        if (osName.toLowerCase().indexOf("win") != -1) {
            if (ObjectUtils.isEmpty(storeDir))
                storeDir = "C:\\tmp";
        } else {
            storeDir = "/tmp";
        }
//        fileName=fileName.replace("=?", "");
//        fileName=fileName.replace("?=", "");
//        fileName = fileName.substring(fileName.length() - 6, fileName.length());
        FileOutputStream fos = new FileOutputStream(new File(storeDir + File.separator + fileName));
        IOUtils.copy(in, fos);
        IOUtils.closeQuietly(fos);
        IOUtils.closeQuietly(in);
    }
 
    /**
     * 獲取163郵箱信息
     *
     * @param host
     * @param username
     * @param password
     * @param protocol
     * @return
     * @throws MessagingException
     */
    public static Message[] getWEMessage(String host, String username, String password, String protocol) throws MessagingException {
        //創建屬性對象
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        //創建會話
        Session session = Session.getDefaultInstance(props, null);
        //存儲對象
        Store store = session.getStore(protocol);
        //連接
        store.connect(host, username, password);
        //創建目錄對象
        Folder folder = store.getFolder("INBOX");
        if (folder instanceof IMAPFolder) {
            IMAPFolder imapFolder = (IMAPFolder)folder;
            //javamail中使用id命令有校驗checkOpened, 所以要去掉id方法中的checkOpened();
            imapFolder.doCommand(new IMAPFolder.ProtocolCommand() {
                public Object doCommand(IMAPProtocol p) throws com.sun.mail.iap.ProtocolException {
                    p.id("FUTONG");
                    return null;
                }
            });
        }
        if(folder != null) {
            folder.open(Folder.READ_WRITE);
        }
        return folder.getMessages();
    }
 
    /**
     * 獲取qq郵箱信息
     *
     * @param host
     * @param username
     * @param password
     * @param protocol
     * @return
     * @throws MessagingException
     */
    public static Message[] getQQMessage(String host, String username, String password, String protocol) throws MessagingException {
        //創建屬性對象
        Properties props = new Properties();
        props.put("mail.store.protocol", protocol);
        //創建會話
        Session session = Session.getDefaultInstance(props, null);
        //存儲對象
        Store store = session.getStore(protocol);
        //連接
        store.connect(host,username,password);
        //創建目錄對象
        Folder folder = store.getFolder("Inbox");
        if(folder != null) {
            folder.open(Folder.READ_WRITE);
        }
        return folder.getMessages();
    }
 
    /**
     * 過濾郵箱信息
     *
     * @param messages
     * @param fromMail 隻讀取該郵箱發來的郵件,如果為空則不過濾
     * @param startDate 隻讀取該日期以後的郵件,如果為空則不過濾
     * @return
     * @throws MessagingException
     */
    public static List<Message> filterMessage(Message[] messages, String fromMail, String startDate) throws MessagingException, ParseException {
        List<Message> messageList = new ArrayList<>();
        if (ObjectUtils.isEmpty(messages)) {
            return messageList;
        }
        boolean isEnptyFromMail = ObjectUtils.isEmpty(fromMail);
        boolean isEnptyStartDate = ObjectUtils.isEmpty(startDate);
        if (isEnptyFromMail && isEnptyStartDate) {
            return Arrays.asList(messages);
        }
 
        String from;
        for (Message message: messages) {
            from = null;
            if(message.getFrom() != null) {
                from = (message.getFrom()[0]).toString();
            }
            if (isEnptyFromMail) {
                if (message.getSentDate() != null && new SimpleDateFormat(NORM_DATETIME_PATTERN).parse(startDate).getTime() > message.getSentDate().getTime()) {
                    continue;
                }
            } else if (null != from && from.contains(fromMail)) {
                if (!isEnptyStartDate && new SimpleDateFormat(NORM_DATETIME_PATTERN).parse(startDate).getTime() > message.getSentDate().getTime()) {
                    continue;
                }
            } else {
                continue;
            }
            messageList.add(message);
        }
        return messageList;
    }
 
    /**
     * 打印郵件
     *
     * @param messageList
     * @throws IOException
     * @throws MessagingException
     */
    public static void printMailMessage(List<Message> messageList) throws IOException, MessagingException {
        System.out.println("郵件數量:" + messageList.size());
        ShowMail re;
        Message message;
        for (int i = 0, leng = messageList.size(); i < leng; i++) {
            message = messageList.get(i);
            re = new ShowMail((MimeMessage) message);
            System.out.println("郵件【" + i + "】主題:" + re.getSubject());
            System.out.println("郵件【" + i + "】發送時間:" + re.getSentDate());
            System.out.println("郵件【" + i + "】是否需要回復:" + re.getReplySign());
            System.out.println("郵件【" + i + "】是否已讀:" + re.isNew());
            System.out.println("郵件【" + i + "】是否包含附件:" + re.isContainAttach( message));
            System.out.println("郵件【" + i + "】發送人地址:" + re.getFrom());
            System.out.println("郵件【" + i + "】收信人地址:" + re.getMailAddress("to"));
            System.out.println("郵件【" + i + "】抄送:" + re.getMailAddress("cc"));
            System.out.println("郵件【" + i + "】暗抄:" + re.getMailAddress("bcc"));
            System.out.println("郵件【" + i + "】發送時間:" + re.getSentDate());
            System.out.println("郵件【" + i + "】郵件ID:" + ((MimeMessage) message).getMessageID());
            re.getMailContent(message);
            System.out.println("郵件【" + i + "】正文內容:\r\n" + re.getBodyText());
            re.setAttachPath("D:\\Download\\mailFile\\");
            re.saveAttachMent(message);
        }
    }
 
    public static void main(String[] args) throws MessagingException, IOException, ParseException {
        //163登錄信息
        //郵件服務器
        String host = "mail.xx.com";
        //郵箱賬號
        String username = "xx";
        //授權碼
        String password = "yy";
        //協議
        String protocol = "imaps";
        //隻讀取該郵箱發來的郵件
        String fromMail = null;
        //隻讀取該日期以後的郵件
        String startDate = null;
        List<Message> messageList = filterMessage(getWEMessage(host, username, password, protocol), fromMail, startDate);
        printMailMessage(messageList);
 
        //qq登錄信息
        String host2 = "imap.qq.com";
        String username2 = "xx";
        String password2 = "yy";
       // String protocol2 = "imaps";
        String protocol2 = "pop3";
        String fromMail2 = null;
        String startDate2 = null;
        List<Message> messageList2 = filterMessage(getQQMessage(host2, username2, password2, protocol2), fromMail2, startDate2);
        printMailMessage(messageList2);
    }
 
}

2.配置授權碼

163郵箱:

qq郵箱:

3.實現效果:

運行main方法,查看控制臺:

郵件數量:xx
郵件【0】主題:歡迎您使用xx郵箱!
郵件【0】發送時間:xx
郵件【0】是否需要回復:false
郵件【0】是否已讀:true
郵件【0】是否包含附件:false
郵件【0】發送人地址:xx
郵件【0】收信人地址:xx
郵件【0】抄送:
郵件【0】暗抄:
郵件【0】發送時間:xx
郵件【0】郵件ID:xx
郵件【0】正文內容:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>歡迎使用</title>
    <style>
        body, div, p, img {
            padding: 0;
            margin: 0;
            font-family: 'Microsoft Yahei', "PingFang SC", "Hiragino Sans GB", "wenquanyi micro hei", Arial, Helvetica, "STHeiti", sans-serif;
        }
        .contain {
            width: 700px;
            margin: 0 auto;
            font-size: 0;
        }
        .wrap {
            position: relative;
        }
        .wrap .welcome {
            position: absolute;
            width: 290px;
            left: 75px;
            top: 100px;
            font-size: 18px;
            color: #fff;
            line-height: 32px;
            font-weight: 500;
        }
        .wrap .welcome p.indentation {
            font-size: 16px;
            font-weight: normal;
        }
        .wrap a {
            position: absolute;
            display: block;
            width: 104px;
            height: 39px;
        }
        .wrap a.mobile{
            left: 501px;
            top: 434px;
        }
        .wrap a.pc{
            left: 501px;
            top: 485px;
        }
    </style>
</head>
<body>
    <div class="contain">
        <div class="wrap">
            <div class="welcome">
                <p class="indentation-title">尊敬的xx:</p>
                <p class="indentation">您好,您的郵箱已開通。</p>
            </div>
        </div>
    </div>
</body>
</html>

到此這篇關於Java實現讀取163郵箱,qq郵箱的郵件內容的文章就介紹到這瞭,更多相關Java讀取郵箱郵件內容內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: