package com.ots.project.tool.email.utils; import lombok.extern.slf4j.Slf4j; import javax.mail.*; import javax.mail.Message.RecipientType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.*; @Slf4j public class EmailUtil { private String username = null; private String password = null; public EmailUtil(String username, String password) { this.username = username; this.password = password; } public static boolean isSeen(MimeMessage msg) throws MessagingException { return msg.getFlags().contains(Flags.Flag.SEEN); } 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(); } public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException { 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); } } } public Session createSession(Properties props) { Session session = Session.getInstance(props, new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { PasswordAuthentication pa = new PasswordAuthentication(username, password); return pa; } }); return session; } public void sendMail(Properties props, SendEmailMessage sem) throws Exception { Session session = createSession(props); Message msg = new MimeMessage(session); msg.setFrom(InternetAddress.parse(MimeUtility.decodeText(sem.getFrom()))[0]); msg.setRecipients(RecipientType.TO, InternetAddress.parse(sem.getRecipient())); msg.setSubject(sem.getSubject()); msg.setText(sem.getText()); msg.setSentDate(new Date()); Transport.send(msg); } public List receiveMail(Properties props, String protocol) { Store store = null; List bouncedUserList = new ArrayList<>(); try { Session session = createSession(props); store = session.getStore(protocol); store.connect(); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_WRITE); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.ENVELOPE); Message[] msgs = inbox.getMessages(); inbox.fetch(msgs, profile); for (int i = 0; i < msgs.length; i++) { MimeMessage msg = (MimeMessage) msgs[i]; String sender = decodeText(msgs[i].getFrom()[0].toString()); if (isSeen(msg)) { continue; } if (countStr(sender, "PostMaster") > 0) { StringBuffer content = new StringBuffer(30); getMailTextContent(msg, content); String head = "收件人("; int start = content.indexOf(head); int end = content.indexOf(")", start); String realSender = content.substring(start + head.length(), end); String message = content.substring(end, end + 30); BouncedUser bouncedUser = new BouncedUser(); bouncedUser.setRealsender(realSender); bouncedUser.setSentDateExtend(getSentDate(msg, "yyyy-MM-dd HH:mm:ss")); bouncedUser.setReason(message); int len = content.length(); if (len > 3000) { len = 3000; } bouncedUser.setContent(content.toString().substring(0, len)); bouncedUser.setTitle(msgs[i].getSubject()); bouncedUser.setReceiveaddress(getReceiveAddress(msg, null)); bouncedUser.setSenddate(msg.getSentDate()); bouncedUser.setSender(sender); bouncedUserList.add(bouncedUser); log.error("----------------------------------------------------------------------"); log.error("发送时间:{}", msgs[i].getSentDate()); log.error("发送时间:{}", getSentDate(msg, "yyyy-MM-dd HH:mm:ss")); log.error("发送人:{}", sender); log.error("收件人:{}", getReceiveAddress(msg, null)); log.error("大小:{}", msgs[i].getSize()); log.error("是否已读:{}", isSeen(msg)); log.error("标题:{}", msgs[i].getSubject()); log.error("内容:{}", msgs[i].getContent()); log.error("退信邮箱地址:{}", realSender); log.error("退信原因:{}", message); log.error("----------------------------------------------------------------------"); } } } catch (Exception ex) { log.error("接收邮件拉取失败:{}" + ex.getMessage(), ex); } finally { if (Objects.isNull(store)) { try { store.close(); } catch (MessagingException e) { log.error("关闭邮箱拉取连接通道失败:{}", e.getMessage(), e); } } } return bouncedUserList; } private int countStr(String str, String sToFind) { int num = 0; while (str.contains(sToFind)) { str = str.substring(str.indexOf(sToFind) + sToFind.length()); num++; } return num; } public 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 "; Calendar cal = Calendar.getInstance(); cal.setTime(receivedDate); cal.add(Calendar.MINUTE, 10); return new SimpleDateFormat(pattern).format(cal.getTime()); } private String decodeText(String text) throws UnsupportedEncodingException { if (text == null) { return null; } if (text.startsWith("=?GB") || text.startsWith("=?gb")) text = MimeUtility.decodeText(text); else text = new String(text.getBytes("ISO8859_1")); return text; } }