呼之欲出 WebMail 开发手记 (五) 邮件操作类
这两天身体不是很舒服,来晚了,在此向大家谢罪。
本来准备就讲邮件收发了,突然发现好像一些基本的东西都还没有说呢。贴代码:
邮件操作类:MailHelper
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.IO;
/**//***************************************
******** 里奥特在线邮件收发系统 *****
***************************************/
namespace Lyout.WebMail {
/**//// <summary>
/// 功能:基本处理
/// 编写:夏荣全
/// 日期:2009-07-03
/// </summary>
public sealed class MailHelper {
public static readonly string POP3Name = "__POP3MAIL__";
public static readonly string SMTPName = "__SMTPMAIL__";
public static string MakeFileName() {
return DateTime.Now.ToString("yyyyMMddHHmmss");
}
DeleteFile#region DeleteFile
/**//// <summary>
/// 删除文件
/// </summary>
/// <param name="filePath">文件全路径</param>
public static bool DeleteFile(string filePath) {
try {
if (File.Exists(filePath)) {
File.Delete(filePath);
}
return true;
}
catch {
return false;
}
}
#endregion
ParseDate#region ParseDate
/**//// <summary>
/// 获取邮件时间
/// </summary>
/// <param name="headers"></param>
public static DateTime ParseDate(string date) {
try {
if (date.Length > 0) {
return ParseDateS(date);
}
else {
return DateTime.Now;
}
}
catch {
return DateTime.Now;
}
}
/**//// <summary>
/// Parses rfc2822 datetime.
/// </summary>
/// <param name="date">Date string</param>
/// <returns></returns>
public static DateTime ParseDateS(string date) {
/**//*
GMT -0000
EDT -0400
EST -0500
CDT -0500
CST -0600
MDT -0600
MST -0700
PDT -0700
PST -0800
*/
if (!string.IsNullOrEmpty(date)) {
if (date.IndexOf("(") != -1) {
date = date.Substring(0, date.IndexOf("(") - 1);
}
date = date.Replace("GMT", "-0000");
date = date.Replace("EDT", "-0400");
date = date.Replace("EST", "-0500");
date = date.Replace("CDT", "-0500");
date = date.Replace("CST", "-0600");
date = date.Replace("MDT", "-0600");
date = date.Replace("MST", "-0700");
date = date.Replace("PDT", "-0700");
date = date.Replace("PST", "-0800");
string[] formats = new string[]{
"f","F","g","G","r",
"d MMM yyyy HH':'mm':'ss",
"dd MMM yyyy HH':'mm':'ss",
"ddd, d MMM yyyy HH':'mm':'ss",
"ddd, dd MMM yyyy HH':'mm':'ss",
"d MMM yyyy HH':'mm':'ss zzz",
"dd MMM yyyy HH':'mm':'ss zzz",
"ddd, d MMM yyyy HH':'mm':'ss zzz",
"ddd, dd MMM yyyy HH':'mm':'ss zzz",
"d'-'MMM'-'yyyy HH':'mm':'ss zzz",
"dd'-'MMM'-'yyyy HH':'mm':'ss zzz"
};
try {
return DateTime.ParseExact(date.Trim(), formats, System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None);
}
catch {
return DateTime.Now;
}
}
else {
return DateTime.Now;
}
}
#endregion
保存日志#region 保存日志
public static void SaveLogs(string filePath, string text) {
try {
using (FileStream fs = new FileStream(filePath + DateTime.Now.ToString("yyyy-MM-dd") + ".log", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) {
byte[] bytes = System.Text.Encoding.Default.GetBytes(DateTime.Now.ToString("HH:mm:ss\t") + text + "\r\n");
fs.Write(bytes, 0, bytes.Length);
}
}
catch {
}
}
#endregion
SetChecked#region SetChecked
public static void SetChecked(string id, GridView grid, int cellIndex) {
SetChecked(true, id, grid, cellIndex);
}
public static void SetChecked(bool Checked, string id, GridView grid, int cellIndex) {
foreach (GridViewRow row in grid.Rows) {
CheckBox checkbox = (CheckBox)row.Cells[cellIndex].FindControl(id);
if (checkbox != null && checkbox.Enabled) {
checkbox.Checked = Checked;
}
}
}
#endregion
GetString#region GetString
public static string GetString(string sQueryValue, string sDefault) {
if (!string.IsNullOrEmpty(sQueryValue) && sQueryValue != "") {
return sQueryValue.Trim();
}
else {
return sDefault;
}
}
#endregion
邮件头解码#region 邮件头解码
public static string DecodeStr(string str) {
if (!string.IsNullOrEmpty(str)) {
string[] sArr = str.Split(new char[] { '?' });
if (sArr.Length == 5) {
System.Text.Encoding enc = System.Text.Encoding.GetEncoding(sArr[1]);
if (sArr[2].ToUpper() == "B") {
return enc.GetString(Convert.FromBase64String(sArr[3]));
}
else if (sArr[2].ToUpper() == "Q") {
return QDecode(enc, sArr[3]);
}
}
return (str != "") ? str : "无主题";
}
else {
return "无主题";
}
}
/**//// <summary>
/// quoted-printable decoder.
/// </summary>
/// <param name="encoding">Input string encoding.</param>
/// <param name="data">String which to encode.</param>
/// <returns></returns>
public static string QDecode(System.Text.Encoding encoding, string data) {
// ASCII
MemoryStream strm = new MemoryStream(System.Text.Encoding.Default.GetBytes(data));
int b = strm.ReadByte();
MemoryStream dStrm = new MemoryStream();
while (b > -1) {
// Hex eg. =E4
if (b == '=') {
byte[] buf = new byte[2];
strm.Read(buf, 0, 2);
// <CRLF> followed by =, it's splitted line
if (!(buf[0] == '\r' && buf[1] == '\n')) {
try {
int val = int.Parse(System.Text.Encoding.Default.GetString(buf), System.Globalization.NumberStyles.HexNumber);
//string encodedChar = encoding.GetString(new byte[] { (byte)val });
//byte[] d = System.Text.Encoding.Unicode.GetBytes(encodedChar);
byte[] d = new byte[] { (byte)val };
dStrm.Write(d, 0, d.Length);
}
catch { // If worng hex value, just skip this chars
}
}
}
else {
string encodedChar = encoding.GetString(new byte[] { (byte)b });
byte[] d = System.Text.Encoding.Default.GetBytes(encodedChar);
dStrm.Write(d, 0, d.Length);
}
b = strm.ReadByte();
}
return encoding.GetString(dStrm.ToArray());
//return System.Text.Encoding.Unicode.GetString(dStrm.ToArray());
}
#endregion
GetAddress#region GetAddress
public static MailAddressCollection GetAddress(string strAddress) {
int len = 0;
return GetAddress(strAddress, ref len);
}
/**//// <summary>
/// 分析邮件地址
/// </summary>
/// <param name="strAddress">邮件地址串如:"姓名" <邮件地址></param>
/// <param name="totalLength">总长度.用于计算邮件大小</param>
/// <returns></returns>
public static MailAddressCollection GetAddress(string strAddress, ref int totalLength) {
MailAddressCollection addr = new MailAddressCollection();
int newl = 0;
if (!string.IsNullOrEmpty(strAddress)) {
string[] addressList = strAddress.Trim().Split(new char[] { ',' });
foreach (string address in addressList) {
int p = address.IndexOf("<");
if (p != -1) {
string displayName = address.Substring(0, p - 1).Trim();
displayName = displayName.Replace("\"", "");
string emailAddress = address.Substring(p + 1).Trim();
emailAddress = emailAddress.Replace(">", "");
try {
addr.Add(new MailAddress(emailAddress, displayName));
}
catch {
}
newl += displayName.Length + emailAddress.Length;
}
else {
try {
addr.Add(new MailAddress(address, address));
}
catch {
}
}
}
}
totalLength = newl;
return addr;
}
#endregion
简单的字符串加密解密#region 简单的字符串加密解密
//加密
public static string Encrypt(string data, string skey) {
if (!string.IsNullOrEmpty(data) && data != "") {
string encodestr = "";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
try {
encodestr = Convert.ToBase64String(bytes);
}
catch {
encodestr = data;
}
return encodestr;
}
else {
return "";
}
}
//解密
public static string Decrypt(string data, string skey) {
if (!string.IsNullOrEmpty(data) && data != "") {
string decodestr = "";
byte[] bytes = Convert.FromBase64String(data);
try {
decodestr = System.Text.Encoding.UTF8.GetString(bytes);
}
catch {
decodestr = data;
}
return decodestr;
}
else {
return "";
}
}
#endregion
}
}
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.IO;
/**//***************************************
******** 里奥特在线邮件收发系统 *****
***************************************/
namespace Lyout.WebMail {
/**//// <summary>
/// 功能:基本处理
/// 编写:夏荣全
/// 日期:2009-07-03
/// </summary>
public sealed class MailHelper {
public static readonly string POP3Name = "__POP3MAIL__";
public static readonly string SMTPName = "__SMTPMAIL__";
public static string MakeFileName() {
return DateTime.Now.ToString("yyyyMMddHHmmss");
}
DeleteFile#region DeleteFile
/**//// <summary>
/// 删除文件
/// </summary>
/// <param name="filePath">文件全路径</param>
public static bool DeleteFile(string filePath) {
try {
if (File.Exists(filePath)) {
File.Delete(filePath);
}
return true;
}
catch {
return false;
}
}
#endregion
ParseDate#region ParseDate
/**//// <summary>
/// 获取邮件时间
/// </summary>
/// <param name="headers"></param>
public static DateTime ParseDate(string date) {
try {
if (date.Length > 0) {
return ParseDateS(date);
}
else {
return DateTime.Now;
}
}
catch {
return DateTime.Now;
}
}
/**//// <summary>
/// Parses rfc2822 datetime.
/// </summary>
/// <param name="date">Date string</param>
/// <returns></returns>
public static DateTime ParseDateS(string date) {
/**//*
GMT -0000
EDT -0400
EST -0500
CDT -0500
CST -0600
MDT -0600
MST -0700
PDT -0700
PST -0800
*/
if (!string.IsNullOrEmpty(date)) {
if (date.IndexOf("(") != -1) {
date = date.Substring(0, date.IndexOf("(") - 1);
}
date = date.Replace("GMT", "-0000");
date = date.Replace("EDT", "-0400");
date = date.Replace("EST", "-0500");
date = date.Replace("CDT", "-0500");
date = date.Replace("CST", "-0600");
date = date.Replace("MDT", "-0600");
date = date.Replace("MST", "-0700");
date = date.Replace("PDT", "-0700");
date = date.Replace("PST", "-0800");
string[] formats = new string[]{
"f","F","g","G","r",
"d MMM yyyy HH':'mm':'ss",
"dd MMM yyyy HH':'mm':'ss",
"ddd, d MMM yyyy HH':'mm':'ss",
"ddd, dd MMM yyyy HH':'mm':'ss",
"d MMM yyyy HH':'mm':'ss zzz",
"dd MMM yyyy HH':'mm':'ss zzz",
"ddd, d MMM yyyy HH':'mm':'ss zzz",
"ddd, dd MMM yyyy HH':'mm':'ss zzz",
"d'-'MMM'-'yyyy HH':'mm':'ss zzz",
"dd'-'MMM'-'yyyy HH':'mm':'ss zzz"
};
try {
return DateTime.ParseExact(date.Trim(), formats, System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None);
}
catch {
return DateTime.Now;
}
}
else {
return DateTime.Now;
}
}
#endregion
保存日志#region 保存日志
public static void SaveLogs(string filePath, string text) {
try {
using (FileStream fs = new FileStream(filePath + DateTime.Now.ToString("yyyy-MM-dd") + ".log", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) {
byte[] bytes = System.Text.Encoding.Default.GetBytes(DateTime.Now.ToString("HH:mm:ss\t") + text + "\r\n");
fs.Write(bytes, 0, bytes.Length);
}
}
catch {
}
}
#endregion
SetChecked#region SetChecked
public static void SetChecked(string id, GridView grid, int cellIndex) {
SetChecked(true, id, grid, cellIndex);
}
public static void SetChecked(bool Checked, string id, GridView grid, int cellIndex) {
foreach (GridViewRow row in grid.Rows) {
CheckBox checkbox = (CheckBox)row.Cells[cellIndex].FindControl(id);
if (checkbox != null && checkbox.Enabled) {
checkbox.Checked = Checked;
}
}
}
#endregion
GetString#region GetString
public static string GetString(string sQueryValue, string sDefault) {
if (!string.IsNullOrEmpty(sQueryValue) && sQueryValue != "") {
return sQueryValue.Trim();
}
else {
return sDefault;
}
}
#endregion
邮件头解码#region 邮件头解码
public static string DecodeStr(string str) {
if (!string.IsNullOrEmpty(str)) {
string[] sArr = str.Split(new char[] { '?' });
if (sArr.Length == 5) {
System.Text.Encoding enc = System.Text.Encoding.GetEncoding(sArr[1]);
if (sArr[2].ToUpper() == "B") {
return enc.GetString(Convert.FromBase64String(sArr[3]));
}
else if (sArr[2].ToUpper() == "Q") {
return QDecode(enc, sArr[3]);
}
}
return (str != "") ? str : "无主题";
}
else {
return "无主题";
}
}
/**//// <summary>
/// quoted-printable decoder.
/// </summary>
/// <param name="encoding">Input string encoding.</param>
/// <param name="data">String which to encode.</param>
/// <returns></returns>
public static string QDecode(System.Text.Encoding encoding, string data) {
// ASCII
MemoryStream strm = new MemoryStream(System.Text.Encoding.Default.GetBytes(data));
int b = strm.ReadByte();
MemoryStream dStrm = new MemoryStream();
while (b > -1) {
// Hex eg. =E4
if (b == '=') {
byte[] buf = new byte[2];
strm.Read(buf, 0, 2);
// <CRLF> followed by =, it's splitted line
if (!(buf[0] == '\r' && buf[1] == '\n')) {
try {
int val = int.Parse(System.Text.Encoding.Default.GetString(buf), System.Globalization.NumberStyles.HexNumber);
//string encodedChar = encoding.GetString(new byte[] { (byte)val });
//byte[] d = System.Text.Encoding.Unicode.GetBytes(encodedChar);
byte[] d = new byte[] { (byte)val };
dStrm.Write(d, 0, d.Length);
}
catch { // If worng hex value, just skip this chars
}
}
}
else {
string encodedChar = encoding.GetString(new byte[] { (byte)b });
byte[] d = System.Text.Encoding.Default.GetBytes(encodedChar);
dStrm.Write(d, 0, d.Length);
}
b = strm.ReadByte();
}
return encoding.GetString(dStrm.ToArray());
//return System.Text.Encoding.Unicode.GetString(dStrm.ToArray());
}
#endregion
GetAddress#region GetAddress
public static MailAddressCollection GetAddress(string strAddress) {
int len = 0;
return GetAddress(strAddress, ref len);
}
/**//// <summary>
/// 分析邮件地址
/// </summary>
/// <param name="strAddress">邮件地址串如:"姓名" <邮件地址></param>
/// <param name="totalLength">总长度.用于计算邮件大小</param>
/// <returns></returns>
public static MailAddressCollection GetAddress(string strAddress, ref int totalLength) {
MailAddressCollection addr = new MailAddressCollection();
int newl = 0;
if (!string.IsNullOrEmpty(strAddress)) {
string[] addressList = strAddress.Trim().Split(new char[] { ',' });
foreach (string address in addressList) {
int p = address.IndexOf("<");
if (p != -1) {
string displayName = address.Substring(0, p - 1).Trim();
displayName = displayName.Replace("\"", "");
string emailAddress = address.Substring(p + 1).Trim();
emailAddress = emailAddress.Replace(">", "");
try {
addr.Add(new MailAddress(emailAddress, displayName));
}
catch {
}
newl += displayName.Length + emailAddress.Length;
}
else {
try {
addr.Add(new MailAddress(address, address));
}
catch {
}
}
}
}
totalLength = newl;
return addr;
}
#endregion
简单的字符串加密解密#region 简单的字符串加密解密
//加密
public static string Encrypt(string data, string skey) {
if (!string.IsNullOrEmpty(data) && data != "") {
string encodestr = "";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
try {
encodestr = Convert.ToBase64String(bytes);
}
catch {
encodestr = data;
}
return encodestr;
}
else {
return "";
}
}
//解密
public static string Decrypt(string data, string skey) {
if (!string.IsNullOrEmpty(data) && data != "") {
string decodestr = "";
byte[] bytes = Convert.FromBase64String(data);
try {
decodestr = System.Text.Encoding.UTF8.GetString(bytes);
}
catch {
decodestr = data;
}
return decodestr;
}
else {
return "";
}
}
#endregion
}
}