java 邮件 接收与发送

...

package com.e6soft;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.BodyTerm;
import javax.mail.search.SearchTerm;
import javax.mail.Address;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import org.quartz.impl.jdbcjobstore.DBSemaphore;

import com.e6soft.base.service.JService;
import com.sun.mail.imap.IMAPMessage;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;



public class MainTest extends JService{

    static String HOST = "smtp.163.com"; // smtp服务器
    static String FROM = "****@163.com"; // 发件人地址
    
    //static String TO = "******@qq.com"; // 收件人地址
    //static String AFFIX = "E:\\安装手册-6.3.5.doc"; // 附件地址
    //static String AFFIXNAME = "安装手册-6.3.5.doc"; // 附件名称
    
    static String USER = "******"; // 用户名
    static String PWD = "**********"; // 163的授权码
    
    //static String SUBJECT = "您愿望单中的 2 件物品正在促销!"; // 邮件标题
    //static String[] TOS = TO.split(",");
    
    public static void main(String[] args) {
        MainTest mainTest=new MainTest();
        //mainTest.send("123456@qq.com","Your registration is complete!","注册验证您好 123456@qq.com!欢迎注册码云,请将验证码填写到注册页面。验证码:******","");
     //(以上是) 发送的邮箱,标题,内容,
        //mainTest.send("请尽快配合申请工作");
        mainTest.getEmailList();
    }

    /* 发件人 -> MUA -> MTA -> MTA -> 若干个MTA -> MDA <- MUA <- 收件人
          本质上就是:
                编写MUA把邮件发到MTA;
                编写MUA从MDA上收邮件。
        发邮件时,MUA和MTA使用的协议就是SMTP:Simple Mail Transfer Protocol,后面的MTA到另一个MTA也是用SMTP协议。
        收邮件时,MUA和MDA使用的协议有两种:POP:Post Office Protocol
        
        在MyEclipse中,会自动给web项目导入javax.mail包中的类,但是不全(其实是只有接口,而没有接口的实现类),所以只靠MyEclipse中的类是不能运行java mail项目的,但是如果这时你再去自行导入mail.jar时,就会出现冲突。
        
        java mail中主要类:javax.mail.Session、javax.mail.internet.MimeMessage、javax.mail.Transport。
            Session:表示会话,即客户端与邮件服务器之间的会话!想获得会话需要给出账户和密码,当然还要给出服务器名称。在邮件服务中的Session对象,就相当于连接数据库时的Connection对象。            
            MimeMessage:表示邮件类,它是Message的子类。它包含邮件的主题(标题)、内容,收件人地址、发件人地址,还可以设置抄送和暗送,甚至还可以设置附件。            
            Transport:用来发送邮件。它是发送器!
     */
    /* 以下是参考 // 接收
    public static void s() throws IOException{
        System.out.print("请输入用户名:");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String userName = in.readLine();
        System.out.print("请输入密码:");
        String password = in.readLine();
        BASE64Encoder encoder = new BASE64Encoder();
        System.out.println("编码后的用户名为:" + encoder.encode(userName.getBytes()));
        System.out.println("编码后的密码为:" + encoder.encode(password.getBytes()));
        
        BASE64Decoder decoder = new BASE64Decoder();
        //邮件主题的Base64编码
        String emailSubject = "=?GBK?B?08q8/rLiytQ=?=";
        //邮件文本内容的Base64编码
        String emailPlainContent = "vPK1pbXE08q8/reiy82y4srUo6E=";
        //带html标签和邮件内容的Base64编码
        String emailHtmlContent = "PFA+vPK1pbXE08q8/reiy82y4srUo6E8L1A+";
        //将使用Base64编码过后的文本内容再使用Base64来解码
        emailSubject = new String(decoder.decodeBuffer(emailSubject),"GBK");
        emailPlainContent = new String(decoder.decodeBuffer(emailPlainContent),"GBK");
        emailHtmlContent = new String(decoder.decodeBuffer(emailHtmlContent),"GBK");
        System.out.println("邮件标题:"+emailSubject);
        System.out.println("邮件内容:"+emailPlainContent);
        System.out.println("带html标签的邮件内容:"+emailHtmlContent);
    }
    // 接收
    public static void ss() throws Exception{
        //收件人地址
        String recipientAddress = "xxx@163.com";
        //收件人账户名
        String recipientAccount = "xxx";
        //收件人账户密码
        String recipientPassword = "xxx";
        
        //1、连接邮件服务器的参数配置
        Properties props = new Properties();
        //设置传输协议
        props.setProperty("mail.store.protocol", "pop3");
        //设置收件人的POP3服务器
        props.setProperty("mail.pop3.host", "pop3.163.com");
        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(props);
        //设置调试信息在控制台打印出来
        //session.setDebug(true);
         
        Store store = session.getStore("pop3");
        //连接收件人POP3服务器
        store.connect("pop3.163.com", recipientAccount, recipientPassword);
        //获得用户的邮件账户,注意通过pop3协议获取某个邮件夹的名称只能为inbox
        Folder folder = store.getFolder("inbox");
        //设置对邮件账户的访问权限
        folder.open(Folder.READ_WRITE);
         
        //得到邮件账户的所有邮件信息
        Message [] messages = folder.getMessages();
        for(int i = 0 ; i < messages.length ; i++){
            //获得邮件主题
            String subject = messages[i].getSubject();
            //获得邮件发件人
            Address[] from = messages[i].getFrom();
            //获取邮件内容(包含邮件内容的html代码)
            String content = (String) messages[i].getContent();
        }
         
        //关闭邮件夹对象
        
        folder.close(false);
        
        //关闭连接对象
        store.close();
    }
    */
    
    
    /**
     * 发送邮件 
     *     sjrdz 收件人地址
     *     bt 标题
     *     context 内容
     * @param host
     * @param user
     * @param pwd
     */
    public static void send(String sjrdz,String bt,String context,String fjId) {
        MainTest MainTest=new MainTest();
        String []TOS=sjrdz.split(",");
        Properties props = new Properties(); // Session 对象利用了java.util.Properties对象获得了邮件服务器、用户名、密码信息  和整个应用程序都要使用到的 共享信息
        props.put("mail.smtp.host", HOST);//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
        props.put("mail.smtp.auth", "true");  //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
        Session session = Session.getDefaultInstance(props);//用props对象构建一个session
        session.setDebug(true);
        MimeMessage message = new MimeMessage(session);//用session为参数定义消息对象
        try {
            message.setFrom(new InternetAddress(FROM));// 加载发件人地址
            InternetAddress[] sendTo = new InternetAddress[TOS.length]; // 加载收件人地址
            for (int i = 0; i < TOS.length; i++) {  
                sendTo[i] = new InternetAddress(TOS[i]);  
            }
            message.addRecipients(Message.RecipientType.TO,sendTo);
            message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(FROM));//设置在发送给收信人之前给自己(发送方)抄送一份,不然会被当成垃圾邮件,报554错
            message.setSubject(bt);//加载标题
            Multipart multipart = new MimeMultipart();//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
            BodyPart contentPart = new MimeBodyPart();//设置邮件的文本内容
            contentPart.setText(context);
            multipart.addBodyPart(contentPart);
            
            
            if(!fjId.isEmpty()){//添加附件
                String sqlString="select t.file_extend,t.file_info_id,t.file_filename,t.file_url from T_P_FILE_INFO t where t.file_index='"+fjId+"' ";
                List<Map<String, Object>> list=MainTest.dBSelect(sqlString);
                 for(int i=0;i<list.size();i++){
                     BodyPart messageBodyPart = new MimeBodyPart();
                     String AFFIX=System.getProperty("catalina.home")+"/webapps/webdav/"+list.get(i).get("file_info_id")+"."+list.get(i).get("file_extend");
                     String AFFIXNAME=list.get(i).get("file_filename").toString();
                     DataSource source = new FileDataSource(AFFIX);
                     messageBodyPart.setDataHandler(new DataHandler(source));//添加附件的内容
                     sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();//添加附件的标题
                     messageBodyPart.setFileName("=?GBK?B?"+ enc.encode(AFFIXNAME.getBytes()) + "?=");
                     multipart.addBodyPart(messageBodyPart);
                 }
                 
            }
            message.setContent(multipart);//将multipart对象放到message中
            message.saveChanges(); //保存邮件
            Transport transport = session.getTransport("smtp");//发送邮件
            transport.connect(HOST, USER, PWD);//连接服务器的邮箱
            transport.sendMessage(message, message.getAllRecipients());//把邮件发送出去
            transport.close();//关闭连接
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //获取邮件列表
    public void getEmailList(){
        Properties props = new Properties(); //1、连接邮件服务器的参数配置
        
        props.put("mail.store.protocol", "imap"); //设置传输协议
        props.put("mail.imap.host", "imap.163.com"); //设置收件人的POP3服务器
        //props.put("mail.imap.port", "143");
        props.put("mail.imap.auth.plain.disable","true");
        Session session = Session.getDefaultInstance(props); //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Store store;
        try {
            store = session.getStore("imap"); //连接收件人POP3服务器
            store.connect("imap.163.com",USER, PWD);
            Folder folder = store.getFolder("INBOX"); //获得用户的邮件账户,注意通过pop3协议获取某个邮件夹的名称只能为inbox
            folder.open(Folder.READ_WRITE); //设置对邮件账户的访问权限
            //SearchTerm search= new BodyTerm("test");  
            //Message[] messages = folder.search(search);  //得到邮件账户的所有邮件信息
            Message[] messages = folder.getMessages();
            for (int i = 0 ; i < messages.length; i++){
                Message msg = messages[i];
                                
                InternetAddress address =  (InternetAddress) msg.getFrom()[0];
                System.out.println(" [ #" + i + " ] ");
                System.out.println( "Subject : " + msg.getSubject()); // 回复的标题
                    //Subject : 回复:Your registration is complete!
                System.out.println("From : " + address.getPersonal() + "<" + address.getAddress() + ">"); // 回复人的名称和邮箱
                    //From : " Follow your heart "<935220462@qq.com>
                System.out.println("ContentType : " + msg.getContentType());  //内容类型
                    //ContentType : multipart/alternative; 
                    //    boundary="----=_NextPart_5CA330D9_0A968A68_5C0E2915"
                //Message表示一个邮件,msg.getContent()返回一个Multipart对象。一个Multipart对象包含一个或多个BodyPart对象,来组成邮件的正文部分(包括附件)。
                System.out.println("Content Detail : " + msg.getContent().toString()); // 内容细节
                    //Content Detail : javax.mail.internet.MimeMultipart@12bc6874
                System.out.println("时间 : " + msg.getSentDate()); // 日期和时间 
                
                if(msg.isMimeType("multipart/*")){ 
                    Multipart mp = (Multipart)msg.getContent();
                    int bodynum = mp.getCount();
                    for(int j=0; j<bodynum; j++){
                        if(mp.getBodyPart(j).isMimeType("text/html")){
                            String content = (String)mp.getBodyPart(j).getContent();
                            System.out.print("邮件内容:"+content);
                        }
                    }
                }else{  
                    System.out.println("不支持的邮件类型!");  
                }  
            }
            folder.close(false);
            store.close();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
    
    /**
     * 解析综合数据
     * @param part
     * @throws Exception
     */
    private static void getAllMultipart(Part part) throws Exception{
     String contentType = part.getContentType();
     int index = contentType.indexOf("name");
     boolean conName = false;
     if(index!=-1){
      conName=true;
     }
     //判断part类型
     if(part.isMimeType("text/plain") && ! conName) {
      System.out.println((String) part.getContent());
     }else if (part.isMimeType("text/html") && ! conName) {
      System.out.println((String) part.getContent());
     }else if (part.isMimeType("multipart/*")) {
      Multipart multipart = (Multipart) part.getContent();
      int counts = multipart.getCount();
      for (int i = 0; i < counts; i++) {
       //递归获取数据
       getAllMultipart(multipart.getBodyPart(i));
       //附件可能是截图或上传的(图片或其他数据)
       if (multipart.getBodyPart(i).getDisposition() != null) {
        //附件为截图
        if (multipart.getBodyPart(i).isMimeType("image/*")) {
         InputStream is = multipart.getBodyPart(i)
           .getInputStream();
         String name = multipart.getBodyPart(i).getFileName();
         String fileName;
         //截图图片
         if(name.startsWith("=?")){
          fileName = name.substring(name.lastIndexOf(".") - 1,name.lastIndexOf("?="));
         }else{
          //上传图片
          fileName = name;
         }
        
         FileOutputStream fos = new FileOutputStream("D:\\"
           + fileName);
         int len = 0;
         byte[] bys = new byte[1024];
         while ((len = is.read(bys)) != -1) {
          fos.write(bys,0,len);
         }
         fos.close();
        } else {
         //其他附件
         InputStream is = multipart.getBodyPart(i)
           .getInputStream();
         String name = multipart.getBodyPart(i).getFileName();
         FileOutputStream fos = new FileOutputStream("D:\\"
           + name);
         int len = 0;
         byte[] bys = new byte[1024];
         while ((len = is.read(bys)) != -1) {
          fos.write(bys,0,len);
         }
         fos.close();
        }
       }
      }
     }else if (part.isMimeType("message/rfc822")) {
      getAllMultipart((Part) part.getContent());
     } 
    }
    
    /**
     * 解析附件内容
     * @param part
     * @throws Exception
     */
    private static void getAttachmentMultipart(Part part) throws Exception{
     if(part.isMimeType("multipart/*")){
      Multipart multipart = (Multipart) part.getContent();
      int count = multipart.getCount();
      for (int i = 0; i < count; i++) {
       BodyPart bodyPart = multipart.getBodyPart(i);
       if(bodyPart.getDisposition()!=null){
        InputStream is = bodyPart.getInputStream();
        FileOutputStream fos=new FileOutputStream("路径+文件名");
        int len=0;
        byte[] bys=new byte[1024];
        while((len=is.read(bys))!=-1){
         fos.write(bys, 0, len);
        }
        fos.close();
       }
      }
     }
     
    }
    /**
     * 解析图片内容
     * @param part
     * @throws Exception
     */
    private static void getPicMultipart(Part part) throws Exception{
     if(part.isMimeType("multipart/*")){
      Multipart multipart = (Multipart) part.getContent();
      int count = multipart.getCount();
      for (int i = 0; i < count; i++) {
       BodyPart bodyPart = multipart.getBodyPart(i);
       if(bodyPart.isMimeType("image/*")){
        InputStream is = bodyPart.getInputStream();
        FileOutputStream fos=new FileOutputStream("路径+文件名");
        int len=0;
        byte[] bys=new byte[1024];
        while((len=is.read(bys))!=-1){
         fos.write(bys, 0, len);
        }
        fos.close();
       }
      }
     }
    }
    /**
     * 解析文本内容
     * @param part
     * @throws Exception
     */
    private static void getTextMultipart(Part part) throws Exception{
     if(part.isMimeType("text/html")){
      String content = (String) part.getContent();
      System.out.println(content);
     }else if(part.isMimeType("text/plain")){
      String content = (String) part.getContent();
      System.out.println(content);
     }

    }

}

 

posted @ 2019-04-03 14:17  SilentKiller  阅读(1710)  评论(0编辑  收藏  举报