文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java实现读取163邮箱,qq邮箱的邮件内容

2024-04-02 19:55

关注

通过使用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 = "";
    
    private StringBuffer bodyText = new StringBuffer();
 
    
    public ShowMail(MimeMessage mimeMessage) {
        this.mimeMessage = mimeMessage;
    }
 
    
    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;
    }
 
    
    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);
    }
 
    
    public String getSubject() throws MessagingException, UnsupportedEncodingException {
        String subject = MimeUtility.decodeText(mimeMessage.getSubject());
        if (subject == null) {
            subject = "";
        }
        return subject;
    }
 
    
    public String getSentDate() throws MessagingException {
        Date sentDate = mimeMessage.getSentDate();
        SimpleDateFormat format = new SimpleDateFormat(NORM_DATETIME_PATTERN);
        return format.format(sentDate);
    }
 
    
    public String getBodyText() {
        return bodyText.toString();
    }
 
    
    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
    public boolean getReplySign() throws MessagingException {
 
        boolean replySign = false;
 
        String needReply[] = mimeMessage.getHeader("Disposition-Notification-To");
 
        if (needReply != null) {
            replySign = true;
        }
        return replySign;
    }
 
    
    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;
    }
 
    
    public boolean isContainAttach(Part part) throws MessagingException, IOException {
        boolean attachFlag = false;
        if (part.isMimeType("multipart
    public void saveAttachMent(Part part) throws MessagingException, IOException {
        String fileName;
        if (part.isMimeType("multipart
    public void setAttachPath(String attachPath) {
        this.saveAttachPath = attachPath;
    }
 
    
    public String getAttachPath() {
        return saveAttachPath;
    }
 
    
    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);
    }
 
    
    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();
    }
 
    
    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();
    }
 
    
    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;
    }
 
    
    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读取邮箱邮件内容内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯