• 2022-10-04
宇哥博客 后端开发 Java使用mail.jar获取已发送邮件,会议UID获取

Java使用mail.jar获取已发送邮件,会议UID获取

通过程序可以发送会议邀请邮件,会议邮件有一个唯一标识UID(发送时自定义字符串),这个UID可以用于修改、取消会议。

bodyPart.isMimeType("text/calendar")

System.out.println("text/calendar类型:" + bodyPart.getContent());
InputStream is = bodyPart.getInputStream();
String info=inputStreamToString(is);
System.out.println("详情:" + info);

会议邮件类型为text/calendar,输出的info中有uid标识。

图 | 输出内容

下面完整代码获取邮箱中已发送记录,邮件由新到旧输出,获取会议邮件UID标识。

package com.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
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.Session;
import javax.mail.Store;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.commons.lang3.StringUtils;


public class TestEmail {

	public static void main(String args[]) {
		
        Properties props = new Properties(); // 参数配置
        props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
        props.setProperty("mail.smtp.host", "smtp.exmail.qq.com"); // 发件人的邮箱的SMTP服务器地址
        props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
        // PS:某些邮箱服务器要求SMTP连接需要使用SSL安全认证(为了提高安全性,邮箱支持SSL连接,也可以自己开启),
        // 如果无法连接邮件服务器,仔细查看控制台打印的 log,如果有有类似"连接失败,要求 SSL安全连接"等错误,
        // 开启 SSL安全连接
        // SMTP服务器的端口(非 SSL连接的端口一般默认为 25,可以不添加,如果开启了SSL连接,
        // 需要改为对应邮箱的SMTP服务器的端口,具体可查看对应邮箱服务的帮助,
        // QQ邮箱的SMTP(SLL)端口为465或587
        final String smtpPort = "465";
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);
        Session session = Session.getDefaultInstance(props);
        session.setDebug(false);
        try {
            Store store = session.getStore("imap");
            store.connect("imap.exmail.qq.com", "XXXXX", "XXXXXX");// change the user and password accordingly
            Folder folder = store.getFolder("inbox");//INBOX
            if (!folder.exists()) {
                System.out.println("inbox not found");
                System.exit(0);
            }
            folder.open(Folder.READ_ONLY);
            Message[] messages = folder.getMessages();
            if (messages == null || messages.length <= 0) {
                System.out.println("this inbox no messages");
                System.exit(0);
            }
            System.out.println("数量:" + messages.length);
            for (int j = messages.length-1; j>=0; j--) {
            	MimeMessage mimeMessage = (MimeMessage) messages[j]; 
            	
            	String subject=mimeMessage.getSubject();
            	System.out.println("标题:" + subject);
            	//解析邮件内容
                Object content = mimeMessage.getContent();
                if (null != content) {
                    if (content instanceof MimeMultipart) {
                        MimeMultipart multipart = (MimeMultipart)content;
                        parseMultipart(multipart);
                    }
                }
            	
                /*
            	//获取所有的Header,头信息
            	Enumeration headers = mimeMessage.getAllHeaders();
            	System.out.println("----------------------allHeaders-----------------------------");
            	while (headers.hasMoreElements()) {
            		Header header = (Header)headers.nextElement();
            		System.out.println(header.getName()+" ======= "+header.getValue());
            	}
            	System.out.println("x2:" + x2);
             	*/
            	
            	Thread.sleep(500);
            }
            
            /*
            for (Message message : messages) {
                String subject = message.getSubject();
                if (StringUtils.isNotBlank(subject)) {
                    System.out.println("subject:" + subject);
                }
                 //* 解析邮件内容
                Object content = message.getContent();
                if (null != content) {
                    if (content instanceof MimeMultipart) {
                        MimeMultipart multipart = (MimeMultipart)content;
                        parseMultipart(multipart);
                    }
                }
            }
        	*/
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 对复杂邮件的解析
     * 
     * @param multipart
     * @throws MessagingException
     * @throws IOException
     */
    public static void parseMultipart(Multipart multipart) throws MessagingException, IOException {
        int count = multipart.getCount();
        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("text/plain类型:" + bodyPart.getContent());
            } else if (bodyPart.isMimeType("text/html")) {
                System.out.println("text/html类型:" + bodyPart.getContent());
            } else if (bodyPart.isMimeType("multipart/*")) {
                Multipart mpart = (Multipart)bodyPart.getContent();
                parseMultipart(mpart);
            } else if(bodyPart.isMimeType("text/calendar")){
            	//会议邀请
            	 System.out.println("text/calendar类型:" + bodyPart.getContent());
            	 InputStream is = bodyPart.getInputStream();
            	 String info=inputStreamToString(is);
            	 System.out.println("详情:" + info);
            } else if (bodyPart.isMimeType("application/octet-stream")) {
                String disposition = bodyPart.getDisposition();
                System.out.println(disposition);
                if (StringUtils.isNotBlank(disposition) && disposition.equalsIgnoreCase(BodyPart.ATTACHMENT)) {
                    String fileName = bodyPart.getFileName();
                    InputStream is = bodyPart.getInputStream();
                   // copy(is, new FileOutputStream("E:\\" + 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();
    }
    
    
    public static String inputStreamToString(InputStream is) throws IOException{
    	StringBuilder sb=new StringBuilder();
    	String line;
    	BufferedReader br=new BufferedReader(new InputStreamReader(is,"utf-8"));
    	while((line=br.readLine())!=null){
    		sb.append(line);
    		sb.append("\n");
    	}
    	return sb.toString();
    }
    
}

以上主要代码来自:http://www.javashuo.com/article/p-acpgcihp-ea.html

相关文章:

Java使用mail.jar发送邮件,异常550 Mailbox not found or access denied

Java使用mail.jar收邮件,邮件顺序从新到旧

Java发送邮件,多个收件人、抄送、图片

ad
本文来自网络,不代表本站立场,转载请注明出处。http://www.ygbks.com/3490.html

发表评论

您的电子邮箱地址不会被公开。

返回顶部