javax.mail获取邮件以及遇到的常见问题整理

maven依赖

<dependency>
  <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.1</version>
</dependency>

代码

import javax.mail.*;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

public class ReceiveMailJob2 {

    public static void main(String[] args) {
        String username = ""; // 邮箱账号
        String password = ""; // 邮箱密码
        String protocol = ""; // 接收协议
        String port = ""; // 端口
        String host = protocol + "." + ""; // 邮件服务器主机名
        // 设置连接属性
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imap.host", host);
        props.setProperty("mail.imap.port", port);
        props.setProperty("mail.imap.ssl.enable", "true");
        try {
            // 连接到邮件服务器
            Session session = Session.getDefaultInstance(props);
            Store store = session.getStore(protocol);
            store.connect(host, username, password);
            // 打开收件箱
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            // 获取最近100封邮件
            int messageCount = inbox.getMessageCount();
            int startIndex = Math.max(1, messageCount - 100 + 1); // 最近的100封邮件的起始索引
            Message[] messages = inbox.getMessages(startIndex, messageCount);
            // 将邮件按照时间戳排序
            Arrays.sort(messages, new Comparator<Message>() {
                @Override
                public int compare(Message message1, Message message2) {
                    try {
                        Date date1 = message1.getSentDate();
                        Date date2 = message2.getSentDate();
                        if (date1 != null && date2 != null) {
                            return date2.compareTo(date1);
                        }
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return 0;
                }
            });
            for (Message message : messages) {
                System.out.println("---------------------------分割线----------------------------");
                String title = message.getSubject();
                //邮件标题
                System.out.println("标题:" + title);
                //邮件发送时间
                String send_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(message.getSentDate());
                System.out.println("发送时间:" + send_time);
                Object content = message.getContent();
                //定义保存邮件附件路径
                String dir = "D:/tmp/" + UUID.randomUUID().toString().replace("-", "") + "/";
                //邮件正文、附件
                processMultipartRelated((Multipart) content, dir);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void processMultipartRelated(Multipart multipart, String dir) throws MessagingException, IOException {
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            String contentType = bodyPart.getContentType();
            //System.out.println("=====contentType====="+contentType);
            if (bodyPart.getFileName() != null && bodyPart.getDisposition() != null && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                String originalFilename = MimeUtility.decodeText(bodyPart.getFileName());
                System.out.println("邮件附件:" + originalFilename);
                InputStream inputStream = bodyPart.getInputStream();
                // 保存附件
                File file = new File(dir);
                if (!file.exists()) {
                    file.mkdirs();
                }
                Path path = Paths.get(dir + originalFilename);
                Files.copy(inputStream, path);
                System.out.println("附件保存成功:" + dir + originalFilename);
                continue;
            }
            // 检查Content-Type
            if (contentType.startsWith("text/plain") || contentType.startsWith("text/html")) {
                // 获取正文内容
                Object content = bodyPart.getContent();
                if (content instanceof String) {
                    System.out.println("邮件正文:" + content);
                }
            }
        }
    }

}

问题1

邮件有正文却获取不到,通过String contentType = bodyPart.getContentType();
发现contentType = multipart/related;
如果仍然是multipart/related类型,则递归处理。

            if (contentType.startsWith("text/plain") || contentType.startsWith("text/html")) {
                // 获取正文内容
                Object content = bodyPart.getContent();
                if (content instanceof String) {
                    System.out.println("邮件正文:" + content);
                }
            } else if (contentType.startsWith("multipart/related")) {
                // 如果仍然是multipart/related类型,则递归处理
                processMultipartRelated((Multipart) bodyPart.getContent(), dir);
            }

问题2

当邮件类型复杂,我这邮件中有多个附件时会出现
String originalFilename = MimeUtility.decodeText(bodyPart.getFileName());
获取originalFilename 是 null 或者报错java.lang.NullPointerException
打印contentType 发现格式为

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; 
  name*0="=?UTF-8?Q?=E9=99=84=E4=BB=B66=EF=BC=9A=E6=B6=89=E6=A1=88?=
 ="; 
  name*1="?UTF-8?Q?=E5=8F=B7=E7=A0=81=E5=8F=8D=E9=A6=88=E6=A8=A1=E6=9D"; 
  name*2="=BF-?= =?UTF-8?Q?20240106.xlsx?="

这时尝试直接解析contentType 获取文件名称。
通过ParameterList中获取name参数并最终使用MimeUtility.decodeText进行解码。

    /*
        这个代码尝试解析contentType,然后从ParameterList中获取name参数,并最终使用MimeUtility.decodeText进行解码。请注意,这里使用了ContentType类,它可以帮助你更方便地处理Content-Type头部。
    */
    private static String decodeName(String contentType) throws ParseException, UnsupportedEncodingException {
        String encodedName = "";
        ContentType ct = new ContentType(contentType);
        ParameterList parameterList = ct.getParameterList();
        Enumeration names = parameterList.getNames();
        while (names.hasMoreElements()) {
            encodedName += parameterList.get((String) names.nextElement());
        }
        String originalFilename = MimeUtility.decodeText(encodedName);
        return originalFilename;
    }

整合

import javax.mail.*;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.ParameterList;
import javax.mail.internet.ParseException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

public class ReceiveMailJob {

    public static void main(String[] args) {
        String username = ""; // 邮箱账号
        String password = ""; // 邮箱密码
        String protocol = ""; // 接收协议
        String port = ""; // 端口
        String host = protocol + "." + ""; // 邮件服务器主机名
        // 设置连接属性
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imap.host", host);
        props.setProperty("mail.imap.port", port);
        props.setProperty("mail.imap.ssl.enable", "true");
        try {
            // 连接到邮件服务器
            Session session = Session.getDefaultInstance(props);
            Store store = session.getStore(protocol);
            store.connect(host, username, password);
            // 打开收件箱
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            // 获取最近100封邮件
            int messageCount = inbox.getMessageCount();
            int startIndex = Math.max(1, messageCount - 100 + 1); // 最近的100封邮件的起始索引
            Message[] messages = inbox.getMessages(startIndex, messageCount);
            // 将邮件按照时间戳排序
            Arrays.sort(messages, new Comparator<Message>() {
                @Override
                public int compare(Message message1, Message message2) {
                    try {
                        Date date1 = message1.getSentDate();
                        Date date2 = message2.getSentDate();
                        if (date1 != null && date2 != null) {
                            return date2.compareTo(date1);
                        }
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return 0;
                }
            });
            for (Message message : messages) {
                System.out.println("---------------------------分割线----------------------------");
                String title = message.getSubject();
                //邮件标题
                System.out.println("标题:" + title);
                //邮件发送时间
                String send_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(message.getSentDate());
                System.out.println("发送时间:" + send_time);
                Object content = message.getContent();
                //定义保存邮件附件路径
                String dir = "D:/tmp/" + UUID.randomUUID().toString().replace("-", "") + "/";
                //邮件正文
                processMultipartRelated((Multipart) content, dir);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void processMultipartRelated(Multipart multipart, String dir) throws MessagingException, IOException {
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            String contentType = bodyPart.getContentType();
            if (bodyPart.getDisposition() != null && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
                String originalFilename = decodeName(contentType);
                System.out.println("邮件附件:" + originalFilename);
                InputStream inputStream = bodyPart.getInputStream();
                // 保存附件
                File file = new File(dir);
                if (!file.exists()) {
                    file.mkdirs();
                }
                Path path = Paths.get(dir + originalFilename);
                Files.copy(inputStream, path);
                System.out.println("附件保存成功:" + dir + originalFilename);
                continue;
            }
            // 检查Content-Type
            if (contentType.startsWith("text/plain") || contentType.startsWith("text/html")) {
                // 获取正文内容
                Object content = bodyPart.getContent();
                if (content instanceof String) {
                    System.out.println("邮件正文:" + content);
                }
            } else if (contentType.startsWith("multipart/related")) {
                // 如果仍然是multipart/related类型,则递归处理
                processMultipartRelated((Multipart) bodyPart.getContent(), dir);
            }
        }
    }

    /*
        这个代码尝试解析contentType,然后从ParameterList中获取name参数,并最终使用MimeUtility.decodeText进行解码。请注意,这里使用了ContentType类,它可以帮助你更方便地处理Content-Type头部。
    */
    private static String decodeName(String contentType) throws ParseException, UnsupportedEncodingException {
        String encodedName = "";
        ContentType ct = new ContentType(contentType);
        ParameterList parameterList = ct.getParameterList();
        Enumeration names = parameterList.getNames();
        while (names.hasMoreElements()) {
            encodedName += parameterList.get((String) names.nextElement());
        }
        return MimeUtility.decodeText(encodedName);
    }

}

  • 22
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 JavaMail 可以获取邮件内容并删除引用部分的具体方法如下: 1. 使用 `Session` 对象创建一个 `Store` 对象,连接到邮件服务器,并打开相应的文件夹(例如 `INBOX`)。 ```java Properties props = new Properties(); props.setProperty("mail.store.protocol", "imap"); Session session = Session.getInstance(props); Store store = session.getStore(); store.connect(host, username, password); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); ``` 2. 获取邮件对象并读取其内容。 ```java Message message = folder.getMessage(messageNumber); String contentType = message.getContentType(); Object content = message.getContent(); ``` 3. 如果邮件是纯文本类型,可以直接读取内容,如果是 HTML 或者带有附件的邮件,需要进行相应的处理。 ```java if (contentType.contains("text/plain")) { String text = (String) content; // 删除引用部分 text = deleteReply(text); System.out.println(text); } else if (contentType.contains("text/html")) { String html = (String) content; // 删除引用部分 html = deleteReply(html); // 使用 Jsoup 等库解析 HTML 内容 Document doc = Jsoup.parse(html); System.out.println(doc.text()); } else if (contentType.contains("multipart")) { Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (bodyPart.getContentType().contains("text/plain")) { String text = (String) bodyPart.getContent(); // 删除引用部分 text = deleteReply(text); System.out.println(text); } else if (bodyPart.getContentType().contains("text/html")) { String html = (String) bodyPart.getContent(); // 删除引用部分 html = deleteReply(html); // 使用 Jsoup 等库解析 HTML 内容 Document doc = Jsoup.parse(html); System.out.println(doc.text()); } else if (bodyPart.getContentType().contains("multipart")) { // 处理嵌套的 multipart 部分 // ... } else { // 处理附件部分 // ... } } } ``` 4. 删除邮件引用部分。可以使用正则表达式或者字符串处理函数等方法实现。 ```java private static String deleteReply(String text) { // 删除带有 ">" 前缀的行 String regex = "(?m)^\\s*>.*$"; text = text.replaceAll(regex, ""); // 删除带有 "On ... wrote:" 或者 "在 ... 写道:" 前缀的部分 regex = "(?m)^\\s*(On\\s.*?wrote:|在\\s.*?写道:).*$"; text = text.replaceAll(regex, ""); // 删除多余的空行和空格 regex = "(?m)^[ \t]*\r?\n|^[ \t]+"; text = text.replaceAll(regex, ""); return text; } ``` 5. 关闭文件夹和存储库。 ```java folder.close(false); store.close(); ``` 完整的代码示例: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; public class ReadEmail { public static void main(String[] args) throws Exception { String host = "imap.gmail.com"; String username = "username@gmail.com"; String password = "password"; Properties props = new Properties(); props.setProperty("mail.store.protocol", "imap"); Session session = Session.getInstance(props); Store store = session.getStore(); store.connect(host, username, password); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); int messageNumber = 1; Message message = folder.getMessage(messageNumber); String contentType = message.getContentType(); Object content = message.getContent(); if (contentType.contains("text/plain")) { String text = (String) content; text = deleteReply(text); System.out.println(text); } else if (contentType.contains("text/html")) { String html = (String) content; html = deleteReply(html); Document doc = Jsoup.parse(html); System.out.println(doc.text()); } else if (contentType.contains("multipart")) { Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (bodyPart.getContentType().contains("text/plain")) { String text = (String) bodyPart.getContent(); text = deleteReply(text); System.out.println(text); } else if (bodyPart.getContentType().contains("text/html")) { String html = (String) bodyPart.getContent(); html = deleteReply(html); Document doc = Jsoup.parse(html); System.out.println(doc.text()); } else if (bodyPart.getContentType().contains("multipart")) { // 处理嵌套的 multipart 部分 // ... } else { // 处理附件部分 // ... } } } folder.close(false); store.close(); } private static String deleteReply(String text) { String regex = "(?m)^\\s*>.*$"; text = text.replaceAll(regex, ""); regex = "(?m)^\\s*(On\\s.*?wrote:|在\\s.*?写道:).*$"; text = text.replaceAll(regex, ""); regex = "(?m)^[ \t]*\r?\n|^[ \t]+"; text = text.replaceAll(regex, ""); return text; } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值