maven之javamail操作qq的smtp与imap

参考:

Java mail 官网 https://java.net/projects/javamail/pages/Home#Samples

  maven 添加javamail支持               http://blog.csdn.net/dai_richard/article/details/7070713

 qq的imap需要使用ssl 的993端口进行通信  http://blog.csdn.net/superstorm5/article/details/2157022

书籍– java 网络编程精解(孙卫琴)


先看一些理论的东西






qq的邮箱账号 先要开通imap/smtp  在邮箱的  设置–账号 里面 如下





最后再来个测试代码  代码上都加了注释 不废话

  1. package com.undergrowth;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Date;  
  5. import java.util.Enumeration;  
  6. import java.util.Properties;  
  7.   
  8. import javax.activation.DataHandler;  
  9. import javax.activation.FileDataSource;  
  10. import javax.mail.Authenticator;  
  11. import javax.mail.BodyPart;  
  12. import javax.mail.Folder;  
  13. import javax.mail.Header;  
  14. import javax.mail.Message;  
  15. import javax.mail.MessagingException;  
  16. import javax.mail.Multipart;  
  17. import javax.mail.Part;  
  18. import javax.mail.PasswordAuthentication;  
  19. import javax.mail.Session;  
  20. import javax.mail.Store;  
  21. import javax.mail.Transport;  
  22. import javax.mail.internet.AddressException;  
  23. import javax.mail.internet.InternetAddress;  
  24. import javax.mail.internet.MimeBodyPart;  
  25. import javax.mail.internet.MimeMessage;  
  26. import javax.mail.internet.MimeMultipart;  
  27.   
  28.   
  29. /** 
  30.  * 简单发送和接收邮件 
  31.  * @author u1 
  32.  * 
  33.  */  
  34. public class SimpleSendReceiveMessage {  
  35.   
  36.     //邮件通信会话  
  37.     Session session;  
  38.     //邮件接收处理对象  
  39.     Store store;  
  40.       
  41.     //连接邮件发送的账号与密码  
  42.     String username=”xxxxxxx”;  
  43.     private String passwd=“xxxxxx”;  
  44.     private String receiveHost=“imap.qq.com”;  
  45.     private String sendHost=“smtp.qq.com”;  
  46.       
  47.     /** 
  48.      * 邮件配置参数和连接接收邮件服务器 
  49.      * @throws MessagingException 
  50.      */  
  51.     private void init() throws MessagingException{  
  52.         Properties properties=new Properties();  
  53.         //设置发送和接收协议  
  54.         properties.put(”mail.transport.protocal”“smtp”);  
  55.         properties.put(”mail.store.protocal”“imap”);  
  56.         //设置ssl的端口  
  57.         properties.setProperty(”mail.imap.socketFactory.class”“javax.net.ssl.SSLSocketFactory”);  
  58.         properties.setProperty(”mail.imap.socketFactory.fallback”“false”);  
  59.         properties.setProperty(”mail.imap.port”“993”);  
  60.         properties.setProperty(”mail.imap.socketFactory.port”“993”);/* 
  61.         properties.put(“mail.imap.port”, “993”); 
  62.         properties.put(“mail.smtp.port”, “465”);*/  
  63.         //smtp认证  
  64.         properties.put(”mail.smtp.auth”“true”);  
  65.         //设置发送和接收处理类  
  66.         properties.put(”mail.transport.class”“com.sun.mail.smtp.SMTPTransport”);  
  67.         properties.put(”mail.imap.class”“com.sun.mail.imap.IMAPStore”);  
  68.         //设置发送邮件服务器  
  69.         properties.put(”mail.smtp.host”,sendHost);  
  70.         //获取邮件通信会话  
  71.         Authenticator auth=new MailAuthenticator();  
  72.         session=Session.getDefaultInstance(properties,auth);  
  73.         session.setDebug(true);  
  74.         //获取接收邮件对象  
  75.         store=session.getStore(”imap”);  
  76.         //连接接收邮件服务器  
  77.         store.connect(receiveHost, nullnull);  
  78.     }  
  79.       
  80.     /** 
  81.      * 关闭邮件接收服务器 
  82.      * @throws MessagingException 
  83.      * @throws IOException  
  84.      */  
  85.     public void close() throws MessagingException, IOException  
  86.     {  
  87.         store.close();  
  88.           
  89.     }  
  90.       
  91.     /** 
  92.      * 创建一封简单的邮件 
  93.      * @param fromAddr 
  94.      * @param toAddr 
  95.      * @return 
  96.      * @throws AddressException 
  97.      * @throws MessagingException 
  98.      */  
  99.     public Message createSimpleMessage(String fromAddr,String toAddr) throws AddressException, MessagingException{  
  100.         //建立一封邮件  
  101.         MimeMessage message=new MimeMessage(session);  
  102.         //设置发送者和接收者  
  103.         message.setFrom(new InternetAddress(fromAddr));  
  104.         message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));  
  105.         //设置主题  
  106.         message.setSubject(”使用JAVAMAIL发送邮件”);  
  107.         //设置日期  
  108.         message.setSentDate(new Date(System.currentTimeMillis()));  
  109.         //设置正文  
  110.         message.setText(”今天是2015-6-12,离职一个周,准备下一份工作”);  
  111.         return message;  
  112.     }  
  113.       
  114.     public Message createComplexMessage(String fromAddr,String toAddr) throws AddressException, MessagingException{  
  115.         //建立一封邮件  
  116.         MimeMessage message=new MimeMessage(session);  
  117.         //设置发送者和接收者  
  118.         message.setFrom(new InternetAddress(fromAddr));  
  119.         message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));  
  120.         //设置主题  
  121.         message.setSubject(”使用JAVAMAIL发送邮件”);  
  122.         //设置日期  
  123.         message.setSentDate(new Date(System.currentTimeMillis()));  
  124.         //设置正文  
  125.         Multipart mp=createMultiPart();  
  126.         message.setContent(mp);  
  127.         return message;  
  128.     }  
  129.       
  130.     /** 
  131.      * 创建复杂的正文 
  132.      * @return 
  133.      * @throws MessagingException  
  134.      */  
  135.     private Multipart createMultiPart() throws MessagingException {  
  136.         // TODO Auto-generated method stub  
  137.         Multipart multipart=new MimeMultipart();  
  138.           
  139.         //第一块  
  140.         BodyPart bodyPart1=new MimeBodyPart();  
  141.         bodyPart1.setText(”创建复杂的邮件,此为正文部分”);  
  142.         multipart.addBodyPart(bodyPart1);  
  143.           
  144.         //第二块 以附件形式存在  
  145.         MimeBodyPart bodyPart2=new MimeBodyPart();  
  146.         //设置附件的处理器  
  147.         FileDataSource attachFile=new FileDataSource(ClassLoader.getSystemResource(“attach.txt”).getFile());  
  148.         DataHandler dh=new DataHandler(attachFile);  
  149.         bodyPart2.setDataHandler(dh);  
  150.         bodyPart2.setDisposition(Part.ATTACHMENT);  
  151.         bodyPart2.setFileName(”test”);  
  152.         multipart.addBodyPart(bodyPart2);  
  153.           
  154.         return multipart;  
  155.     }  
  156.   
  157.     /** 
  158.      * 发送邮件 
  159.      * @param message 
  160.      * @throws MessagingException 
  161.      */  
  162.     public void send(Message message) throws MessagingException{  
  163.         Transport.send(message);  
  164.     }  
  165.       
  166.     /** 
  167.      * 接收邮件 
  168.      * @throws Exception  
  169.      */  
  170.     public void receive() throws Exception{  
  171.         browseMessageFromFolder(”INBOX”);  
  172.     }  
  173.   
  174.     /** 
  175.      * 根据邮件夹名称浏览邮件 
  176.      * @param folderName 
  177.      * @throws Exception 
  178.      */  
  179.     private void browseMessageFromFolder(String folderName) throws Exception {  
  180.         // TODO Auto-generated method stub  
  181.         Folder folder=store.getFolder(folderName);  
  182.         if(folder==nullthrow new Exception(folderName+“邮件夹不存在”);  
  183.         browseMessageFromFolder(folder);  
  184.     }  
  185.   
  186.     /** 
  187.      * 根据邮件夹对象浏览邮件 
  188.      * @param folder 
  189.      * @throws MessagingException  
  190.      * @throws IOException  
  191.      */  
  192.     private void browseMessageFromFolder(Folder folder) throws MessagingException, IOException {  
  193.         // TODO Auto-generated method stub  
  194.         folder.open(Folder.READ_ONLY);  
  195.         System.out.println(”总共有”+folder.getMessageCount()+“封邮件”);  
  196.         System.out.println(”总共有”+folder.getUnreadMessageCount()+“封未读邮件”);  
  197.         Message[] messages=folder.getMessages();  
  198.         for (int i = 1; i <=messages.length; i++) {  
  199.             System.out.println(”这是第”+i+“封邮件”);  
  200.             getMessageHeader(folder.getMessage(i));  
  201.             writeSubjectToOutPutStream(folder.getMessage(i));;  
  202.         }  
  203.         folder.close(false);  
  204.     }  
  205.       
  206.     /** 
  207.      * 遍历每封邮件的头部部分 
  208.      * @param message 
  209.      * @throws MessagingException  
  210.      */  
  211.     private void getMessageHeader(Message message) throws MessagingException {  
  212.         // TODO Auto-generated method stub  
  213.         @SuppressWarnings(“unchecked”)  
  214.         Enumeration<Header> allHeader=message.getAllHeaders();  
  215.         for(;allHeader.hasMoreElements();){  
  216.             Header header=allHeader.nextElement();  
  217.             System.out.println(header.getName()+”:”+header.getValue());  
  218.         }  
  219.     }  
  220.   
  221.     /** 
  222.      * 将每封邮件的主题写入输出流中 
  223.      * @param message 
  224.      * @throws MessagingException  
  225.      */  
  226.     private void writeSubjectToOutPutStream(Message message) throws MessagingException {  
  227.         // TODO Auto-generated method stub  
  228.         System.out.println(”邮件主题为:”+message.getSubject());  
  229.     }  
  230.   
  231.     public static void main(String[] args){  
  232.         SimpleSendReceiveMessage sendReceiveMessage=new SimpleSendReceiveMessage();  
  233.         try {  
  234.             sendReceiveMessage.init();  
  235.             Message message=sendReceiveMessage.createSimpleMessage(sendReceiveMessage.username, sendReceiveMessage.username);  
  236.             sendReceiveMessage.send(message);  
  237.             message=sendReceiveMessage.createComplexMessage(sendReceiveMessage.username, sendReceiveMessage.username);  
  238.             sendReceiveMessage.send(message);  
  239.             sendReceiveMessage.receive();  
  240.             sendReceiveMessage.close();  
  241.         } catch (Exception e) {  
  242.             // TODO: handle exception  
  243.             e.printStackTrace();  
  244.         }  
  245.     }  
  246.       
  247.     /** 
  248.      * 登陆认证 
  249.      * @author u1 
  250.      * 
  251.      */  
  252.     private class MailAuthenticator extends Authenticator{  
  253.   
  254.         @Override  
  255.         protected PasswordAuthentication getPasswordAuthentication() {  
  256.             // TODO Auto-generated method stub  
  257.             return new PasswordAuthentication(username, passwd);  
  258.         }  
  259.           
  260.     }  
  261. }  
package com.undergrowth;

import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


/**
 * 简单发送和接收邮件
 * @author u1
 *
 */
public class SimpleSendReceiveMessage {

    //邮件通信会话
    Session session;
    //邮件接收处理对象
    Store store;

    //连接邮件发送的账号与密码
    String username="xxxxxxx";
    private String passwd="xxxxxx";
    private String receiveHost="imap.qq.com";
    private String sendHost="smtp.qq.com";

    /**
     * 邮件配置参数和连接接收邮件服务器
     * @throws MessagingException
     */
    private void init() throws MessagingException{
        Properties properties=new Properties();
        //设置发送和接收协议
        properties.put("mail.transport.protocal", "smtp");
        properties.put("mail.store.protocal", "imap");
        //设置ssl的端口
        properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.imap.socketFactory.fallback", "false");
        properties.setProperty("mail.imap.port", "993");
        properties.setProperty("mail.imap.socketFactory.port", "993");/*
        properties.put("mail.imap.port", "993");
        properties.put("mail.smtp.port", "465");*/
        //smtp认证
        properties.put("mail.smtp.auth", "true");
        //设置发送和接收处理类
        properties.put("mail.transport.class", "com.sun.mail.smtp.SMTPTransport");
        properties.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");
        //设置发送邮件服务器
        properties.put("mail.smtp.host",sendHost);
        //获取邮件通信会话
        Authenticator auth=new MailAuthenticator();
        session=Session.getDefaultInstance(properties,auth);
        session.setDebug(true);
        //获取接收邮件对象
        store=session.getStore("imap");
        //连接接收邮件服务器
        store.connect(receiveHost, null, null);
    }

    /**
     * 关闭邮件接收服务器
     * @throws MessagingException
     * @throws IOException 
     */
    public void close() throws MessagingException, IOException
    {
        store.close();

    }

    /**
     * 创建一封简单的邮件
     * @param fromAddr
     * @param toAddr
     * @return
     * @throws AddressException
     * @throws MessagingException
     */
    public Message createSimpleMessage(String fromAddr,String toAddr) throws AddressException, MessagingException{
        //建立一封邮件
        MimeMessage message=new MimeMessage(session);
        //设置发送者和接收者
        message.setFrom(new InternetAddress(fromAddr));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
        //设置主题
        message.setSubject("使用JAVAMAIL发送邮件");
        //设置日期
        message.setSentDate(new Date(System.currentTimeMillis()));
        //设置正文
        message.setText("今天是2015-6-12,离职一个周,准备下一份工作");
        return message;
    }

    public Message createComplexMessage(String fromAddr,String toAddr) throws AddressException, MessagingException{
        //建立一封邮件
        MimeMessage message=new MimeMessage(session);
        //设置发送者和接收者
        message.setFrom(new InternetAddress(fromAddr));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
        //设置主题
        message.setSubject("使用JAVAMAIL发送邮件");
        //设置日期
        message.setSentDate(new Date(System.currentTimeMillis()));
        //设置正文
        Multipart mp=createMultiPart();
        message.setContent(mp);
        return message;
    }

    /**
     * 创建复杂的正文
     * @return
     * @throws MessagingException 
     */
    private Multipart createMultiPart() throws MessagingException {
        // TODO Auto-generated method stub
        Multipart multipart=new MimeMultipart();

        //第一块
        BodyPart bodyPart1=new MimeBodyPart();
        bodyPart1.setText("创建复杂的邮件,此为正文部分");
        multipart.addBodyPart(bodyPart1);

        //第二块 以附件形式存在
        MimeBodyPart bodyPart2=new MimeBodyPart();
        //设置附件的处理器
        FileDataSource attachFile=new FileDataSource(ClassLoader.getSystemResource("attach.txt").getFile());
        DataHandler dh=new DataHandler(attachFile);
        bodyPart2.setDataHandler(dh);
        bodyPart2.setDisposition(Part.ATTACHMENT);
        bodyPart2.setFileName("test");
        multipart.addBodyPart(bodyPart2);

        return multipart;
    }

    /**
     * 发送邮件
     * @param message
     * @throws MessagingException
     */
    public void send(Message message) throws MessagingException{
        Transport.send(message);
    }

    /**
     * 接收邮件
     * @throws Exception 
     */
    public void receive() throws Exception{
        browseMessageFromFolder("INBOX");
    }

    /**
     * 根据邮件夹名称浏览邮件
     * @param folderName
     * @throws Exception
     */
    private void browseMessageFromFolder(String folderName) throws Exception {
        // TODO Auto-generated method stub
        Folder folder=store.getFolder(folderName);
        if(folder==null) throw new Exception(folderName+"邮件夹不存在");
        browseMessageFromFolder(folder);
    }

    /**
     * 根据邮件夹对象浏览邮件
     * @param folder
     * @throws MessagingException 
     * @throws IOException 
     */
    private void browseMessageFromFolder(Folder folder) throws MessagingException, IOException {
        // TODO Auto-generated method stub
        folder.open(Folder.READ_ONLY);
        System.out.println("总共有"+folder.getMessageCount()+"封邮件");
        System.out.println("总共有"+folder.getUnreadMessageCount()+"封未读邮件");
        Message[] messages=folder.getMessages();
        for (int i = 1; i <=messages.length; i++) {
            System.out.println("这是第"+i+"封邮件");
            getMessageHeader(folder.getMessage(i));
            writeSubjectToOutPutStream(folder.getMessage(i));;
        }
        folder.close(false);
    }

    /**
     * 遍历每封邮件的头部部分
     * @param message
     * @throws MessagingException 
     */
    private void getMessageHeader(Message message) throws MessagingException {
        // TODO Auto-generated method stub
        @SuppressWarnings("unchecked")
        Enumeration<Header> allHeader=message.getAllHeaders();
        for(;allHeader.hasMoreElements();){
            Header header=allHeader.nextElement();
            System.out.println(header.getName()+":"+header.getValue());
        }
    }

    /**
     * 将每封邮件的主题写入输出流中
     * @param message
     * @throws MessagingException 
     */
    private void writeSubjectToOutPutStream(Message message) throws MessagingException {
        // TODO Auto-generated method stub
        System.out.println("邮件主题为:"+message.getSubject());
    }

    public static void main(String[] args){
        SimpleSendReceiveMessage sendReceiveMessage=new SimpleSendReceiveMessage();
        try {
            sendReceiveMessage.init();
            Message message=sendReceiveMessage.createSimpleMessage(sendReceiveMessage.username, sendReceiveMessage.username);
            sendReceiveMessage.send(message);
            message=sendReceiveMessage.createComplexMessage(sendReceiveMessage.username, sendReceiveMessage.username);
            sendReceiveMessage.send(message);
            sendReceiveMessage.receive();
            sendReceiveMessage.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 登陆认证
     * @author u1
     *
     */
    private class MailAuthenticator extends Authenticator{

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            // TODO Auto-generated method stub
            return new PasswordAuthentication(username, passwd);
        }

    }
}


maven的javamail依赖

  1. <dependencies>  
  2.         <dependency>  
  3.             <groupId>javax.activation</groupId>  
  4.             <artifactId>activation</artifactId>  
  5.             <version>1.1</version>  
  6.         </dependency>  
  7.         <dependency>  
  8.             <groupId>javax.mail</groupId>  
  9.             <artifactId>mail</artifactId>  
  10.             <version>1.4</version>  
  11.         </dependency>  
  12.   
  13.     </dependencies>  
<dependencies>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>

    </dependencies>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值