`
yuancihang
  • 浏览: 142610 次
  • 性别: Icon_minigender_1
  • 来自: 洛阳
社区版块
存档分类
最新评论

MIME解码

阅读更多

1.环境

 

JDK6

Java MAIL

 

2. 代码


import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.mail.Header;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.ParseException;

import org.apache.log4j.Logger;

public class MimeDecoder {
   
    private Logger logger =  Logger.getLogger(MimeDecoder.class);
   
    private MimeMessage message;
    private String encoding = "UTF-8"; //MIME正文编码
   
    private String txtContent; //纯文本正文
    private String htmlContent; //超文本正文
    private Map<String, MimeAttachment> attachmentMap = new HashMap<String, MimeAttachment>(); //附件, 内嵌文件
    private Map<String, String> headers = new LinkedHashMap<String, String>();
   
    /**
     * 构造MIME解码器
     * @param text String MIME原始报文
     * @param encoding String MIME正文默认编码, 仅当MIME正文没有指定编码时使用
     * @throws MessagingException
     */
    public MimeDecoder(String text, String encoding)throws MessagingException{
        message = new MimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(text.getBytes()));
        this.encoding = encoding;
    }
    public MimeDecoder(String text)throws MessagingException{
        message = new MimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(text.getBytes()));
    }
    public MimeDecoder(byte[] data, String encoding)throws MessagingException{
        message = new MimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(data));
        this.encoding = encoding;
    }
    public MimeDecoder(byte[] data)throws MessagingException{
        message = new MimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(data));
    }
    public MimeDecoder(InputStream is, String encoding)throws MessagingException{
        message = new MimeMessage(Session.getDefaultInstance(new Properties()), is);
        this.encoding = encoding;
    }
    public MimeDecoder(InputStream is)throws MessagingException{
        message = new MimeMessage(Session.getDefaultInstance(new Properties()), is);
    }
   
    public String getHeader(String name){
        return headers.get(name);
    }
    public Set<String> headNameSet(){
        return headers.keySet();
    }
   
    public String getTxtContent(){
        return txtContent;
    }
    public byte[] getTxtData()throws UnsupportedEncodingException{
        if(txtContent != null){
            return txtContent.getBytes(encoding);
        }
        return null;
    }
    public String getHtmlContent(){
        return htmlContent;
    }
    public byte[] getHtmlData()throws UnsupportedEncodingException{
        if(htmlContent != null){
            return htmlContent.getBytes(encoding);
        }
        return null;
    }
    public Iterator<Map.Entry<String, MimeAttachment>> attachmentIterator(){
        return attachmentMap.entrySet().iterator();
    }
   
    public Collection<MimeAttachment> attachmentCollections(){
        return attachmentMap.values();
    }
   
    private void updateEncoding(String contentType)throws ParseException{
        if(contentType != null){
            ContentType ct = new ContentType(contentType);
            String e = ct.getParameter("charset");
            if(e != null){
                this.encoding = e;
            }
        }
    }
   
    public void decode(){
        try {
            decodeHeaders();
           
            Object messageBody = message.getContent();
            if(message.isMimeType("text/html")){//MIME超文本正文
                updateEncoding(message.getContentType());
                htmlContent = (String)messageBody;
            }else if(message.isMimeType("text/*")){//MIME纯文本正文
                updateEncoding(message.getContentType());
                txtContent = (String)messageBody;
            }else if(message.isMimeType("multipart/*")){ //带附件的MIME处理
                Multipart multipart = (Multipart)messageBody;
                int count = multipart.getCount();
                for (int i=0, n=count; i<n; i++) {
                    MimeBodyPart part = (MimeBodyPart)multipart.getBodyPart(i);
                    decodeBodyPart(part);
                }
            }
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    }
   
    protected void decodeHeaders()throws MessagingException{
        Enumeration<?> headEnumeration = message.getAllHeaders();
        while(headEnumeration.hasMoreElements()){
            Header header = (Header)headEnumeration.nextElement();
            headers.put(header.getName(), header.getValue());
        }
    }
   
    protected void decodeBodyPart(MimeBodyPart part)throws MessagingException, IOException{
        String disposition = part.getDisposition();
        if (disposition != null) {//如果是附件
            MimeAttachment mimeAttachment= new MimeAttachment(part);
            attachmentMap.put(mimeAttachment.getName(), mimeAttachment);
        }else {
            if(part.isMimeType("text/html")){//MIME超文本正文
                updateEncoding(part.getContentType());
                htmlContent = (String)part.getContent();
            }else if(part.isMimeType("text/*")){//MIME纯文本正文
                updateEncoding(part.getContentType());
                txtContent = (String)part.getContent();
            }else if(part.isMimeType("multipart/*")){//嵌套multipart
                Multipart multipart = (Multipart)part.getContent();
                int count = multipart.getCount();
                for (int i=0, n=count; i<n; i++) {
                    MimeBodyPart p = (MimeBodyPart)multipart.getBodyPart(i);
                    decodeBodyPart(p);
                }
            }else{
                logger.info("不支持的MIME正文媒体类型: " + part.getContentType());
            }
           
        }
    }
   
   
}



import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.mail.MessagingException;
import javax.mail.Part;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeUtility;

public class MimeAttachment {
   
    protected byte[] data;
    protected String name;
    protected boolean isInline = false;
    protected ContentType ct;
   
    public MimeAttachment(MimeBodyPart part)throws IOException, MessagingException{
        String disposition = part.getDisposition();
        if (disposition != null) {//如果是附件
            ct = new ContentType(part.getContentType());
            if(disposition.equals(Part.ATTACHMENT)){
                this.name = nameDecode(part.getFileName());
            }else if(disposition.equals(Part.INLINE)){
                this.name = nameDecode(part.getContentID());
                this.isInline = true;
            }
            parse(part);
        }
    }
   
    protected void parse(MimeBodyPart part)throws IOException, MessagingException{
        InputStream is = part.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int data = -1;
        while((data = is.read()) != -1){
            baos.write(data);
        }
        this.data = baos.toByteArray();
    }
   
    protected String nameDecode(String s)throws UnsupportedEncodingException{
        return MimeUtility.decodeText(s);
    }
   
    public byte[] getData(){
        return data;
    }
   
    public String getName(){
        return name;
    }
   
    public File saveTo(String dir)throws IOException{
        if(data != null){
            File f = new File(new File(dir), name);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
            bos.write(data);
            bos.close();
            return f;
        }
       
        return null;
    }
   
    public boolean isInline(){
        return isInline;
    }
   
    public ContentType getContentType(){
        return ct;
    }

}

3. 测试

 

public static void main(String args[])throws Exception{

        MimeDecoder decoder = new MimeDecoder(new FileInputStream("d:/test/开源项目.eml"));
        decoder.decode();
        if(decoder.getTxtContent() != null){
            System.out.println("MIME纯文本正文: " + decoder.getTxtContent());
        }
        if(decoder.getHtmlContent() != null){
            System.out.println("MIME超文本正文: " + decoder.getHtmlContent());
        }
       
        //保存附件
        String dir = "d:/test";
        Collection<MimeAttachment> attachments = decoder.attachmentCollections();
        for(MimeAttachment attachment : attachments){
            attachment.saveTo(dir);
        }
       
    }

分享到:
评论

相关推荐

    MIME编解码器

    原创作品, VC6.0,MFC开发. 支持常用的MIME编解码, 如base64, quoted-printable, UUENCODE, UTF-7, UTF-8, 简繁转换, MD5计算等.

    The mimedecode library:C ++ MIME解码库-开源

    一个仅提供MIME解码功能的C ++库。 该库专门提供动态(动态)解码功能。 这将使其适合使用MIME封装实时流的应用程序。

    PHP教程之用PHP实现POP3邮件的收取[二]

    分为邮件收取、MIME解码两个部分。这里我们先向您介绍邮件的收取,解码部分会在以后的文章中为各位详细的介绍,敬请关注。  现在Internet上最大的应用应该是非Email莫属了,我们每天都习惯于每天通过Email进行...

    PHP教程之用PHP实现POP3邮件的收取[一]

    分为邮件收取、MIME解码两个部分。这里我们先向您介绍邮件的收取,解码部分会在以后的文章中为各位详细的介绍,敬请关注。  现在Internet上最大的应用应该是非Email莫属了,我们每天都习惯于每天通过Email进行...

    enmime:Go的MIME邮件编码和解码包

    enmime是Go的MIME编码和解码库,专注于生成和解析MIME编码的电子邮件。 它与电子邮件服务一起开发。 enmime包括一个流畅的界面生成器,用于生成MIME编码的消息,请参阅Wiki中的示例。 有关示例和API使用信息,请...

    C#实现邮件内容 MIME信息的编码/解码

    C# 类库来实现MIME的编码和解码 MimeMessage mail new MimeMessage ; mail SetDate ; mail Setversion ; mail SetFrom &quot;sender@local com&quot; null ; mail SetTo &quot;recipient1@server1 com Nick Name...

    MIME Quoted Printable &amp; Base64 编码解码程序

    MIME Quoted Printable &amp; Base64 编码解码程序

    PHP_POP3操作类

    老外用PHP写的POP3类,内含mime解码,还有实例,非常不错的类,跟大家一起分享

    pop3收取邮件的类库,支持附件和MIME

    pop3收取邮件的类库,支持附件和MIME.需要做发邮件功能的朋友,可以看看,不要积分的。

    mime协议(详细)

    邮件阅读程序在读取到这种经过编码处理的邮件后,再按照相应的解码方式解码出原始的二进制数据,这样就可以借助RFC822邮件格式来传递多媒体数据了。这种做法需要解决以下两个技术问题: (1) 邮件阅读程序如何知道...

    电子邮件MIME协议中的Base64编解码

    电子邮件MIME协议中的Base64编解码 整份实验报告 有截图和代码

    各种形式的编码解码工具

    收集整理了各种通过JAVASCRIPT编码解码工具 支持转换的有 \uXXXX \UXXXXXXXX &#DDDD; &#xXXXX; \xXX \OOO Base64 Quoted-printable MIME + Base64 MIME + Quoted-printable 如输入:测试CSDN 结果为: 测试CSDN \...

    MIME

    能够快速 MIME ( Base64 ) 编码及解码的单元

    MIME协议(中文版).doc

    邮件阅读程序在读取到这种经过编码处理的邮件后,再按照相应的解码方式解码出原始的二进制数据,这样就可以借助RFC822邮件格式来传递多媒体数据了。这种做法需要解决以下两个技术问题: (1) 邮件阅读程序如何知道...

    codec-string:解码媒体mime类型中的codec =字符串

    解码媒体mime类型中的codec =字符串 支持 HEVC(hvc1,hev1) AVC(AVC1) AAC(mp4a) AV1(av01) E-AC3(ec-3)-无需处理 VP9-请参阅 EVC-请参阅ISO / IEC 14496-15:2019 Amd.2的附件E.9 VVC-请参阅ISO / ...

    Base64 编码 解码器 V1.6

     Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,可以参见RFC2045~RFC2049,上面有MIME的详细规范。Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3*8 = 4*6 = 24),然后把6Bit再添两位高位0...

    smtp mime格式发送邮件可发附件

    //base64解码 string Base64Decode(LPCTSTR lpszSrc); //读文件数据 bool ReadFromFile(const char* pszFilename,string &filename); unsigned char* m_pbText; int main() { //1.首先需要连接邮件服务器 这里用...

    乱码查看器乱码察看器顾名思义就是用来察看各种乱码的工具软件,目前支持MIME/BASE64

    乱码察看器顾名思义就是用来察看各种乱码的工具软件,目前支持MIME/BASE64, Quoted-Printable,HZ和UUCode四种形式的编码和解码,通过一些特殊的算法, 本程序还可以解开部分由于字节高位被屏蔽而形成的死乱码...

    Base64编码解码、无乱码。本人亲自测试使用。.

    本人亲自测试了这个软件,在转换的时候注意...Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。Base64编码可用于在HTTP环境下传递较长的标识信息。

Global site tag (gtag.js) - Google Analytics