1. Receive mail
package com.yht.email3; import com.yht.pdf.pdfAnalysis; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io. *; import java.text.*; import java.util. *; import javax.mail.*; import javax.mail.internet.*; @SuppressWarnings("value={\"unchecked\", \"rawtypes\"}") public class PraseMimeMessage { private MimeMessage mimeMessage = null; private String saveAttachPath = "";// The storage directory after the attachment is downloaded private StringBuffer bodytext = new StringBuffer(); // StringBuffer object to store email content private String dateformat = "yy-MM-dd HH:mm";// The default display format for the day before /** * Constructor, initialize a MimeMessage object */ public PraseMimeMessage() { } public PraseMimeMessage(MimeMessage mimeMessage) { this.mimeMessage = mimeMessage; System.out.println("Create a PraseMimeMessage object........"); } public void setMimeMessage(MimeMessage mimeMessage) { System.out.println(mimeMessage); this.mimeMessage = mimeMessage; } /** * Get sender's address and name */ public String getFrom() throws Exception { 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 = personal + "<" + from + ">"; return fromaddr; } /** * Get the address and name of the recipient, cc, and bcc of the mail, according to the different parameters passed "to" ---- recipient "cc" --- CC address "bcc"- --Bcc address */ public String getMailAddress(String type) throws Exception { String mailaddr = ""; String addtype = type.toUpperCase(); InternetAddress[] address = null; if (addtype.equals("TO") || addtype.equals("CC") || addtype.equals("BCC")) { 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 (address != null) { for (int i = 0; i < address.length; i++) { String email = address[i].getAddress(); if (email == null) email = ""; else { email = MimeUtility.decodeText(email); } String personal = address[i].getPersonal(); if (personal == null) personal = ""; else { personal = MimeUtility.decodeText(personal); } String compositeto = personal + "<" + email + ">"; mailaddr += "," + compositeto; } mailaddr = mailaddr.substring(1); } } else { throw new Exception("Wrong email address type!"); } return mailaddr; } /** * Get email subject */ public String getSubject() throws MessagingException { String subject = ""; try { subject = MimeUtility.decodeText(mimeMessage.getSubject()); if (subject == null) subject = ""; } catch (Exception exce) { } return subject; } /** * Get the date the email was sent */ public String getSentDate() throws Exception { Date sentdate = mimeMessage.getSentDate(); SimpleDateFormat format = new SimpleDateFormat(dateformat); return format.format(sentdate); } /** * Get the message body content */ public String getBodyText() { return bodytext.toString(); } /** * Parse the email and save the obtained email content to a StringBuffer object. Parsing the email mainly performs different operations according to the type of MimeType, and parses it step by step */ public void getMailContent(Part part) throws Exception { String contenttype = part.getContentType(); int nameindex = contenttype.indexOf("name"); boolean conname = false; if (nameindex != -1) conname = true; System.out.println("CONTENTTYPE: " + contenttype); 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()); } else { } } /** * Determine whether this email needs a receipt, if it needs a receipt, return "true", otherwise return "false" */ public boolean getReplySign () throws MessagingException { boolean replysign = false; String needreply[] = mimeMessage.getHeader("Disposition-Notification-To"); if (needreply != null) { replysign = true; } return replysign; } /** * Get the Message-ID of this email */ public String getMessageId() throws MessagingException { System.out.println(mimeMessage.getMessageID().toString()); return mimeMessage.getMessageID(); } /** * [Determine whether this email has been read, if not, return false, otherwise return true] */ public boolean isNew() throws MessagingException { boolean isnew = false; Flags flags = ((Message) mimeMessage).getFlags(); Flags.Flag[] flag = flags.getSystemFlags(); System.out.println("flags的长度: " + flag.length); for (int i = 0; i < flag.length; i++) { if (flag[i] == Flags.Flag.SEEN) { isnew = true; System.out.println("seen Message......."); break; } } return isnew; } /** * Determine if this email contains attachments */ public boolean isContainAttach(Part part) throws Exception { boolean attachflag = false; String contentType = part.getContentType(); if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mpart = mp.getBodyPart(i); String disposition = mpart.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) attachflag = true; else if (mpart.isMimeType("multipart/*")) { attachflag = isContainAttach((Part) mpart); } else { String contype = mpart.getContentType(); if (contype.toLowerCase().indexOf("application") != -1) attachflag = true; if (contype.toLowerCase().indexOf("name") != -1) attachflag = true; } } } else if (part.isMimeType("message/rfc822")) { attachflag = isContainAttach((Part) part.getContent()); } return attachflag; } /** * 【Save attachments】 */ public void saveAttachMent(Part part) throws Exception { String fileName = ""; if (part.isMimeType("multipart/*")) { Multipart mp = (Multipart) part.getContent(); for (int i = 0; i < mp.getCount(); i++) { BodyPart mpart = mp.getBodyPart(i); String disposition = mpart.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) { fileName = mpart.getFileName(); if (fileName.toLowerCase().indexOf("gb2312") != -1) { fileName = MimeUtility.decodeText(fileName); } if (fileName.toLowerCase().indexOf("gbk") != -1) { fileName = MimeUtility.decodeText(fileName); } saveFile(fileName, mpart.getInputStream()); } else if (mpart.isMimeType("multipart/*")) { saveAttachMent (mpart); } else { fileName = mpart.getFileName(); if ((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)) { fileName = MimeUtility.decodeText(fileName); saveFile(fileName, mpart.getInputStream()); } } } } else if (part.isMimeType("message/rfc822")) { saveAttachMent((Part) part.getContent()); } } /** * [Set attachment storage path] */ public void setAttachPath(String attachpath) { this.saveAttachPath = attachpath; } /** * 【Set date display format】 */ public void setDateFormat(String format) throws Exception { this.dateformat = format; } /** * [Get the attachment storage path] */ public String getAttachPath() { return saveAttachPath; } /** * [Real save attachments to the specified directory] */ private void saveFile(String fileName, InputStream in) throws Exception { String osName = System.getProperty("os.name"); String storedir = getAttachPath(); String separator = ""; if (osName == null) osName = ""; if (osName.toLowerCase().indexOf("win") != -1) { separator = "\\"; if (storedir == null || storedir.equals("")) storedir = "c:\\tmp"; } else { separator = "/"; storedir = "/tmp"; } File storefile = new File(storedir + separator + fileName); System.out.println("download file address: " + storefile.toString()); BufferedOutputStream bos = null; BufferedInputStream bis = null; try { bos = new BufferedOutputStream(new FileOutputStream(storefile)); bis = new BufferedInputStream(in); int c; while ((c = bis.read()) != -1) { bos.write(c); bos.flush(); } } catch (Exception exception) { exception.printStackTrace(); throw new Exception("Failed to save the file!"); } finally { bos.close(); bis.close(); } } /** * PraseMimeMessage class test */ static String pdf_Url; public static void main(String args[]) throws Exception { String host = "pop.qq.com"; // 【pop.mail.yahoo.com.cn】 String username = "[email protected]"; String password = "skvtezboajgfgfgfgfghjhjgfdcvncpvbide"; Properties p = new Properties(); p.setProperty("mail.pop3.host", "pop.qq.com"); // Change as needed p.setProperty("mail.pop3.port", "995"); // SSL secure connection parameters p.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); p.setProperty("mail.pop3.socketFactory.fallback", "true"); p.setProperty("mail.pop3.socketFactory.port", "995"); Session session = Session.getDefaultInstance(p, null); Store store = session.getStore("pop3"); store.connect(host, username, password); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); System.out.println("Messages's length: " + message.length); PraseMimeMessage pmm = null; for (int i = 0; i < message.length; i++) { pmm = new PraseMimeMessage((MimeMessage) message[i]); System.out.println("Message " + i + " 主题: " + pmm.getSubject()); System.out.println("Message " + i + " Whether there is an attachment: " + pmm.isContainAttach((Part) message[i])); System.out.println("Message " + i + " 发件人: " + pmm.getFrom()); System.out.println("Message " + i + " 收件人: " + pmm.getMailAddress("to")); pmm.setDateFormat("yy year MM month dd day HH:mm"); pmm.getMailContent((Part) message[i]); // System.out.println("Message " + i + " 内容: \r\n" + pmm.getBodyText()); String email_Body = pmm.getBodyText(); if (pmm.getSubject().contains("20KG")) { //Download attachments File file = new File("C:\\tmp\\"); if (!file.exists()) { file.mkdirs(); } pmm.setAttachPath(file.toString()); pmm.saveAttachMent((Part) message[i]); } String aa = pmm.getSubject(); if (aa.contains("Tigerair")) { //If the name is "Tigerair", get the URL Document doc =Jsoup.parse(email_Body); Elements es = doc.select("table[class=em_main_table]").select("table[style=border-collapse: collapse;]").select("table[align=center]").select("a"); System.out.println("我是URL"+es.attr("href"));// } } public static void read() throws IOException { // The downloaded link is the downloaded name and the downloaded path pdfAnalysis.downLoadByUrl(pdf_Url, "KK.pdf", "F:/"); // read the file pdfAnalysis pdf = new pdfAnalysis(); // read the file String pdfName = "F:\\KK.pdf"; // Parse the value in the PDF and store it in the variable pdf_Body String pdf_Body = pdf.readFileOfPDF(pdfName); // Get the value in the Department (leave the ground) String depart_Temp = pdf_Body.substring(pdf_Body.indexOf("Depart"), pdf_Body.indexOf("Arrive")); String depart_Temp2 = depart_Temp.substring(depart_Temp.indexOf("Depart")); // System.out.println("Total value of Department taken out:" + depart_Temp2); String depart_Temp3 = depart_Temp2.substring(depart_Temp2.indexOf("("), depart_Temp2.indexOf(")")); // replace parentheses with empty strings and remove empty strings String depart = depart_Temp3.replace("(", "").trim(); System.out.println("Depart:" + depart); // Get the value of Arrive (arrival) String arrive_Temp = pdf_Body.substring(pdf_Body.indexOf("Arrive:"), pdf_Body.indexOf("passenger details")); String arrive_Temp1 = arrive_Temp.substring(arrive_Temp.indexOf("("), arrive_Temp.indexOf(")")); // replace parentheses with empty strings and remove empty strings String arrive = arrive_Temp1.replace("(", "").trim(); System.out.println("Arrive:" + arrive); // get the money value String money = pdf_Body.substring(pdf_Body.indexOf("AUD ") + 4, pdf_Body.indexOf("GST")); System.out.println("Total amount:" + money); // get the name value String name_Temp = pdf_Body.substring(pdf_Body.indexOf("Arrive"), pdf_Body.indexOf("passenger details")); // System.out.println(str); String name_Temp1 = null; String result_name = null; List list_Name = new ArrayList<>(); for (int i = 1; i < name_Temp.length(); i++) { if (name_Temp.contains(i + ".")) { name_Temp1 = name_Temp.substring(name_Temp.indexOf(i + ".")); result_name = name_Temp1.substring(name_Temp1.indexOf(i + ".") + 3, name_Temp1.indexOf("Seat Number Services")); list_Name.add(result_name); } // System.out.println(add); // System.out.println(str2); if (name_Temp1.equals("null")) { continue; } } for (String i : list_Name) { System.out.println("All names: " + i); } System.out.println("----------------------------------------------------------------"); } } }