• Javamail使用代码整理


    package com.hengrun.mail;
    
    import java.io.*;
    import java.security.Security;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Properties;
    
    import javax.mail.*;
    import javax.mail.internet.*;
    
    import sun.misc.BASE64Decoder;
    
    public class MailReceive {
        
        public MailReceive(){
            
        }
        
        private Folder inbox = null;
        
        private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
        
        //获取所有邮件
        public String getMails(int page,String username,String pass){
            int pageNum = 10;
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Properties props = System.getProperties();
            props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.imap.socketFactory.fallback", "false");
            props.setProperty("mail.store.protocol", "imap"); 
            props.setProperty("mail.imap.host", "imap.exmail.qq.com"); 
            props.setProperty("mail.imap.port", "993");
            props.setProperty("mail.imap.socketFactory.port", "993");
            
            Session session = Session.getDefaultInstance(props,null);
            
            URLName urln = new URLName("imap","imap.exmail.qq.com",993,null,
                    username, pass);
            
            Store store = null;
            String msg = "";
            
            try {
                store = session.getStore(urln);
                store.connect();
                inbox = store.getFolder("INBOX");
                inbox.open(Folder.READ_ONLY);
                FetchProfile profile = new FetchProfile();
                profile.add(FetchProfile.Item.ENVELOPE);
                Message[] messages = inbox.getMessages();
                inbox.fetch(messages, profile);
                
                //计算页数
                int all = inbox.getMessageCount();
                int pages = all/pageNum;
                if(all%pageNum>0){
                    pages++;
                }
                int begin = all-((page-1)*pageNum);
                
                
                
                for (int i = begin-1; i > (begin-pageNum)&&i>=0; i--) {
                    //邮件发送者
                    String from = decodeText(messages[i].getFrom()[0].toString());
                    msg += messages[i].getMessageNumber()+"&";
                    InternetAddress ia = new InternetAddress(from);
                    msg+=ia.getPersonal()+"&";
                    msg+=ia.getAddress()+"&";
                    //邮件标题
                    msg+=messages[i].getSubject()+"&";
                    //邮件大小
                    msg+=messages[i].getSize()+"&";
                    //邮件发送时间
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    msg+=format.format(messages[i].getSentDate())+";";
                    
                    //判断是否由附件
    //                if(messages[i].isMimeType("multipart/*")){
    //                    Multipart multipart = (Multipart)messages[i].getContent();
    //                    int bodyCounts = multipart.getCount();
    //                    for(int j = 0; j < bodyCounts; j++) {
    //                        BodyPart bodypart = multipart.getBodyPart(j);
    //                        if(bodypart.getFileName() != null){
    //                            String filename = bodypart.getFileName(); 
    //                            if(filename.startsWith("=?")){
    //                                filename = MimeUtility.decodeText(filename);
    //                            }
    //                            msg+=filename+"<br/>";
    //                        }
    //                    }
    //                }
                }
            } catch (MessagingException | IOException e) {
                // TODO Auto-generated catch block
                msg = "0";
            } finally{
                try {
                    inbox.close(false);
                    store.close();
                } catch (MessagingException e) {
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }finally{
                    return msg;
                }
            }
        }
        
        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;
        }
        
        
        //附件下载到服务器
        public void getAtth(int msgnum,int bodynum,String filename,String mailpath) throws MessagingException, IOException{
            Message message = inbox.getMessage(msgnum);
            Multipart multipart = (Multipart)message.getContent(); 
            BodyPart bodypart = multipart.getBodyPart(bodynum); 
            InputStream input = bodypart.getInputStream();
            byte[] buffer = new byte[input.available()];
            input.read(buffer);
            input.close();
            
            File file = new File("D:\App\MailFile\"+mailpath);
            if(!file.isDirectory()&&!file.exists()){
                file.mkdir();
            }
            
            FileOutputStream fos = new FileOutputStream(filename);
            fos.write(buffer);
            fos.close();
        }
        
        //获得单个邮件信息
        public String getMail(int id,final String username,final String pass) throws MessagingException, IOException{
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Properties props = System.getProperties();
            props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.imap.socketFactory.fallback", "false");
            props.setProperty("mail.store.protocol", "imap"); 
            props.setProperty("mail.imap.host", "imap.exmail.qq.com"); 
            props.setProperty("mail.imap.port", "993");
            props.setProperty("mail.imap.socketFactory.port", "993");
            
            Session session = Session.getDefaultInstance(props,null);
            
            URLName urln = new URLName("imap","imap.exmail.qq.com",993,null,
                    username, pass);
            
            Store store = session.getStore(urln);
            store.connect();
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            FetchProfile profile = new FetchProfile();
            profile.add(FetchProfile.Item.ENVELOPE);
            
            Message message = inbox.getMessage(id);
            
            String msg = "";
            
            msg+=message.getMessageNumber()+"&#@";
            msg+=message.getSubject()+"&#@";
            msg+=new InternetAddress(message.getFrom()[0].toString()).getAddress()+"&#@";
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            msg+=format.format(message.getSentDate())+"&#@";
            
            //判断是否由附件
            if(message.isMimeType("multipart/*")){
                Multipart multipart = (Multipart)message.getContent();
                int bodyCounts = multipart.getCount();
                for(int j = 0; j < bodyCounts; j++) {
                    BodyPart bodypart = multipart.getBodyPart(j);
                    if(bodypart.getContent()!=null){
                        msg+=bodypart.getContent()+"&#@";
                    }
                }
            }else{
                msg+=message.getContent().toString()+"&#@";
            }
            
            if(message.isMimeType("multipart/*")){
                Multipart multipart = (Multipart)message.getContent();
                int bodyCounts = multipart.getCount();
                for(int j = 0; j < bodyCounts; j++) {
                    BodyPart bodypart = multipart.getBodyPart(j);
                    if(bodypart.getFileName() != null){
                        String filename = bodypart.getFileName(); 
                        if(filename.startsWith("=?")){
                            filename = MimeUtility.decodeText(filename);
                        }
                        msg+=filename+";";
                    }
                }
            }
            
            store.close();
            return msg;
        }
        
        //发送邮件
        public String sendmail(final String username,final String pass,String from,String to,String subject,String content){
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Properties props = System.getProperties();
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.store.protocol", "smtp"); 
            props.setProperty("mail.smtp.host", "smtp.exmail.qq.com"); 
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.auth", "true");
            Session session = Session.getInstance(props, new Authenticator(){
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, pass);
                }});
            
            Message msg = new MimeMessage(session);
            try {
                msg.setFrom(new InternetAddress(username));
                msg.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(to,false));
                msg.setSubject(subject);
                msg.setText(content);
                msg.setSentDate(new Date());
                Transport.send(msg);
                return "1";
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                return e.getMessage();
            }finally{
                
            }
        }
        
        //Base64
        public static String decryptBASE64(String key) throws Exception {    
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bt = decoder.decodeBuffer(key);
            return new String(bt,"GBK");
        }
        
        //新邮件提醒
        public int MailMsg(String username,String pass){
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Properties props = System.getProperties();
            props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.imap.socketFactory.fallback", "false");
            props.setProperty("mail.store.protocol", "imap"); 
            props.setProperty("mail.imap.host", "imap.exmail.qq.com"); 
            props.setProperty("mail.imap.port", "993");
            props.setProperty("mail.imap.socketFactory.port", "993");
            
            Session session = Session.getDefaultInstance(props,null);
            
            URLName urln = new URLName("imap","imap.exmail.qq.com",993,null,
                    username, pass);
            
            Store store = null;
            int num = 0;
            
            try {
                store = session.getStore(urln);
                store.connect();
                inbox = store.getFolder("INBOX");
                inbox.open(Folder.READ_ONLY);
                FetchProfile profile = new FetchProfile();
                profile.add(FetchProfile.Item.ENVELOPE);
                
                num = inbox.getMessageCount();
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                num = 0;
            }finally{
                try {
                    inbox.close(false);
                    store.close();
                } catch (MessagingException e) {
                    // TODO Auto-generated catch block
                }finally{
                    return num;
                }
            }        
        }
    }
    package com.hengrun.mail;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.mail.MessagingException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class MailMsg
     */
    public class MailMsg extends HttpServlet {
        private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public MailMsg() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            
            request.setCharacterEncoding("gbk");
            
            String username = request.getParameter("username");
            String pass = request.getParameter("pass");
            
            MailReceive mr = new MailReceive();
            
            int num = 0;
            PrintWriter out = null;
            
            num = mr.MailMsg(username, pass);
            
            response.setCharacterEncoding("gbk");
            response.setContentType("text/html; charset=gbk");
            response.setHeader("Pragma", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache");
            
            out = response.getWriter();
    
            out.println(num);
            
            out.flush();
            out.close();
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
            
            //设置request编码方式
            request.setCharacterEncoding("gbk");
            
            String username = request.getParameter("username");
            String pass = request.getParameter("pass");
            
            MailReceive mr = new MailReceive();
            
            int num = 0;
            PrintWriter out = null;
            
            num = mr.MailMsg(username, pass);
            
            response.setCharacterEncoding("gbk");
            response.setContentType("text/html; charset=gbk");
            response.setHeader("Pragma", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-cache");
            
            out = response.getWriter();
    
            out.println(num);
            
            out.flush();
            out.close();
        }
    
    }

    带附件发送邮件

    //发送邮件
        public String sendmail(final String username,final String pass,String from,String to,String subject,String content, String atthid) throws SQLException, ClassNotFoundException, UnsupportedEncodingException{
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Properties props = System.getProperties();
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.store.protocol", "smtp"); 
            props.setProperty("mail.smtp.host", "smtp.exmail.qq.com"); 
            props.setProperty("mail.smtp.port", "465");
            props.setProperty("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.auth", "true");
            Session session = Session.getInstance(props, new Authenticator(){
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, pass);
                }});
            
            Message msg = new MimeMessage(session);
            try {
                msg.setFrom(new InternetAddress(username));
                msg.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(to,false));
                msg.setSubject(subject);
                //msg.setContent(content, "text/html;charset=gb2312");
                msg.setSentDate(new Date());
                
                Multipart mt = new MimeMultipart();
                MimeBodyPart mbp = new MimeBodyPart();
                mbp.setContent(content, "text/html;charset=gb2312");
                mt.addBodyPart(mbp);
                if(atthid!=null&&!atthid.equals("")){
                    List<Map> list = Utility.GetFiles(atthid);
                    
                    if(list!=null&&list.size()>0){
                        for(int i=0;i<list.size();i++){
                            MimeBodyPart fbp = new MimeBodyPart();
                            FileDataSource fds = new FileDataSource(((HashMap)list.get(i)).get("AnnexDirection").toString());
                            fbp.setDataHandler(new DataHandler(fds));
                            fbp.setFileName(MimeUtility.encodeText(((HashMap)list.get(i)).get("AnnexName").toString()));
                            
                            mt.addBodyPart(fbp);
                        }
                    }
                }
                
                msg.setContent(mt);
                
                Transport.send(msg);
                return "1";
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                return e.getMessage();
            }finally{
                
            }
        }

     最新整理收邮件代码,通过UID收取新邮件及附近,已测试成功

    private IMAPFolder inbox = null;
        
        private String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
        
        //获取新邮件
        public String getMails(String username,String pass,String server,String port,Boolean ssl){
            String num = "";
            Properties props = System.getProperties();
            props.setProperty("mail.imap.socketFactory.fallback", "false");
            props.setProperty("mail.store.protocol", "imap"); 
            props.setProperty("mail.imap.host", server); 
            props.setProperty("mail.imap.port", port);
            props.setProperty("mail.imap.socketFactory.port", port);
            props.setProperty("mail.imap.auth.login.disable", "true");
            props.setProperty("mail.imap.auth.plain.disable", "true");
            
            if(ssl){
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
            }
               
            Session session = Session.getDefaultInstance(props,null);
            
            URLName urln = new URLName("imap",server,Integer.parseInt(port),null,
                    username, pass);
            
            Store store = null;
            String ids = "";
            
            try {
                store = session.getStore(urln);
                store.connect();
                inbox = (IMAPFolder)store.getFolder("inbox");
                inbox.open(Folder.READ_WRITE);
                //FetchProfile profile = new FetchProfile();
                //profile.add(FetchProfile.Item.ENVELOPE);
                //Message[] messages = inbox.getMessages();
                //inbox.fetch(messages, profile);
                Message[] msgs = inbox.getMessages();
                for(int i=0;i<msgs.length;i++){
                    ids+="insert into #tmp (UID) values ("+inbox.getUID(msgs[i])+");";
                }
                List<Integer> list = Utility.GetUnreads(username, ids);
                int res = SaveMail(list, username);
                
                if(res<0){
                    num="";
                }else{
                    num = "ok";
                }
                
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                num = "";
            } finally{
                try {
                    inbox.close(false);
                    store.close();
                } catch (MessagingException e) {
                    // TODO Auto-generated catch block
                    //e.printStackTrace();
                }finally{
                    return num;
                }
            }
        }
        
        
        public int SaveMail(List<Integer> list,String username){
            int num = 0;
            try{
                for(int i=0;i<list.size();i++){
                    
                    Message msg = inbox.getMessageByUID(list.get(i));

              Address[] tos = msg.getRecipients(RecipientType.TO);
                    String to = "";
                    for(int j=0;j<tos.length;j++){
                        to+=getAdds(decodeText(tos[j].toString()));
                    }
               Address[] froms
    = msg.getFrom(); String from = ""; for(int j=0;j<froms.length;j++){ from += getAdds(decodeText(froms[j].toString()))+";"; } Address[] ccs = msg.getRecipients(RecipientType.CC); String cc = ""; for(int j=0;ccs!=null&&j<ccs.length;j++){ cc += getAdds(decodeText(ccs[j].toString()))+";"; } Address[] bccs = msg.getRecipients(RecipientType.BCC); String bcc = ""; for(int j=0;bccs!=null&&j<bccs.length;j++){ bcc += getAdds(decodeText(bccs[j].toString()))+";"; } String content = ""; String atth = ""; if(msg.isMimeType("multipart/*")){ Multipart multipart = (Multipart)msg.getContent(); int bodyCounts = multipart.getCount(); for(int j = 0; j < bodyCounts; j++) { BodyPart bodypart = multipart.getBodyPart(j); if(bodypart.getFileName() != null){ String filename = bodypart.getFileName(); if(filename.startsWith("=?")){ filename = MimeUtility.decodeText(filename); } String path = SaveFile(bodypart.getInputStream(), filename); atth+=path+";"; } if(bodypart.isMimeType("text/html")){ content = bodypart.getContent().toString(); } if(bodypart.isMimeType("text/plain")){ content = bodypart.getContent().toString(); } } }else{ content = msg.getContent().toString(); } int iscc = 0; if(cc.contains(username)){ iscc = 1; } int isbcc = 0; if(bcc.contains(username)){ isbcc = 1; } int has = 0; if(!atth.equals("")){ has = 1; }
              int isread = 0;
                    Flag[] flags = msg.getFlags().getSystemFlags();
                    for(int j=0;j<flags.length;j++){
                        if(flags[j] == Flag.SEEN){
                            isread = 1;
                        }
                    }
    Utility.SaveUnread(username, list.get(i), msg.getSentDate(), from, msg.getSubject(), content, cc, bcc, atth,iscc,isbcc,has,to,isread); } num
    =1; }catch(Exception e){ e.printStackTrace(); num=-1; }finally{ return num; } } public String SaveFile(InputStream stream,String filename){ String path = ""; try{ Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String d = sdf.format(date); File file = new File("D:\server\Test\soaTest\files\"+d); if(!file.exists()){ file.mkdirs(); } FileOutputStream out = new FileOutputStream("D:\server\Test\soaTest\files\"+d+"\"+filename); int data; while((data = stream.read()) != -1) { out.write(data); } stream.close(); out.close(); path = "D:\server\Test\soaTest\files\"+d+"\"+filename; }catch(Exception ex){ ex.printStackTrace(); }finally{ return path; } }

     这里要注意,当你先使用一个需要SSL的邮箱接受之后,再使用一个不需要SSL的邮箱接受就会报错,错误提示你无法获取SSL信息。

    这时,你需要这样修改

    Properties props = System.getProperties();
            props.setProperty("mail.imap.socketFactory.fallback", "false");
            props.setProperty("mail.store.protocol", "imap"); 
            props.setProperty("mail.imap.host", server); 
            props.setProperty("mail.imap.port", port);
            
            if(ssl){
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                props.setProperty("mail.imap.socketFactory.class", SSL_FACTORY);
                // 这三句从if外面移进来
                props.setProperty("mail.imap.socketFactory.port", port);         
                props.setProperty("mail.imap.auth.login.disable", "true");
                props.setProperty("mail.imap.auth.plain.disable", "true");
            }

     有的时候会收不到邮件正文,因为有多层的Mult。

    public String takeMult(Object par,int i,String username) throws Exception{
            String content = "";
            Multipart multipart = (Multipart)par;
            int bodyCounts = multipart.getCount();
            for(int j = 0; j < bodyCounts; j++) {
                BodyPart bodypart = multipart.getBodyPart(j);
                if(bodypart.getFileName() != null){
                    String filename = bodypart.getFileName();
                    if(filename.startsWith("=?")){
                        filename = MimeUtility.decodeText(filename);
                    }
                    if(Utility.IsSaved(i,username)==0){
                        String path = SaveFile(bodypart.getInputStream(), filename);
                        //atth+=path+";";
                    }
                }
                if(bodypart.isMimeType("text/html")){
                    content = bodypart.getContent().toString();
                }
                if(bodypart.isMimeType("text/plain")){
                    content = bodypart.getContent().toString();
                }
                if(bodypart.isMimeType("message/rfc822")){
                    content = bodypart.getContent().toString();
                }
                if(bodypart.isMimeType("multipart/*")){
                    content = this.takeMult(bodypart.getContent(), i, username);
                }
            }
            return content; 
        }
    if(bodypart.isMimeType("text/html")){
                                  content = bodypart.getContent().toString();
                              }
                              if(bodypart.isMimeType("text/plain")){
                                  content = bodypart.getContent().toString();
                              }
                              if(bodypart.isMimeType("message/rfc822")){
                                  content = bodypart.getContent().toString();
                              }
                              if(bodypart.isMimeType("multipart/*")){
                                  content = this.takeMult(bodypart.getContent(), i, username);
                              }
  • 相关阅读:
    浅谈树的重心
    倍增的奇妙用处
    KMP——从入门到不会打题
    万能的进制哈希
    浅谈扫描线算法的应用
    无需Flash录视频——HTML5中级进阶
    一个模仿微信群聊的H5页面
    关于建议
    前端技术学习线路
    Kurento安装与入门02——运行示例前的准备
  • 原文地址:https://www.cnblogs.com/wpcnblog/p/3688595.html
Copyright © 2020-2023  润新知