点击下载 MimeReader.rar

这个类是关于MimeReader的帮助类
看下面代码吧

/// <summary>
/// 类说明:Assistant
/// 编 码 人:苏飞
/// 联系方式:361983679
/// 更新网站:[url=http://www.cckan.net/thread-655-1-1.html]http://www.cckan.net/thread-655-1-1.html[/url]
/// </summary>
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Mime; namespace DotNet.Utilities
{
/// <summary>
/// This class is responsible for parsing a string array of lines
/// containing a MIME message.
/// </summary>
public class MimeReader
{
private static readonly char[] HeaderWhitespaceChars = new char[] { ' ', '\t' }; private Queue<string> _lines;
/// <summary>
/// Gets the lines.
/// </summary>
/// <value>The lines.</value>
public Queue<string> Lines
{
get
{
return _lines;
}
} private MimeEntity _entity; /// <summary>
/// Initializes a new instance of the <see cref="MimeReader"/> class.
/// </summary>
private MimeReader()
{
_entity = new MimeEntity();
} /// <summary>
/// Initializes a new instance of the <see cref="MimeReader"/> class.
/// </summary>
/// <param name="entity">The entity.</param>
/// <param name="lines">The lines.</param>
private MimeReader(MimeEntity entity, Queue<string> lines)
: this()
{
if (entity == null)
{
throw new ArgumentNullException("entity");
} if (lines == null)
{
throw new ArgumentNullException("lines");
} _lines = lines;
_entity = new MimeEntity(entity);
} /// <summary>
/// Initializes a new instance of the <see cref="MimeReader"/> class.
/// </summary>
/// <param name="lines">The lines.</param>
public MimeReader(string[] lines)
: this()
{
if (lines == null)
{
throw new ArgumentNullException("lines");
} _lines = new Queue<string>(lines);
} /// <summary>
/// Parse headers into _entity.Headers NameValueCollection.
/// </summary>
private int ParseHeaders()
{
string lastHeader = string.Empty;
string line = string.Empty;
// the first empty line is the end of the headers.
while (_lines.Count > && !string.IsNullOrEmpty(_lines.Peek()))
{
line = _lines.Dequeue(); //if a header line starts with a space or tab then it is a continuation of the
//previous line.
if (line.StartsWith(" ") || line.StartsWith(Convert.ToString('\t')))
{
_entity.Headers[lastHeader] = string.Concat(_entity.Headers[lastHeader], line);
continue;
} int separatorIndex = line.IndexOf(':'); if (separatorIndex < )
{
System.Diagnostics.Debug.WriteLine("Invalid header:{0}", line);
continue;
} //This is an invalid header field. Ignore this line. string headerName = line.Substring(, separatorIndex);
string headerValue = line.Substring(separatorIndex + ).Trim(HeaderWhitespaceChars); _entity.Headers.Add(headerName.ToLower(), headerValue);
lastHeader = headerName;
} if (_lines.Count > )
{
_lines.Dequeue();
} //remove closing header CRLF. return _entity.Headers.Count;
} /// <summary>
/// Processes mime specific headers.
/// </summary>
/// <returns>A mime entity with mime specific headers parsed.</returns>
private void ProcessHeaders()
{
foreach (string key in _entity.Headers.AllKeys)
{
switch (key)
{
case "content-description":
_entity.ContentDescription = _entity.Headers[key];
break;
case "content-disposition":
_entity.ContentDisposition = new ContentDisposition(_entity.Headers[key]);
break;
case "content-id":
_entity.ContentId = _entity.Headers[key];
break;
case "content-transfer-encoding":
_entity.TransferEncoding = _entity.Headers[key];
_entity.ContentTransferEncoding = MimeReader.GetTransferEncoding(_entity.Headers[key]);
break;
case "content-type":
_entity.SetContentType(MimeReader.GetContentType(_entity.Headers[key]));
break;
case "mime-version":
_entity.MimeVersion = _entity.Headers[key];
break;
}
}
} /// <summary>
/// Creates the MIME entity.
/// </summary>
/// <returns>A mime entity containing 0 or more children representing the mime message.</returns>
public MimeEntity CreateMimeEntity()
{
try
{
ParseHeaders(); ProcessHeaders(); ParseBody(); SetDecodedContentStream(); return _entity;
}
catch
{
return null; }
} /// <summary>
/// Sets the decoded content stream by decoding the EncodedMessage
/// and writing it to the entity content stream.
/// </summary>
/// <param name="entity">The entity containing the encoded message.</param>
private void SetDecodedContentStream()
{
switch (_entity.ContentTransferEncoding)
{
case System.Net.Mime.TransferEncoding.Base64:
_entity.Content = new MemoryStream(Convert.FromBase64String(_entity.EncodedMessage.ToString()), false);
break; case System.Net.Mime.TransferEncoding.QuotedPrintable:
_entity.Content = new MemoryStream(GetBytes(QuotedPrintableEncoding.Decode(_entity.EncodedMessage.ToString())), false);
break; case System.Net.Mime.TransferEncoding.SevenBit:
default:
_entity.Content = new MemoryStream(GetBytes(_entity.EncodedMessage.ToString()), false);
break;
}
} /// <summary>
/// Gets a byte[] of content for the provided string.
/// </summary>
/// <param name="decodedContent">Content.</param>
/// <returns>A byte[] containing content.</returns>
private byte[] GetBytes(string content)
{
using (MemoryStream stream = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(content);
}
return stream.ToArray();
}
} /// <summary>
/// Parses the body.
/// </summary>
private void ParseBody()
{
if (_entity.HasBoundary)
{
while (_lines.Count >
&& !string.Equals(_lines.Peek(), _entity.EndBoundary))
{
/*Check to verify the current line is not the same as the parent starting boundary.
If it is the same as the parent starting boundary this indicates existence of a
new child entity. Return and process the next child.*/
if (_entity.Parent != null
&& string.Equals(_entity.Parent.StartBoundary, _lines.Peek()))
{
return;
} if (string.Equals(_lines.Peek(), _entity.StartBoundary))
{
AddChildEntity(_entity, _lines);
} //Parse a new child mime part.
else if (string.Equals(_entity.ContentType.MediaType, MediaTypes.MessageRfc822, StringComparison.InvariantCultureIgnoreCase)
&& string.Equals(_entity.ContentDisposition.DispositionType, DispositionTypeNames.Attachment, StringComparison.InvariantCultureIgnoreCase))
{
/*If the content type is message/rfc822 the stop condition to parse headers has already been encountered.
But, a content type of message/rfc822 would have the message headers immediately following the mime
headers so we need to parse the headers for the attached message now. This is done by creating
a new child entity.*/
AddChildEntity(_entity, _lines); break;
}
else
{
_entity.EncodedMessage.Append(string.Concat(_lines.Dequeue(), Pop3Commands.Crlf));
} //Append the message content.
}
} //Parse a multipart message.
else
{
while (_lines.Count > )
{
_entity.EncodedMessage.Append(string.Concat(_lines.Dequeue(), Pop3Commands.Crlf));
}
} //Parse a single part message.
} /// <summary>
/// Adds the child entity.
/// </summary>
/// <param name="entity">The entity.</param>
private void AddChildEntity(MimeEntity entity, Queue<string> lines)
{
/*if (entity == null)
{
return;
} if (lines == null)
{
return;
}*/ MimeReader reader = new MimeReader(entity, lines);
entity.Children.Add(reader.CreateMimeEntity());
} /// <summary>
/// Gets the type of the content.
/// </summary>
/// <param name="contentType">Type of the content.</param>
/// <returns></returns>
public static ContentType GetContentType(string contentType)
{
if (string.IsNullOrEmpty(contentType))
{
contentType = "text/plain; charset=us-ascii";
}
return new ContentType(contentType); } /// <summary>
/// Gets the type of the media.
/// </summary>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
public static string GetMediaType(string mediaType)
{
if (string.IsNullOrEmpty(mediaType))
{
return "text/plain";
}
return mediaType.Trim();
} /// <summary>
/// Gets the type of the media main.
/// </summary>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
public static string GetMediaMainType(string mediaType)
{
int separatorIndex = mediaType.IndexOf('/');
if (separatorIndex < )
{
return mediaType;
}
else
{
return mediaType.Substring(, separatorIndex);
}
} /// <summary>
/// Gets the type of the media sub.
/// </summary>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
public static string GetMediaSubType(string mediaType)
{
int separatorIndex = mediaType.IndexOf('/');
if (separatorIndex < )
{
if (mediaType.Equals("text"))
{
return "plain";
}
return string.Empty;
}
else
{
if (mediaType.Length > separatorIndex)
{
return mediaType.Substring(separatorIndex + );
}
else
{
string mainType = GetMediaMainType(mediaType);
if (mainType.Equals("text"))
{
return "plain";
}
return string.Empty;
}
}
} /// <summary>
/// Gets the transfer encoding.
/// </summary>
/// <param name="transferEncoding">The transfer encoding.</param>
/// <returns></returns>
/// <remarks>
/// The transfer encoding determination follows the same rules as
/// Peter Huber's article w/ the exception of not throwing exceptions
/// when binary is provided as a transferEncoding. Instead it is left
/// to the calling code to check for binary.
/// </remarks>
public static TransferEncoding GetTransferEncoding(string transferEncoding)
{
switch (transferEncoding.Trim().ToLowerInvariant())
{
case "7bit":
case "8bit":
return System.Net.Mime.TransferEncoding.SevenBit;
case "quoted-printable":
return System.Net.Mime.TransferEncoding.QuotedPrintable;
case "base64":
return System.Net.Mime.TransferEncoding.Base64;
case "binary":
default:
return System.Net.Mime.TransferEncoding.Unknown; }
}
}
}

[Mime] MimeReader--读取Mime的帮助类 (转载)的更多相关文章

  1. MIME协议(四) -- MIME消息的头字段

    MIME消息的头字段 4.1  Content-Type 对于表示某个具体资源的MIME消息,它的消息头中需要指定资源的数据类型:对于MIME组合消息,它的消息头中需要指定组合关系.具体资源的数据类型 ...

  2. 读取Config文件工具类 PropertiesConfig.java

    package com.util; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io ...

  3. 利用java反射机制 读取配置文件 实现动态类载入以及动态类型转换

    作者:54dabang 在spring的学习过程之中,我们能够看出通过配置文件来动态管理bean对象的优点(松耦合 能够让零散部分组成一个总体,而这些总体并不在意之间彼此的细节,从而达到了真正的物理上 ...

  4. EpPlus读取生成Excel帮助类+读取csv帮助类+Aspose.Cells生成Excel帮助类

    大部分功能逻辑都在,少量自定义异常类和扩展方法 ,可用类似代码自己替换 //EpPlus读取生成Excel帮助类+读取csv帮助类,epplus只支持开放的Excel文件格式:xlsx,不支持 xls ...

  5. golang:mime.Encode、mime.Decode

    最近在做邮件解析的工作,所以记录一下对mime.Encode.mime.Decode的总结.

  6. golang:mime.Decode、mime.DecodeHeader

    最近在做邮件解析的相关工作,在使用mime.Decode/mime.DecodeHeader时有些疑问. 有些搞不懂mime.Encode和mime.EncodeHeader的区别.

  7. Java读取properties配置文件工具类

    1.   PropertyUtils.java package javax.utils; import java.io.InputStream; import java.util.Properties ...

  8. MIME类型释义--MIME类型大全--web.xml中有关<mime-mapping>配置说明

    最早的HTTP协议中,并没有附加的数据类型信息,所有传送的数据都被客户程序解释为超文本标记语言HTML 文档,而为了支持多媒体数据类型,HTTP协议中就使用了附加在文档之前的MIME数据类型信息来标识 ...

  9. 读取XML直接转换为类对象

    <?xml version="1.0" encoding="utf-8"?> <ArrayOfMenuItems xmlns:xsi=&quo ...

随机推荐

  1. Minimum Cost(最小费用最大流)

    Description Dearboy, a goods victualer, now comes to a big problem, and he needs your help. In his s ...

  2. CentOS 7下载地址(ISO文件)

    CentOS安装文件有两类(32位和64位),每类下载对应有不同的版本,这些版本适合不同需求的用户.CentOS 7官方下载地址:https://www.centos.org/download/在Ce ...

  3. Ubuntu 使用apt-get时提示错误:无法获得锁 /var/lib/dpkg/lock

    推荐博客:http://blog.sina.com.cn/s/blog_5c1450a8010188ju.html Ubuntu 使用apt-get时提示错误:无法获得锁 /var/lib/dpkg/ ...

  4. selenium webdriver 环境搭建--java

    selenium java环境的安装可以分为三个部分:jdk.eclipse和selenium. jdk jdk(java development kit)是sun公司针对java开发人员的产品,是整 ...

  5. Codevs 3286 火柴排队 2013年NOIP全国联赛提高组 树状数组,逆序对

    题目:http://codevs.cn/problem/3286/ 3286 火柴排队  2013年NOIP全国联赛提高组  时间限制: 1 s   空间限制: 128000 KB   题目等级 : ...

  6. Bzoj 1878: [SDOI2009]HH的项链 莫队

    1878: [SDOI2009]HH的项链 Time Limit: 4 Sec  Memory Limit: 64 MBSubmit: 2717  Solved: 1363[Submit][Statu ...

  7. eclipse安装Hadoop1.1.2版本开发插件

    Hadoop1.1.2版本没有直接适合Eclipse的安装插件,需要手动打包jar文件. 我的系统配置: VMware Workstation10 CentOS-6.5-i386 hadoop-1.1 ...

  8. Apache 虚拟主机 VirtualHost 配置

    虚拟主机 (Virtual Host) 是在同一台机器搭建属于不同域名或者基于不同 IP 的多个网站服务的技术. 可以为运行在同一物理机器上的各个网站指配不同的 IP 和端口, 也可让多个网站拥有不同 ...

  9. MFC中树控件CTreeCtrl的用法

    树形控件可以用于树形的结构,其中有一个根接点(Root)然后下面有许多子结点,而每个子结点上有允许有一个或多个或没有子结点.MFC中使用CTreeCtrl类来封装树形控件的各种操作.通过调用 BOOL ...

  10. AndroidHttp通信 HTTP Client与HttpURLConnection的区别

    Apache HTTP Client DefaultHttpClient 以及其相关类AndroidHttpClient 适用于 web browsers, 他们是可扩展的,并且拥有大量的稳定APIs ...