精华内容
下载资源
问答
  • java邮件读取工具类,可读取附件,功能强大,经测试可用。
  • java连接Lotes邮件服务器(Domino) 读取邮件内容附件完整实例
  • 完美邮件读取,各种格式附件获取,完美DEMO源码演示,处理已有BUG
  • 项目中要求读取指定邮件未读邮件的内容,在网上查了很多资料发现都不行,不是自己想要的,要么是读取最新的,要么是读取第一封邮件,根本就不能读取未读的旧邮件。...java读取未读邮件内容包括附件包含javamail.jar
  • javamail 实例 获取pop3或者imap方式获取邮件信息,配置运行MailHelper即可.
  • 2、POP3只能读取收件箱(INBOX),javamail删除后需要等待folder close才能删除(经验证outlook支持同步),经验证qq邮箱无法读取邮件状态及folder的准确邮件数量,outlook可以正确读取邮件状态及邮件数量。...

    一、邮件读取有两种协议:POP3、IMAP

    二、区别:

    1、IMAP是双向协议,能够准确读取收件箱(INBOX)、垃圾邮件等folder的状态,javamail删除会立马同步到邮箱上,安全性高于POP3。

    2、POP3只能读取收件箱(INBOX),javamail删除后需要等待 folder.close(true) 才能删除(经验证outlook支持同步),经验证qq邮箱无法读取邮件状态及folder的准确邮件数量,outlook可以正确读取邮件状态及邮件数量。

    三、使用:

    1、IMAP安全性高于POP3且实效性高,如果只读取文本或者读取邮件附件频率不高的时候建议使用此协议。

    2、POP3读取附件的速度优于IMAP,经验证400KB的附件IMAP读取需要耗时是POP3的10倍,邮件附件获取频率高,数据量大的时候建议使用此协议。

    四、注意:

    POP3在解析邮件,删除邮件时需要注意并发操作。outlook经验证,并发处理邮件过程中,操作一定频率后会出现邮件无法删除的情况,后续改为串行操作暂未出现异常。

     

     

    展开全文
  • javamail 读取邮箱邮件并下载附件

    千次阅读 2020-11-24 17:13:13
    java 从邮箱里面把附件拿出来 代码直接用 package com.kdmins.mail; import com.sun.mail.pop3.POP3Folder; import com.sun.mail.pop3.POP3Store; import com.sun.mail.util.MailSSLSocketFactory; import java....

    java 从邮箱里面把附件拿出来
    代码直接用
    springboot 项目

     <!--Emial-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-mail</artifactId>
            </dependency>
    
    package com.kdmins.mail;
    
    
    import com.sun.mail.pop3.POP3Folder;
    import com.sun.mail.pop3.POP3Store;
    import com.sun.mail.util.MailSSLSocketFactory;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Properties;
    import javax.mail.Address;
    import javax.mail.BodyPart;
    import javax.mail.Flags;
    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.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    import javax.mail.internet.MimeUtility;
    
    
    /**
     * 邮件接受测试
     */
    
    /**
     * 使用POP3协议接收邮件
     */
    public class POP3ReceiveMailTest {
    
        public static void main(String[] args) throws Exception {
            resceive();
        }
    
        /**
         * 接收邮件   使用之前请先开启邮箱中的协议
         */
        public static void resceive() throws Exception {
    
            Properties props = new Properties();
            props.setProperty("mail.popStore.protocol", "pop3");       // 使用pop3协议
            props.setProperty("mail.pop3.port", "995");           // 端口 每个邮箱端口号都不一样  网易163 是110
    
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.pop3.ssl.enable",true);
            props.put("mail.pop3.ssl.socketFactory",sf);
    
            //props.setProperty("mail.debug", "true");
            props.setProperty("mail.pop3.host", "pop.qq.com");
    
            Session session = Session.getInstance(props);
            POP3Store store = (POP3Store) session.getStore("pop3");
            //这里的密码 是令牌 而不是 真正的邮箱密码,具体请百度
            store.connect("pop.qq.com", 995, "123456@qq.com", "qqqqqqqqqqqqqq");
            POP3Folder folder = (POP3Folder) store.getFolder("INBOX");
    
    
            // 获得收件箱
            //Folder folder = store.getFolder("INBOX");
            /* Folder.READ_ONLY:只读权限
             * Folder.READ_WRITE:可读可写(可以修改邮件的状态)
             */
            folder.open(Folder.READ_WRITE); //打开收件箱
    
            // 由于POP3协议无法获知邮件的状态,所以getUnreadMessageCount得到的是收件箱的邮件总数
            System.out.println("未读邮件数: " + folder.getUnreadMessageCount());
    
            // 由于POP3协议无法获知邮件的状态,所以下面得到的结果始终都是为0
            System.out.println("删除邮件数: " + folder.getDeletedMessageCount());
            System.out.println("新邮件: " + folder.getNewMessageCount());
    
            // 获得收件箱中的邮件总数
            System.out.println("邮件总数: " + folder.getMessageCount());
    
            // 得到收件箱中的所有邮件,并解析
            Message[] messages = folder.getMessages();
            parseMessage(messages);
    
            //得到收件箱中的所有邮件并且删除邮件
            //deleteMessage(messages);
    
            //释放资源
            folder.close(true);
            store.close();
        }
    
        /**
         * 解析邮件
         *
         * @param messages 要解析的邮件列表
         */
        public static void parseMessage(Message... messages) throws MessagingException, IOException {
            if (messages == null || messages.length < 1)
                throw new MessagingException("未找到要解析的邮件!");
    
            // 解析所有邮件
            for (int i = 0, count = messages.length; i < count; i++) {
                MimeMessage msg = (MimeMessage) messages[i];
                System.out.println("------------------解析第" + msg.getMessageNumber() + "封邮件-------------------- ");
                System.out.println("主题: " + getSubject(msg));
                System.out.println("发件人: " + getFrom(msg));
                System.out.println("收件人:" + getReceiveAddress(msg, null));
                System.out.println("发送时间:" + getSentDate(msg, null));
                System.out.println("是否已读:" + isSeen(msg));
                System.out.println("邮件优先级:" + getPriority(msg));
                System.out.println("是否需要回执:" + isReplySign(msg));
                System.out.println("邮件大小:" + msg.getSize() * 1024 + "kb");
                boolean isContainerAttachment = isContainAttachment(msg);
                System.out.println("是否包含附件:" + isContainerAttachment);
                if (isContainerAttachment) {
                    //saveAttachment(msg, "d:\\mailTest\\" + msg.getSubject() + "_" + i + "_"); //保存附件
                    saveAttachment(msg, "d:\\mailTest\\"); //保存附件路径
                }
                StringBuffer content = new StringBuffer(30);
                getMailTextContent(msg, content);
                System.out.println("邮件正文:" + (content.length() > 100 ? content.substring(0, 100) + "..." : content));
                System.out.println("------------------第" + msg.getMessageNumber() + "封邮件解析结束-------------------- ");
                System.out.println();
    
            }
        }
    
    
        /**
         * 解析邮件
         *
         * @param messages 要解析的邮件列表
         */
        public static void deleteMessage(Message... messages) throws MessagingException, IOException {
            if (messages == null || messages.length < 1)
                throw new MessagingException("未找到要解析的邮件!");
    
            // 解析所有邮件
            for (int i = 0, count = messages.length; i < count; i++) {
    
                /**
                 *   邮件删除
                 */
                Message message = messages[i];
                String subject = message.getSubject();
                // set the DELETE flag to true
                message.setFlag(Flags.Flag.DELETED, true);
                System.out.println("Marked DELETE for message: " + subject);
    
    
            }
        }
    
        /**
         * 获得邮件主题
         *
         * @param msg 邮件内容
         * @return 解码后的邮件主题
         */
        public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {
            return MimeUtility.decodeText(msg.getSubject());
        }
    
        /**
         * 获得邮件发件人
         *
         * @param msg 邮件内容
         * @return 姓名 <Email地址>
         * @throws MessagingException
         * @throws UnsupportedEncodingException
         */
        public static String getFrom(MimeMessage msg) throws MessagingException, UnsupportedEncodingException {
            String from = "";
            Address[] froms = msg.getFrom();
            if (froms.length < 1)
                throw new MessagingException("没有发件人!");
    
            InternetAddress address = (InternetAddress) froms[0];
            String person = address.getPersonal();
            if (person != null) {
                person = MimeUtility.decodeText(person) + " ";
            } else {
                person = "";
            }
            from = person + "<" + address.getAddress() + ">";
    
            return from;
        }
    
        /**
         * 根据收件人类型,获取邮件收件人、抄送和密送地址。如果收件人类型为空,则获得所有的收件人
         * <p>Message.RecipientType.TO  收件人</p>
         * <p>Message.RecipientType.CC  抄送</p>
         * <p>Message.RecipientType.BCC 密送</p>
         *
         * @param msg  邮件内容
         * @param type 收件人类型
         * @return 收件人1 <邮件地址1>, 收件人2 <邮件地址2>, ...
         * @throws MessagingException
         */
        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();
        }
    
        /**
         * 获得邮件发送时间
         *
         * @param msg 邮件内容
         * @return yyyy年mm月dd日 星期X HH:mm
         * @throws MessagingException
         */
        public static 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 ";
    
            return new SimpleDateFormat(pattern).format(receivedDate);
        }
    
        /**
         * 判断邮件中是否包含附件
         * <p>
         * //* @param msg 邮件内容
         *
         * @return 邮件中存在附件返回true,不存在返回false
         * @throws MessagingException
         * @throws IOException
         */
        public static boolean isContainAttachment(Part part) throws MessagingException, IOException {
            boolean flag = false;
            if (part.isMimeType("multipart/*")) {
                MimeMultipart multipart = (MimeMultipart) part.getContent();
                int partCount = multipart.getCount();
                for (int i = 0; i < partCount; i++) {
                    BodyPart bodyPart = multipart.getBodyPart(i);
                    String disp = bodyPart.getDisposition();
                    if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                        flag = true;
                    } else if (bodyPart.isMimeType("multipart/*")) {
                        flag = isContainAttachment(bodyPart);
                    } else {
                        String contentType = bodyPart.getContentType();
                        if (contentType.indexOf("application") != -1) {
                            flag = true;
                        }
    
                        if (contentType.indexOf("name") != -1) {
                            flag = true;
                        }
                    }
    
                    if (flag) break;
                }
            } else if (part.isMimeType("message/rfc822")) {
                flag = isContainAttachment((Part) part.getContent());
            }
            return flag;
        }
    
        /**
         * 判断邮件是否已读
         *
         * @param msg 邮件内容
         * @return 如果邮件已读返回true, 否则返回false
         * @throws MessagingException
         */
        public static boolean isSeen(MimeMessage msg) throws MessagingException {
            return msg.getFlags().contains(Flags.Flag.SEEN);
        }
    
        /**
         * 判断邮件是否需要阅读回执
         *
         * @param msg 邮件内容
         * @return 需要回执返回true, 否则返回false
         * @throws MessagingException
         */
        public static boolean isReplySign(MimeMessage msg) throws MessagingException {
            boolean replySign = false;
            String[] headers = msg.getHeader("Disposition-Notification-To");
            if (headers != null)
                replySign = true;
            return replySign;
        }
    
        /**
         * 获得邮件的优先级
         *
         * @param msg 邮件内容
         * @return 1(High):紧急  3:普通(Normal)  5:低(Low)
         * @throws MessagingException
         */
        public static String getPriority(MimeMessage msg) throws MessagingException {
            String priority = "普通";
            String[] headers = msg.getHeader("X-Priority");
            if (headers != null) {
                String headerPriority = headers[0];
                if (headerPriority.indexOf("1") != -1 || headerPriority.indexOf("High") != -1)
                    priority = "紧急";
                else if (headerPriority.indexOf("5") != -1 || headerPriority.indexOf("Low") != -1)
                    priority = "低";
                else
                    priority = "普通";
            }
            return priority;
        }
    
        /**
         * 获得邮件文本内容
         *
         * @param part    邮件体
         * @param content 存储邮件文本内容的字符串
         * @throws MessagingException
         * @throws IOException
         */
        public static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {
            //如果是文本类型的附件,通过getContent方法可以取到文本内容,但这不是我们需要的结果,所以在这里要做判断
            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);
                }
            }
        }
    
        /**
         * 保存附件
         *
         * @param part    邮件中多个组合体中的其中一个组合体
         * @param destDir 附件保存目录
         * @throws UnsupportedEncodingException
         * @throws MessagingException
         * @throws FileNotFoundException
         * @throws IOException
         */
        public static void saveAttachment(Part part, String destDir) throws UnsupportedEncodingException, MessagingException,
                FileNotFoundException, IOException {
            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);
                    //某一个邮件体也有可能是由多个邮件体组成的复杂体
                    String disp = bodyPart.getDisposition();
                    if (disp != null && (disp.equalsIgnoreCase(Part.ATTACHMENT) || disp.equalsIgnoreCase(Part.INLINE))) {
                        InputStream is = bodyPart.getInputStream();
                        saveFile(is, destDir, decodeText(bodyPart.getFileName()));
                    } else if (bodyPart.isMimeType("multipart/*")) {
                        saveAttachment(bodyPart, destDir);
                    } else {
                        String contentType = bodyPart.getContentType();
                        if (contentType.indexOf("name") != -1 || contentType.indexOf("application") != -1) {
                            saveFile(bodyPart.getInputStream(), destDir, decodeText(bodyPart.getFileName()));
                        }
                    }
                }
            } else if (part.isMimeType("message/rfc822")) {
                saveAttachment((Part) part.getContent(), destDir);
            }
        }
    
        /**
         * 读取输入流中的数据保存至指定目录
         *
         * @param is       输入流
         * @param fileName 文件名
         * @param destDir  文件存储目录
         * @throws FileNotFoundException
         * @throws IOException
         */
        private static void saveFile(InputStream is, String destDir, String fileName)
                throws FileNotFoundException, IOException {
            BufferedInputStream bis = new BufferedInputStream(is);
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(new File(destDir + fileName)));
            int len = -1;
            while ((len = bis.read()) != -1) {
                bos.write(len);
                bos.flush();
            }
            bos.close();
            bis.close();
        }
    
        /**
         * 文本解码
         *
         * @param encodeText 解码MimeUtility.encodeText(String text)方法编码后的文本
         * @return 解码后的文本
         * @throws UnsupportedEncodingException
         */
        public static String decodeText(String encodeText) throws UnsupportedEncodingException {
            if (encodeText == null || "".equals(encodeText)) {
                return "";
            } else {
                return MimeUtility.decodeText(encodeText);
            }
        }
    
    
    }
    
    
    展开全文
  • 使用Java解析邮件时,想要直接读取附件(Excel表格)里的内容,不是下载附件,该怎么实现?
  • 通过Java读取QQ邮件邮件解析-附件资源
  • java邮件带excel附件,以流的形式发送附件,不生成excel文件
  • 使用javax.mail自动读取邮件,并下载解析附件,IMAP/POP3协议等! 直接上代码如下: package *** import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerF...

    搜索网上各个案例,总结的一套比较全面且行之有效的方法。供大家参考使用!

    使用javax.mail自动读取邮件,并下载解析附件,IMAP/POP3协议等!

     

    直接上代码如下:

    package ***
    
    import org.apache.commons.lang3.StringUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    import javax.mail.Address;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.NoSuchProviderException;
    import javax.mail.Part;
    import javax.mail.Session;
    import javax.mail.Store;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeUtility;
    import javax.mail.search.AndTerm;
    import javax.mail.search.ComparisonTerm;
    import javax.mail.search.FromStringTerm;
    import javax.mail.search.SearchTerm;
    import javax.mail.search.SentDateTerm;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Properties;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    /**
     */
    @Component
    public class BlacklistCodeTask {
    
    
        private static Logger logger = LoggerFactory.getLogger(BlacklistCodeTask.class);
    
        @Autowired
        private blacklistService blacklistService;
    
    
    
        // 邮箱附件保存路径
        private static String FILE_SAVE_PATH = ConfigProperties.getProperties("blacklist.emailFilePath");
        // 读取的发件人
        private static String fromEmail = ConfigProperties.getProperties("blacklist.fromEmail");
        // 收件服务器 
        private static String hostServer = ConfigProperties.getProperties("blacklist.hostServer");
        private static String protocol = ConfigProperties.getProperties("blacklist.protocol");
        private static String port = ConfigProperties.getProperties("blacklist.port");
        private static String username = ConfigProperties.getProperties("blacklist.username");
        private static String password = ConfigProperties.getProperties("blacklist.password");
    
        // 执行日期标识
        String dateTimeFlag;
        // 附件名称关键词
        private static String FILE_NAME_FLAG1 = "加黑***明细";
        private static String FILE_NAME_FLAG2 = "加黑";
    
        // Runtime.getRuntime().availableProcessors()
        public static ExecutorService threadPool = Executors.newFixedThreadPool(1);
    
    
        /**
         * 定时任务获取前一天邮件,并解析保存黑端口号码
         */
        public void acquireXinAnEmails() {
            try {
                // 1. 设置连接信息, 生成一个 Session
                // 获取连接
                Session session;
                if ("pop3".equalsIgnoreCase(protocol)) {
                    session = Session.getInstance(getPOP3());
    //                session = Session.getDefaultInstance(getPOP3());
                } else {
    //                session = Session.getDefaultInstance(getIMAP());
                    session = Session.getInstance(getIMAP());
                }
                session.setDebug(false);
                // 2. 获取Store, 并连接到服务器
                Store store = session.getStore(protocol);
                store.connect(hostServer, username, password); // POP3服务器的登陆认证
                //
                Folder defaultFolder = store.getDefaultFolder();// 默认父目录
                if (defaultFolder == null) {
                    logger.error("服务器不可用! hostServer:{}", hostServer);
                    return;
                }
                //
                Folder folder = defaultFolder.getFolder("INBOX");// 获取收件箱
                folder.open(Folder.READ_WRITE);// 可读邮件,可以删邮件的模式打开目录
                // 取出来邮件数
                logger.info("folder urlName: {}, 共有邮件: {}封, UnreadMessages: {}, NewMessages: {}...", folder.getURLName().toString(),
                        folder.getMessageCount(), folder.getUnreadMessageCount(), folder.getNewMessageCount());
                //
                dateTimeFlag = DateTimeUtil.formatDateTime(new Date(), DateTimeUtil.DATA_FORMAT_yyyyMMdd);
                searchMails(folder);
    
                // 7. 关闭 Folder 会真正删除邮件, false 不删除
                folder.close(false);
                // 8. 关闭 store, 断开网络连接
                store.close();
    
            } catch (NoSuchProviderException e) {
                logger.error(e.getMessage(), e);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
    //        // 统一处理下载好的的Excel文件
    //        dealAndGetBlacklist();
            
        }
    
        /**
         * 获取POP3收信配置 995
         *
         * @return
         */
        private Properties getPOP3() {
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", protocol);
            props.setProperty("mail.pop3.host", hostServer); // 按需要更改
            props.setProperty("mail.pop3.port", port);
            // SSL安全连接参数
            props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.pop3.socketFactory.fallback", "false");
            props.setProperty("mail.pop3.socketFactory.port", port);
            // 解决DecodingException: BASE64Decoder: but only got 0 before padding character (=)
            props.setProperty("mail.mime.base64.ignoreerrors", "true");
            return props;
        }
    
        /**
         * 获取IMAP收信配置 993
         *
         * @return
         */
        private Properties getIMAP() {
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", protocol);
            props.setProperty("mail.imap.host", hostServer); // 按需要更改
            props.setProperty("mail.imap.port", port);
            // SSL安全连接参数
            props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.imap.socketFactory.fallback", "false");
            props.setProperty("mail.imap.socketFactory.port", port);
            props.setProperty("mail.mime.base64.ignoreerrors", "true");
            return props;
        }
    
    
        /**
         * 创建搜索条件,并获取邮件...第二天凌晨10分之后执行,查询前一天零点到今天零点的数据
         *
         * @param folder
         * @throws Exception
         */
        private void searchMails(Folder folder) throws Exception {
            //建立搜索条件继承自SearchTerm,像根据发件人,主题搜索,邮件标记FlagTerm等,
            // FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); //false代表未读,true代表已读
            // 搜索昨天收到的的所有邮件
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date start = calendar.getTime();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            Date end = calendar.getTime();
            SearchTerm comparisonTermGe = new SentDateTerm(ComparisonTerm.GE, start);
            SearchTerm comparisonTermLe = new SentDateTerm(ComparisonTerm.LE, end);
            FromStringTerm fromStringTerm = new FromStringTerm(fromEmail);
            SearchTerm andTerm = new AndTerm(new SearchTerm[]{comparisonTermGe, comparisonTermLe, fromStringTerm});
            logger.info("SearchTerm start: {}, end: {}, fromEmail: {}", DateTimeUtil.formatDateTime(start, DateTimeUtil.DATA_FORMAT_yyyy_MM_dd_HH_mm_ss),
                    DateTimeUtil.formatDateTime(end, DateTimeUtil.DATA_FORMAT_yyyy_MM_dd_HH_mm_ss), fromEmail);
            //
            Message[] messages = folder.search(andTerm); //根据设置好的条件获取message
            logger.info("search邮件: " + messages.length + "封, SearchTerm:" + andTerm.getClass());
            // FetchProfile fProfile = new FetchProfile(); // 选择邮件的下载模式,
            // fProfile.add(FetchProfile.Item.ENVELOPE); // 根据网速选择不同的模式
            // folder.fetch(messages, fProfile);// 选择性的下载邮件
            // 5. 循环处理每个邮件并实现邮件转为新闻的功能
            for (int i = 0; i < messages.length; i++) {
                // 单个邮件
                logger.info("---第" + i + "邮件开始------------");
                mailReceiver(messages[i]);
                logger.info("---第" + i + "邮件结束------------");
                // 邮件读取备份保存,用来校验
    //            messages[i].writeTo(new FileOutputStream(FILE_SAVE_PATH + "pop3Mail_" + messages[i].getMessageNumber() + ".eml"));
            }
        }
    
    
        /**
         * 解析邮件
         *
         * @param msg 邮件对象
         * @throws Exception
         */
        private void mailReceiver(Message msg) {
            try {
                // 发件人信息
                Address[] froms = msg.getFrom();
                String mailSubject = transferChinese(msg.getSubject());
                if (froms != null) {
                    InternetAddress addr = (InternetAddress) froms[0];
                    logger.info("发件人地址:" + addr.getAddress() + ", 发件人显示名:" + transferChinese(addr.getPersonal()));
                } else {
                    logger.error("msg.getFrom() is null... subject:" + mailSubject);
                }
                Date sentDate = msg.getSentDate();
                logger.info("邮件主题: {}, sentDate: {}", mailSubject,
                        sentDate == null ? null : DateTimeUtil.formatDateTime(sentDate, DateTimeUtil.DATA_FORMAT_yyyy_MM_dd_HH_mm_ss));
    
                // getContent() 是获取包裹内容, Part相当于外包装
                Object content = msg.getContent();
                if (content instanceof Multipart) {
                    Multipart multipart = (Multipart) content;
                    reMultipart(multipart);
                } else if (content instanceof Part) {
                    Part part = (Part) content;
                    rePart(part);
                } else {
                    String contentType = msg.getContentType();
                    if (contentType != null && contentType.startsWith("text/html")) {
                        logger.warn("---类型:" + contentType);
                    } else {
                        logger.warn("---类型:" + contentType);
                        logger.warn("---内容:" + msg.getContent());
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    
        /**
         * 把邮件主题转换为中文.
         *
         * @param strText the str text
         * @return the string
         */
        public String transferChinese(String strText) {
            try {
                if (StringUtils.isBlank(strText)) {
                    return null;
                }
                strText = MimeUtility.encodeText(new String(strText.getBytes(),
                        "UTF-8"), "UTF-8", "B");
                strText = MimeUtility.decodeText(strText);
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            return strText;
        }
    
    
        /**
         * @param part 解析内容
         * @throws Exception
         */
        private void rePart(Part part) {
            String tempFilePath = null;
            try {
                // 附件
                if (part.getDisposition() != null) {
                    // 邮件附件
                    String strFileName = MimeUtility.decodeText(part.getFileName()); //MimeUtility.decodeText解决附件名乱码问题
                    logger.info("发现附件: {}, 内容类型: {} ", strFileName, MimeUtility.decodeText(part.getContentType()));
                    // 读取附件字节并存储到文件中. xls/xlsx
                    String fileType = strFileName.substring(strFileName.lastIndexOf(".") + 1);
                    if ((fileType.equals("xlsx") || fileType.equals("xls")) &&
                            (strFileName.contains(FILE_NAME_FLAG1) || strFileName.contains(FILE_NAME_FLAG2))) {
                        InputStream in = part.getInputStream();// 打开附件的输入流
                        tempFilePath = FILE_SAVE_PATH + dateTimeFlag + strFileName;
                        FileOutputStream out = new FileOutputStream(tempFilePath);
                        int data;
                        while ((data = in.read()) != -1) {
                            out.write(data);
                        }
                        in.close();
                        out.close();
                    } else {
                        logger.info("not what we need file, discard it: {}", strFileName);
                    }
                } else {
                    // 邮件内容
                    if (part.getContentType().startsWith("text/plain") || part.getContentType().startsWith("Text/Plain")) {
                        logger.info("Content文本内容:" + part.getContent());
                    } else if (part.getContentType().startsWith("text/html")) {
    //                    logger.info("HTML内容:" + part.getContent());
                        logger.debug("HTML内容,,不记录日志展示。。");
                    } else {
                        logger.debug("!其它ContentType:" + part.getContentType() + " ?内容:" + part.getContent());
                    }
                }
            } catch (MessagingException e) {
                logger.error(e.getMessage(), e);
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            } finally {
                // 单个处理黑名单文件,放入线程池处理
                String finalTempFilePath = tempFilePath;
                threadPool.execute(() -> {
                            dealBlacklist(finalTempFilePath);
                        }
                );
            }
        }
    
    
        /**
         * @param multipart // 接卸包裹(含所有邮件内容(包裹+正文+附件))
         * @throws Exception
         */
        private void reMultipart(Multipart multipart) throws Exception {
            logger.debug("Multipart邮件共有" + multipart.getCount() + "部分组成");
            // 依次处理各个部分
            for (int j = 0, n = multipart.getCount(); j < n; j++) {
                Part part = multipart.getBodyPart(j);
                // 解包, 取出 MultiPart的各个部分, 每部分可能是邮件内容, 也可能是另一个小包裹(MultipPart)
                if (part.getContent() instanceof Multipart) {
                    logger.debug("部分" + j + "的ContentType: " + part.getContentType() + ", to reMultipart() ");
                    Multipart p = (Multipart) part.getContent();// 转成小包裹
                    //递归迭代
                    reMultipart(p);
                } else {
                    logger.debug("部分" + j + "的ContentType: " + part.getContentType() + ", to rePart() ");
                    rePart(part);
                }
            }
        }
    
        /**
         * 单个处理下载好的文件
         *
         * @param tempFilePath
         */
        private void dealBlacklist(String tempFilePath) {
            if (StringUtil.isBlank(tempFilePath)) {
                return;
            }
            logger.info("to deal with blacklist Excel file: {}", tempFilePath);
            blacklistService.dealBlacklist(tempFilePath);
    
        }
    
    
    }
    

     

    展开全文
  • 当有需求,需要把当天的报表文件发送给指定邮箱又不小生成多余的...实现过程是先将数据库里的数据,导出excel文件输出流中(注:不是直接生成文件),发送邮件附件内容直接从前面excel文件输出流中获取,然后发送邮件
  • java显示邮件内容和附件的实现

    千次阅读 2018-11-10 23:30:28
    java显示邮件内容和附件的实现   自己找了好久的内容实现,一直弄不好,现终于实现了,来张效果图,吼吼吼吼  解析邮件的PraseMimeMsg.java package com.hstc.util; import com.hstc.dto.AttachmentDTO; ...

                          用java显示邮件内容和附件的实现

     

    自己找了好久的内容实现,一直弄不好,现终于实现了,来张效果图,吼吼吼吼

     解析邮件的PraseMimeMsg.java

    package com.hstc.util;
    
    import com.hstc.dto.AttachmentDTO;
    
    import javax.mail.*;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeUtility;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    
    public class PraseMimeMsg {
    
        private MimeMessage mimeMessage = null;
        private StringBuffer bodytext = new StringBuffer();
    
        public PraseMimeMsg(MimeMessage mimeMessage)
        {
            this.mimeMessage = mimeMessage;
        }
    
        public void setMimeMessage(MimeMessage mimeMessage)
        {
            this.mimeMessage = mimeMessage;
        }
    
        // 例子: panjia@hstc.com<panjia@hstc.com>
        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;
        }
    
        public String getSubject()throws MessagingException
        {
            String subject = "";
            try
            {
                subject = MimeUtility.decodeText(mimeMessage.getSubject());
                if(subject == null) subject="";
            }
            catch(Exception exce){ }
            return subject;
        }
    
        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("Error emailaddr type!");
            }
            return mailaddr;
        }
    
        public String getBodyText()
        {
            return bodytext.toString();
        }
    
        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{}
            //Marking mail as read status.
            if(!mimeMessage.isSet(Flags.Flag.SEEN))
                mimeMessage.setFlag(Flags.Flag.SEEN, true);
        }
    
        public List<AttachmentDTO> handleMultipart() throws Exception
        {
            List<AttachmentDTO> attachments = new ArrayList<AttachmentDTO>();
            String disposition;
            BodyPart part;
            Multipart mp = (Multipart) mimeMessage.getContent();
            if(mp.getContentType() == "text/plain" || mp.getContentType() == "text/html" ){
                return attachments;
            }
            int mpCount = mp.getCount();
            AttachmentDTO attachmentDTO;
            for (int m = 0; m < mpCount; m++)
            {
                part = mp.getBodyPart(m);
                disposition = part.getDisposition();
                if (disposition != null && disposition.equals(Part.ATTACHMENT))
                {
                    String fileName = null;
                    fileName = MimeUtility.decodeText(part.getFileName()); //改了
                    attachmentDTO = new AttachmentDTO();
                    attachmentDTO.setAttName(fileName);
                    attachmentDTO.setMpid(m);
                    attachments.add(attachmentDTO);
                }
            }
            return attachments;
        }
    
        public boolean getReplySign()throws MessagingException
        {
            boolean replysign = false;
            String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
            if(needreply != null)
            {
                replysign = true;
            }
            return replysign;
        }
    
        public double getSize() throws Exception
        {
            float size = mimeMessage.getSize();
            size = size/1024;
            return size;
        }
    
        public String getMessageId()throws MessagingException
        {
            return mimeMessage.getMessageID();
        }
    
        public boolean isNew()throws MessagingException
        {
            boolean isnew = false;
            Flags flags = ((Message)mimeMessage).getFlags();
            Flags.Flag []flag = flags.getSystemFlags();
            for(int i=0;i<flag.length;i++)
            {
                if(flag[i] == Flags.Flag.SEEN)
                {
                    isnew=true;
                    break;
                }
            }
            return isnew;
        }
    
        public String getSentDate()throws Exception
        {
            Date sentdate = mimeMessage.getSentDate();
    
            return DateTimeUtil.dateToStr(sentdate);
        }
    
    
    
    
    }
    


    访问附件需要的AttachmentDTO.java

    package com.hstc.dto;
    
    public class AttachmentDTO {
        // 邮件的MimeMutipart ID
        private int mpid;
        // 附件名称
        private String attName;
    
        public int getMpid() {
            return mpid;
        }
    
        public void setMpid(int mpid) {
            this.mpid = mpid;
        }
    
        public String getAttName() {
            return attName;
        }
    
        public void setAttName(String attName) {
            this.attName = attName;
        }
    }
    

     
    浏览器上下载邮件附件实现 HandleAttachServlet.java

    package com.hstc.servlet;
    
    import javax.mail.*;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class HandleAttachServlet extends javax.servlet.http.HttpServlet {
        protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
            doGet(request,response);
        }
    
        protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    
            response.setContentType("text/html");
            HttpSession session = request.getSession();
            ServletOutputStream out = response.getOutputStream();
            int msgnum = Integer.parseInt(request.getParameter("msgnum"));
            int bodynum = Integer.parseInt(request.getParameter("bodynum"));
            String filename = request.getParameter("filename");
            Folder folder = (Folder) session.getAttribute("folder");
            try {
                Message msg = folder.getMessage(msgnum+1);
                response.setHeader("Content-Disposition", "attachment;filename=" + filename);
                Multipart multi = (Multipart) msg.getContent();
                BodyPart bodyPart = multi.getBodyPart(bodynum);
                InputStream is = bodyPart.getInputStream();
                int c = 0;
                while( (c=is.read()) != -1) {
                    out.write(c);
                }
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }
    


    jsp页面的实现代码

     

    <%
        Users user = (Users) request.getSession().getAttribute(Const.USERNAME);
        // 2、读取邮件夹
        Folder folder = (Folder)request.getSession().getAttribute("folder");
        // 获取邮件夹中第i封邮件信息
        Integer msgnum = Integer.parseInt(request.getParameter("msgnum"));
        String subject = null;
        String from = null;
        String to = null;
        Object content = null;
        String sendDate = null;
        List<AttachmentDTO> attachmentDTOList = null;
        try {
            Message[] messages = folder.getMessages();
            MimeMessage message = (MimeMessage) messages[msgnum];
            PraseMimeMsg pmm = new PraseMimeMsg(message);
            subject = pmm.getSubject();
            from = pmm.getFrom();
            to = pmm.getMailAddress("to");
            sendDate = pmm.getSentDate();
            pmm.getMailContent((Part)message);
            content = pmm.getBodyText();
            attachmentDTOList = pmm.handleMultipart();
    
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    %>
    
    
    
      <center><h1><%=subject%></h1></center>
                                <p>&nbsp;&nbsp;正文:<%=content%></p> <br/>
                               <%
                                   for(int i  = 0; i < attachmentDTOList.size(); i++) {
                               %>
                                附件:<a href="<%=basePath%>HandleAttachServlet?msgnum=<%=msgnum%>&&bodynum=<%=((AttachmentDTO)attachmentDTOList.get(i)).getMpid()%>&&filename=<%=((AttachmentDTO)attachmentDTOList.get(i)).getAttName()%>"> <%=((AttachmentDTO)attachmentDTOList.get(i)).getAttName()%></a>
                                <%
                                   }
                               %>
    
                                <div><span>发件人:<%=from%></span></div>
                                <div><span>发送时间:<%=sendDate%></span></div>
                                <hr/>


    再接再厉,我一定行的!

    展开全文
  • 本人接触的项目中,有很多是有关于进行邮件发送进行预购,通知,通告,报告之类的,所以难免会发很多邮件,但是一个功能写一个方法实在是太繁琐了,所以这是适用于以word/excel的形式,进行邮件发送的方式 package ...
  • String pop3Server = "pop3.163.com"; // 收件服务器 pop3.163.com  8531.icoremail.net  String protocol = "pop3";  String port = "995"; // 邮件服务端口号 995  String username = "trsnj_xiabin@1
  • 我在网上找的demo,当qq邮件里包含附件与正文内容时,只能读取附件,正文就读取不到了。 下面这个是我写的,可以拿过去运行看看。困扰我多时了。 http://blog.csdn.net/qq_19806865/article/details/78855326
  • 原本业务使用javamail通过imap协议读取邮件,后来有个客户那边不支持imap协议,需要改为通过微软的ews(exchange web service)协议读取。结合网上已有的资料,自己测试了一把,以下是可以成功运行的代码 1.maven...
  • java读取邮箱邮件

    千次阅读 2019-07-16 15:15:58
    package org.yangxin.study.jm;...import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; im...
  • Spire.Cloud.SDK for Java提供了PdfAttachmentsApi接口添加附件addAttachment()、下载附件downloadAttachment()、获取附件信息getAttachmentsInfo(),本文将通过Java代码示例介绍具体实现方法。详细内容参考以下步骤...
  • java实现读取邮件发送邮件

    千次阅读 2016-02-18 11:16:40
    有些邮箱pop服务器不支持查看是否邮件已经被查看多的功能,只能通过自己认为添加标识标记邮件是已读还是未读 ... * @return 邮件中存在附件返回true,不存在返回false   * @throws Messag
  • Java读取邮件

    千次阅读 2019-11-01 11:05:42
    smtp协议可以用来发送邮件,IMAP协议可以用来读取邮件。QQ邮箱设置中开启POP3协议。发送邮件javaMail-发送邮件 二、代码实现 参看了一篇几年前的博客,拿过来进行了一些改造,只是一个基版,一些邮箱的东西什么可以...
  • 获取邮件附件.zip

    2019-07-29 16:52:52
    获取邮件的内容获得邮件附件的工具类,使用简单测试可用。
  • 通过Java读取QQ邮件邮件解析

    万次阅读 2016-10-18 11:58:25
    最近为了抓取QQ邮箱中部分邮件中的数据,网上找的资料基本都是基于163邮箱的代码,结合部分代码整理出获取QQ邮箱邮件的方式,记录并共享一下。 资源下载mail.jar(用于连接,获取邮件) jsoup.jar(用于解析html)基础...
  • Java从网络取得文件 1个目标文件 简单 Java从压缩包中提取文件 1个目标文件 简单 Java存储与读取对象 1个目标文件 如题 Java调色板面板源代码 1个目标文件 摘要:Java源码,窗体界面,调色板 使用Java语言编写的一款...
  • emailsmtp=smtp.qq.comemailaddress=459104018@qq.comemailpass=******2、读取配置文件的类文件(ReadPropertity.java) import java.io.IOException;import java.util.Properties;public class ReadPropertity { ...
  • java读取qq邮箱邮件

    2019-09-01 21:48:57
    说起获取邮箱邮件的时候我首选的是网易的,因为之前写了,网易的发邮件,想着再写一个收邮件那就完美了,可以网易的那个。http://config.mail.163.com/settings/imap/index.jsp?uid=xxxxxx@163.com不能使用。于是...
  • java读取邮件

    千次阅读 2017-01-11 10:36:10
    package EPF.view; import EPF.util.ADFUtils; import EPF.util.JSFUtils; import java.io.BufferedInputStream; import java.io.BufferedOutputStream;...import java.io.File;...import java.io.FileNotFoundExcepti

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 6,601
精华内容 2,640
关键字:

java读取邮件附件

java 订阅