使用JavaMail接收QQ邮箱邮件

使用pop3协议无法获取邮件的状态,改用了imap协议

import java.security.Security;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;

public class Mail {
    public static void main(String[] args) throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";//ssl加密,jdk1.8无法使用

        // 定义连接imap服务器的属性信息
        String port = "993";
        String imapServer = "imap.qq.com";
        String protocol = "imap";
        String username = "xxx@qq.com";
        String password = "xxxx"; // QQ邮箱的授权码

        //有些参数可能不需要
        Properties props = new Properties();
        props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.imap.socketFactory.fallback", "false");
        props.setProperty("mail.transport.protocol", protocol); // 使用的协议
        props.setProperty("mail.imap.port", port);
        props.setProperty("mail.imap.socketFactory.port", port);

        // 获取连接
        Session session = Session.getDefaultInstance(props);
        session.setDebug(false);

        // 获取Store对象
        Store store = session.getStore(protocol);
        store.connect(imapServer, username, password); // 登陆认证

        // 通过imap协议获得Store对象调用这个方法时,邮件夹名称只能指定为"INBOX"
        Folder folder = store.getFolder("INBOX");// 获得用户的邮件帐户
        folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限

        int n = folder.getUnreadMessageCount();// 得到未读数量
        System.out.println("unread" + n);

        FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); // false代表未读,true代表已读
        Message messages[] = folder.search(ft);
        for (Message message : messages) {
            String subject = message.getSubject();// 获得邮件主题
            Address from = (Address) message.getFrom()[0];// 获得发送者地址
            System.out.println("邮件的主题为: " + subject);
            System.out.println("发件人地址为: "+decodeText(from.toString()));
            System.out.println("日期:" + message.getSentDate());  
/*            Enumeration headers = message.getAllHeaders();     
              System.out.println("----------------------allHeaders-----------------------------");   
              while (headers.hasMoreElements()) {     
                     Header header = (Header)headers.nextElement();    
                     System.out.println(header.getName()+" ======= "+header.getValue());    
                     System.out.println("----------------------------");
                 }*/ 
            parseMultipart((Multipart) message.getContent());
            message.setFlag(Flags.Flag.SEEN, false);     //imap读取后邮件状态会变为已读,设为未读
        }

        folder.close(false);// 关闭邮件夹对象
        store.close(); // 关闭连接对象
    }
    protected static 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;
}


    /**    
     * 对复杂邮件的解析   
     * @param multipart   
     * @throws MessagingException   
     * @throws IOException   
     */    
    public static void parseMultipart(Multipart multipart) throws MessagingException, IOException {     
        int count = multipart.getCount();     
        System.out.println("couont =  "+count);     
        for (int idx=0;idx<count;idx++) {     
            BodyPart bodyPart = multipart.getBodyPart(idx);     
            System.out.println(bodyPart.getContentType());     
            if (bodyPart.isMimeType("text/plain")) {     
                System.out.println("plain................."+bodyPart.getContent());     
            } else if(bodyPart.isMimeType("text/html")) {     
                System.out.println("html..................."+bodyPart.getContent());     
            } else if(bodyPart.isMimeType("multipart/*")) {     
                Multipart mpart = (Multipart)bodyPart.getContent();     
                parseMultipart(mpart);     

            } else if (bodyPart.isMimeType("application/octet-stream")) {     
                String disposition = bodyPart.getDisposition();     
                System.out.println(disposition);     
                if (disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {     
                    String fileName = bodyPart.getFileName();     
                    InputStream is = bodyPart.getInputStream();     
                    copy(is, new FileOutputStream("D:\\"+fileName));     
                }     
            }     
        }     
    }  

    /**     
     * 文件拷贝,在用户进行附件下载的时候,可以把附件的InputStream传给用户进行下载     
     * @param is     
     * @param os     
     * @throws IOException     
     */     
    public static void copy(InputStream is, OutputStream os) throws IOException {     
        byte[] bytes = new byte[1024];     
        int len = 0;     
        while ((len=is.read(bytes)) != -1 ) {     
            os.write(bytes, 0, len);     
        }     
        if (os != null)     
            os.close();     
        if (is != null)     
            is.close();     
    } 
}

参考:
http://www.cnblogs.com/huangminwen/p/6096124.html
http://blog.csdn.net/haigenwong/article/details/7610839
http://www.cnblogs.com/wpcnblog/p/3688595.html
http://blog.csdn.net/tzs_1041218129/article/details/52195922

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Java收取QQ邮箱的代码示例: ```java import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class QQMailReceiver { public static void main(String[] args) { String host = "imap.qq.com"; // QQ邮箱IMAP服务器地址 String username = "your_qq_email@qq.com"; // QQ邮箱账号 String password = "your_qq_email_password"; // QQ邮箱密码 Properties props = new Properties(); props.setProperty("mail.store.protocol", "imap"); props.setProperty("mail.imap.host", host); props.setProperty("mail.imap.port", "993"); props.setProperty("mail.imap.ssl.enable", "true"); try { Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imap"); store.connect(host, username, password); Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Message[] messages = inbox.getMessages(); for (Message message : messages) { System.out.println("From: " + InternetAddress.toString(message.getFrom())); System.out.println("Subject: " + message.getSubject()); System.out.println("Sent Date: " + message.getSentDate()); System.out.println("Message: "); System.out.println(message.getContent().toString()); } inbox.close(false); store.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 其中,需要替换的部分包括: - `host`:QQ邮箱IMAP服务器地址,一般为`imap.qq.com`。 - `username`:QQ邮箱账号,需要替换为自己的QQ邮箱账号。 - `password`:QQ邮箱密码,需要替换为自己的QQ邮箱密码。 此代码使用JavaMail API实现了收取QQ邮箱的功能。具体步骤包括: 1. 创建一个`Properties`对象,设置IMAP协议相关的参数。 2. 创建一个`Session`对象,用于连接IMAP服务器。 3. 通过`Session`对象获取`Store`对象,用于连接邮箱账号。 4. 打开收件箱`INBOX`,获取其中的所有邮件。 5. 遍历所有邮件,输出邮件的发件人、主题、发送时间和内容。 6. 关闭收件箱和邮箱连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值