java來接收郵件並解析郵件正文中的表格


這里是實際需求中的一個DEMO

有一部分內容進行了注釋和處理,參考需要修改成自己的實際參數。另這個是對於實際一個場景的案例並不是通用解決的工具類。

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import static java.lang.System.out;

/**
 * 描述:把郵件轉換成此類的一個實例進行處理
 */

/**
 * <!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
 * <dependency>
 * <groupId>javax.mail</groupId>
 * <artifactId>mail</artifactId>
 * <version>1.4.7</version>
 * </dependency>
 * <p>
 * <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
 * <dependency>
 * <groupId>org.jsoup</groupId>
 * <artifactId>jsoup</artifactId>
 * <version>1.12.1</version>
 * </dependency>
 */
public class ReceiveOneMail {

    /**
     * 郵件信息
     */
    private MimeMessage mimeMessage;
    /**
     * 郵件正文內容
     */
    private StringBuffer bodyText = new StringBuffer();

    public ReceiveOneMail(MimeMessage mimeMessage) {
        this.mimeMessage = mimeMessage;
    }

    /**
     * main測試方法
     */
    public static void main(String args[]) throws Exception {

        Message[] messages = testInit();
        
        ReceiveOneMail pmm = null;
        // 循環測試郵件的收件箱郵件【時間倒序】
        for (int i = messages.length; i >= 0; i--) {
            //            // 構建 ReceiveOneMail 實例
            pmm = new ReceiveOneMail((MimeMessage) messages[i]);
            out.println("---------" + pmm.getSubject() + "--------");
            pmm.getMailContent((Part) messages[i]);
            List<MailContentTableInfo> list = pmm.parseContent();
            // 模擬輸出解析結果
            for (MailContentTableInfo mailContentTableInfo :
                    list) {
                out.println(mailContentTableInfo.toString());
            }
        }
    }

    /**
     * 初始化構建一個連接郵箱的信息進行測試
     *
     * @return 一個數組郵件信息
     * @throws MessagingException 郵件信息異常
     */
    public static Message[] testInit() throws MessagingException {
        Properties props = System.getProperties();
        props.put("mail.pop3.host", "【實際值】");
        Session session = Session.getDefaultInstance(props, null);
        URLName url = new URLName("pop3", "【實際值】", 110, null,
                "【郵箱地址】", "【郵箱密碼】");
        Store store = session.getStore(url);
        store.connect();
        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);
        return folder.getMessages();
    }

    /**
     * 處理郵件中的正文,解析出里面的表格【第一個表格】
     * 按照【委托資金划撥】的規則進行解析並實例化為一組MailContentTableInfo
     */
    public List<MailContentTableInfo> parseContent() throws MessagingException, ParseException {
        List<MailContentTableInfo> list = new ArrayList<>();
        Document doc = Jsoup.parse(this.getBodyText());
        // 處理匹配到的第一個 table 表格,並且獲得表格中的所有行
        Elements rows = doc.select("table").get(0).select("tr");
        Elements firstRowCols = rows.get(0).select("td");
        Elements lastRowCols = rows.get(rows.size() - 1).select("td");
        // 處理整個表格的業務時間
        String transferDate = evalTransferDate(rows.get(1).select("td").get(0).text());
        for (int i = 1; i < firstRowCols.size(); i++) {
            MailContentTableInfo mailContentTableInfo = new MailContentTableInfo();
            mailContentTableInfo.setMailDate(this.getSentDate());
            mailContentTableInfo.setTransferDate(transferDate);
            mailContentTableInfo.setProductName(firstRowCols.get(i).text().replace(" ", ""));
            mailContentTableInfo.setTransferAmount(new BigDecimal(lastRowCols.get(i).text().replace(",", "")));
            list.add(mailContentTableInfo);
        }
        return list;
    }

    /**
     * 處理表格中的業務日期,和郵件發送時間的年份拼接成8位的字符日期;
     * 原有表格中的日期是 6月2日這種,所以需要特殊處理。
     */
    private String evalTransferDate(String transferDateText) throws MessagingException {
        String[] transferMonthDate = transferDateText.split("月");
        String month = transferMonthDate[0].length() == 1 ? "0" + transferMonthDate[0] : transferMonthDate[0];
        String[] transferDayDate = transferMonthDate[1].split("日");
        String day = transferDayDate[0].length() == 1 ? "0" + transferDayDate[0] : transferDayDate[0];
        return this.getSentYearDate() + month + day;
    }

    /**
     * 獲得郵件發送日期
     */
    private String getSentDate() throws MessagingException {
        return new SimpleDateFormat("yyyyMMdd").format(mimeMessage.getSentDate());
    }

    /**
     * 獲得郵件發送年
     */
    private String getSentYearDate() throws MessagingException {
        return this.getSentDate().substring(0, 4);
    }

    /**
     * 獲得當前郵件主題
     */
    private String getSubject() throws MessagingException, UnsupportedEncodingException {
        String subject = MimeUtility.decodeText(mimeMessage.getSubject());
        return subject == null ? "" : subject;
    }

    /**
     * 獲得郵件正文內容
     */
    private String getBodyText() {
        return bodyText.toString();
    }

    /**
     * 解析郵件,把得到的郵件內容保存到一個StringBuffer對象中,解析郵件 主要是根據MimeType類型的不同執行不同的操作,一步一步的解析
     */
    private void getMailContent(Part part) throws Exception {
        String contentType = part.getContentType();
        int nameIndex = contentType.indexOf("name");
        boolean conName = false;
        if (nameIndex != -1) {
            conName = true;
        }
        if (part.isMimeType("text/plain") && !conName) {
            bodyText.append((String) part.getContent());
        } else if (part.isMimeType("text/html") && !conName) {
            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++) {
                getMailContent(multipart.getBodyPart(i));
            }
        } else if (part.isMimeType("message/rfc822")) {
            getMailContent((Part) part.getContent());
        }
    }
}

/**
 * 定義解析郵件表格內容后的實體類
 */
class MailContentTableInfo {

    private String col1;
    private String col2;
    private String col3;
    private BigDecimal col4;

    public String getMailDate() {
        return col1;
    }

    public void setMailDate(String mailDate) {
        this.col1 = mailDate;
    }

    public String getProductName() {
        return col3;
    }

    public void setProductName(String productName) {
        this.col3 = productName;
    }

    public BigDecimal getTransferAmount() {
        return col4;
    }

    public void setTransferAmount(BigDecimal transferAmount) {
        this.col4 = transferAmount;
    }

    public String getTransferDate() {
        return col2;
    }

    public void setTransferDate(String transferDate) {
        this.col2 = transferDate;
    }

    @Override
    public String toString() {
        return "MailContentTableInfo{" +
                "col1=" + col1 +
                ", col2=" + col2 +
                ", col3='" + col3 + '\'' +
                ", col4=" + col4 +
                '}';
    }
}


免責聲明!

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



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