首页 | 邮件资讯 | 技术教程 | 解决方案 | 产品评测 | 邮件人才 | 邮件博客 | 邮件系统论坛 | 软件下载 | 邮件周刊 | 热点专题 | 工具
网络技术 | 操作系统 | 邮件系统 | 客户端 | 电子邮箱 | 反垃圾邮件 | 邮件安全 | 邮件营销 | 移动电邮 | 邮件软件下载 | 电子书下载

邮件服务器

技术前沿 | Qmail | IMail | MDaemon | Exchange | Domino | 其它 | Foxmail | James | Kerio | JavaMail | WinMail | Sendmail | Postfix | Winwebmail | Merak | CMailServer | 邮件与开发 | 金笛 |
首页 > 邮件服务器 > 邮件与程序开发 > C# - MailSender 邮件发送组件源代码 (支持ESMTP, 附件) > 正文

C# - MailSender 邮件发送组件源代码 (支持ESMTP, 附件)

出处:本站收集于网络 作者:请作者联系 时间:2005-7-12 11:45:00

//============================================================
// file: MailSender.cs
// 邮件发送组件
// 支持ESMTP, 多附件
//============================================================

namespace JcPersonal.Utility
{
using System;
using System.Collections;
using System.Net.Sockets;
using System.IO;
using System.Text;

/// <summary>
/// Mail 发送器
/// </summary>
public class MailSender
{
/// <summary>
/// SMTP服务器域名
/// </summary>
public string Server {
get { return server; }
set { if (value != server) server = value; }
} private string server = "";

/// <summary>
/// SMTP服务器端口 [默认为25]
/// </summary>
public int Port {
get { return port; }
set { if (value != port) port = value; }
} private int port = 25;

/// <summary>
/// 用户名 [如果需要身份验证的话]
/// </summary>
public string UserName {
get { return userName; }
set { if (value != userName) userName = value; }
} private string userName = "";

/// <summary>
/// 密码 [如果需要身份验证的话]
/// </summary>
public string Password {
get { return password; }
set { if (value != password) password = value; }
} private string password = "";

/// <summary>
/// 发件人地址
/// </summary>
public string From {
get { return from; }
set { if (value != from) from = value;}
} private string from = "";

/// <summary>
/// 收件人地址
/// </summary>
public string To {
get { return to; }
set { if (value != to) to = value;}
} private string to = "";

/// <summary>
/// 发件人姓名
/// </summary>
public string FromName {
get { return fromName; }
set { if (value != fromName) fromName = value; }
} private string fromName = "";

/// <summary>
/// 收件人姓名
/// </summary>
public string ToName {
get { return toName; }
set { if (value != toName) toName = value; }
} private string toName = "";

/// <summary>
/// 邮件的主题
/// </summary>
public string Subject {
get { return subject; }
set { if (value != subject) subject = value; }
} private string subject = "";

/// <summary>
/// 邮件正文
/// </summary>
public string Body {
get { return body; }
set { if (value != body) body = value; }
} private string body = "";

/// <summary>
/// 超文本格式的邮件正文
/// </summary>
public string HtmlBody {
get { return htmlBody; }
set { if (value != htmlBody) htmlBody = value; }
} private string htmlBody = "";

/// <summary>
/// 是否是html格式的邮件
/// </summary>
public bool IsHtml {
get { return isHtml; }
set { if (value != isHtml) isHtml = value; }
} private bool isHtml = false;

/// <summary>
/// 语言编码 [默认为GB2312]
/// </summary>
public string LanguageEncoding {
get { return languageEncoding; }
set { if (value != languageEncoding) languageEncoding = value; }
} private string languageEncoding = "GB2312";

/// <summary>
/// 邮件编码 [默认为8bit]
/// </summary>
public string MailEncoding {
get { return encoding; }
set { if (value != encoding) encoding = value; }
} private string encoding = "8bit";

/// <summary>
/// 邮件优先级 [默认为3]
/// </summary>
public int Priority {
get { return priority; }
set { if (value != priority) priority = value; }
} private int priority = 3;

/// <summary>
/// 附件 [AttachmentInfo]
/// </summary>
public IList Attachments {
get { return attachments; }
// set { if (value != attachments) attachments = value; }
} private ArrayList attachments = new ArrayList ();


/// <summary>
/// 发送邮件
/// </summary>
public void SendMail ()
{
// 创建TcpClient对象, 并建立连接
TcpClient tcp = null;
try
{
tcp = new TcpClient (server, port);
}
catch (Exception)
{
throw new Exception ("无法连接服务器");
}

ReadString (tcp.GetStream());//获取连接信息

// 开始进行服务器认证
// 如果状态码是250则表示操作成功
if (!Command (tcp.GetStream(), "EHLO Localhost", "250"))
throw new Exception ("登陆阶段失败");

if (userName != "")
{
// 需要身份验证
if (!Command (tcp.GetStream(), "AUTH LOGIN", "334"))
throw new Exception ("身份验证阶段失败");
string nameB64 = ToBase64 (userName); // 此处将username转换为Base64码
if (!Command (tcp.GetStream(), nameB64, "334"))
throw new Exception ("身份验证阶段失败");
string passB64 = ToBase64 (password); // 此处将password转换为Base64码
if (!Command (tcp.GetStream(), passB64, "235"))
throw new Exception ("身份验证阶段失败");
}


// 准备发送
WriteString (tcp.GetStream(), "mail From: " + from);
WriteString (tcp.GetStream(), "rcpt to: " + to);
WriteString (tcp.GetStream(), "data");

// 发送邮件头
WriteString (tcp.GetStream(), "Date: " + DateTime.Now); // 时间
WriteString (tcp.GetStream(), "From: " + fromName + "<" + from + ">"); // 发件人
WriteString (tcp.GetStream(), "Subject: " + subject); // 主题
WriteString (tcp.GetStream(), "To:" + toName + "<" + to + ">"); // 收件人

//邮件格式
WriteString (tcp.GetStream(), "Content-Type: multipart/mixed; boundary=\"unique-boundary-1\"");
WriteString (tcp.GetStream(), "Reply-To:" + from); // 回复地址
WriteString (tcp.GetStream(), "X-Priority:" + priority); // 优先级
WriteString (tcp.GetStream(), "MIME-Version:1.0"); // MIME版本

// 数据ID,随意
// WriteString (tcp.GetStream(), "Message-Id: " + DateTime.Now.ToFileTime() + "@security.com");
WriteString (tcp.GetStream(), "Content-Transfer-Encoding:" + encoding); // 内容编码
WriteString (tcp.GetStream(), "X-Mailer:JcPersonal.Utility.MailSender"); // 邮件发送者
WriteString (tcp.GetStream(), "");

WriteString (tcp.GetStream(), ToBase64 ("This is a multi-part message in MIME format."));
WriteString (tcp.GetStream(), "");

// 从此处开始进行分隔输入
WriteString (tcp.GetStream(), "--unique-boundary-1");

// 在此处定义第二个分隔符
WriteString (tcp.GetStream(), "Content-Type: multipart/alternative;Boundary=\"unique-boundary-2\"");
WriteString (tcp.GetStream(), "");

if(!isHtml)
{
// 文本信息
WriteString (tcp.GetStream(), "--unique-boundary-2");
WriteString (tcp.GetStream(), "Content-Type: text/plain;charset=" + languageEncoding);
WriteString (tcp.GetStream(), "Content-Transfer-Encoding:" + encoding);
WriteString (tcp.GetStream(), "");
WriteString (tcp.GetStream(), body);
WriteString (tcp.GetStream(), "");//一个部分写完之后就写如空信息,分段
WriteString (tcp.GetStream(), "--unique-boundary-2--");//分隔符的结束符号,尾巴后面多了--
WriteString (tcp.GetStream(), "");
}
else
{
//html信息
WriteString (tcp.GetStream(), "--unique-boundary-2");
WriteString (tcp.GetStream(), "Content-Type: text/html;charset=" + languageEncoding);
WriteString (tcp.GetStream(), "Content-Transfer-Encoding:" + encoding);
WriteString (tcp.GetStream(), "");
WriteString (tcp.GetStream(), htmlBody);
WriteString (tcp.GetStream(), "");
WriteString (tcp.GetStream(), "--unique-boundary-2--");//分隔符的结束符号,尾巴后面多了--
WriteString (tcp.GetStream(), "");
}

// 发送附件
// 对文件列表做循环
for (int i = 0; i < attachments.Count; i++)
{
WriteString (tcp.GetStream(), "--unique-boundary-1"); // 邮件内容分隔符
WriteString (tcp.GetStream(), "Content-Type: application/octet-stream;name=\"" + ((AttachmentInfo)attachments[i]).FileName + "\""); // 文件格式
WriteString (tcp.GetStream(), "Content-Transfer-Encoding: base64"); // 内容的编码
WriteString (tcp.GetStream(), "Content-Disposition:attachment;filename=\"" + ((AttachmentInfo)attachments[i]).FileName + "\""); // 文件名
WriteString (tcp.GetStream(), "");
WriteString (tcp.GetStream(), ((AttachmentInfo)attachments[i]).Bytes); // 写入文件的内容
WriteString (tcp.GetStream(), "");
}

Command (tcp.GetStream(), ".", "250"); // 最后写完了,输入"."

// 关闭连接
tcp.Close ();
}

/// <summary>
/// 向流中写入字符
/// </summary>
/// <param name="netStream">来自TcpClient的流</param>
/// <param name="str">写入的字符</param>
protected void WriteString (NetworkStream netStream, string str)
{
str = str + "\r\n"; // 加入换行符

// 将命令行转化为byte[]
byte[] bWrite = Encoding.GetEncoding(languageEncoding).GetBytes(str.ToCharArray());

// 由于每次写入的数据大小是有限制的,那么我们将每次写入的数据长度定在75个字节,一旦命令长度超过了75,就分步写入。
int start=0;
int length=bWrite.Length;
int page=0;
int size=75;
int count=size;
try
{
if (length>75)
{
// 数据分页
if ((length/size)*size<length)
page=length/size+1;
else
page=length/size;
for (int i=0;i<page;i++)
{
start=i*size;
if (i==page-1)
count=length-(i*size);
netStream.Write(bWrite,start,count);// 将数据写入到服务器上
}
}
else
netStream.Write(bWrite,0,bWrite.Length);
}
catch(Exception)
{
// 忽略错误
}
}

/// <summary>
/// 从流中读取字符
/// </summary>
/// <param name="netStream">来自TcpClient的流</param>
/// <returns>读取的字符</returns>
protected string ReadString (NetworkStream netStream)
{
string sp = null;
byte[] by = new byte[1024];
int size = netStream.Read(by,0,by.Length);// 读取数据流
if (size > 0)
{
sp = Encoding.Default.GetString(by);// 转化为String
}
return sp;
}

/// <summary>
/// 发出命令并判断返回信息是否正确
/// </summary>
/// <param name="netStream">来自TcpClient的流</param>
/// <param name="command">命令</param>
/// <param name="state">正确的状态码</param>
/// <returns>是否正确</returns>
protected bool Command (NetworkStream netStream, string command, string state)
{
string sp=null;
bool success=false;
try
{
WriteString (netStream, command);// 写入命令
sp = ReadString (netStream);// 接受返回信息
if (sp.IndexOf(state) != -1)// 判断状态码是否正确
success=true;
}
catch(Exception)
{
// 忽略错误
}
return success;
}

/// <summary>
/// 字符串编码为Base64
/// </summary>
/// <param name="str">字符串</param>
/// <returns>Base64编码的字符串</returns>
protected string ToBase64 (string str)
{
try
{
byte[] by = Encoding.Default.GetBytes (str.ToCharArray());
str = Convert.ToBase64String (by);
}
catch(Exception)
{
// 忽略错误
}
return str;
}

/// <summary>
/// 附件信息
/// </summary>
public struct AttachmentInfo
{
/// <summary>
/// 附件的文件名 [如果输入路径,则自动转换为文件名]
/// </summary>
public string FileName {
get { return fileName; }
set { fileName = Path.GetFileName(value); }
} private string fileName;

/// <summary>
/// 附件的内容 [由经Base64编码的字节组成]
/// </summary>
public string Bytes {
get { return bytes; }
set { if (value != bytes) bytes = value; }
} private string bytes;

/// <summary>
/// 从流中读取附件内容并构造
/// </summary>
/// <param name="ifileName">附件的文件名</param>
/// <param name="stream">流</param>
public AttachmentInfo (string ifileName, Stream stream)
{
fileName = Path.GetFileName (ifileName);
byte[] by = new byte [stream.Length];
stream.Read (by,0,(int)stream.Length); // 读取文件内容
//格式转换
bytes = Convert.ToBase64String (by); // 转化为base64编码
}

/// <summary>
/// 按照给定的字节构造附件
/// </summary>
/// <param name="ifileName">附件的文件名</param>
/// <param name="ibytes">附件的内容 [字节]</param>
public AttachmentInfo (string ifileName, byte[] ibytes)
{
fileName = Path.GetFileName (ifileName);
bytes = Convert.ToBase64String (ibytes); // 转化为base64编码
}

/// <summary>
/// 从文件载入并构造
/// </summary>
/// <param name="path"></param>
public AttachmentInfo (string path)
{
fileName = Path.GetFileName (path);
FileStream file = new FileStream (path, FileMode.Open);
byte[] by = new byte [file.Length];
file.Read (by,0,(int)file.Length); // 读取文件内容
//格式转换
bytes = Convert.ToBase64String (by); // 转化为base64编码
file.Close ();
}
}
}
}

--------------------------------------------------------------------------------


// 使用:

MailSender ms = new MailSender ();
ms.From = "jovenc@tom.com";
ms.To = "jovenc@citiz.net";
ms.Subject = "Subject";
ms.Body = "body text";
ms.UserName = "########"; // 怎么能告诉你呢
ms.Password = "********"; // 怎么能告诉你呢
ms.Server = "smtp.tom.com";

ms.Attachments.Add (new MailSender.AttachmentInfo (@"D:\test.txt"));

Console.WriteLine ("mail sending...");
try
{
ms.SendMail ();
Console.WriteLine ("mail sended.");
}
catch (Exception e)
{
Console.WriteLine (e);
}

,
相关文章 热门文章
  • 腾讯,在创新中演绎互联网“进化论”
  • 华科人 张小龙 (中国第二代程序员 QQ邮箱 Foxmail)
  • 微软推出新功能 提高Hotmail密码安全性
  • 快压技巧分享:秒传邮件超大附件
  • 不容忽视的邮件营销数据分析过程中的算法问题
  • 国内手机邮箱的现状与未来发展——访尚邮创始人Sandy
  • 易观数据:2011Q2中国手机邮箱市场收入规模
  • 穿越时空的爱恋 QQ邮箱音视频及贺卡邮件
  • Hotmail新功能:“我的朋友可能被黑了”
  • 入侵邻居网络发骚扰邮件 美国男子被重判入狱18年
  • 网易邮箱莫子睿:《非你莫属》招聘多过作秀
  • 中国电信推广189邮箱绿色账单
  • 用C++ Builder实现电子邮件群发
  • 用Cdonts实现发送Email
  • Jmail的主要参数列表
  • ASP.NET 2.0发送电子邮件全面剖析之二
  • VC++ SMTP协议电子邮件传送剖析
  • 通过sina的smtp验证的Java发送邮件源代码
  • ASP.NET 2.0中发送电子邮件剖析之一
  • 在Asp.Net中使用SmtpMail发送邮件的方法
  • .NET环境下Email的技术介绍
  • ASP.NET 2.0发送电子邮件中存在的问题
  • 用ASP判断Email地址是否有效
  • IIS如何接收ServerXMLHTTP传过来的编码字符?
  • 自由广告区
     
    最新软件下载
  • SharePoint Server 2010 部署文档
  • Exchange 2010 RTM升级至SP1 教程
  • Exchange 2010 OWA下RBAC实现的组功能...
  • Lync Server 2010 Standard Edition 标..
  • Lync Server 2010 Enterprise Edition...
  • Forefront Endpoint Protection 2010 ...
  • Lync Server 2010 Edge 服务器部署文档
  • 《Exchange 2003专家指南》
  • Mastering Hyper-V Deployment
  • Windows Server 2008 R2 Hyper-V
  • Microsoft Lync Server 2010 Unleashed
  • Windows Server 2008 R2 Unleashed
  • 今日邮件技术文章
  • 腾讯,在创新中演绎互联网“进化论”
  • 华科人 张小龙 (中国第二代程序员 QQ...
  • 微软推出新功能 提高Hotmail密码安全性
  • 快压技巧分享:秒传邮件超大附件
  • 不容忽视的邮件营销数据分析过程中的算..
  • 国内手机邮箱的现状与未来发展——访尚..
  • 易观数据:2011Q2中国手机邮箱市场收入..
  • 穿越时空的爱恋 QQ邮箱音视频及贺卡邮件
  • Hotmail新功能:“我的朋友可能被黑了”
  • 入侵邻居网络发骚扰邮件 美国男子被重..
  • 网易邮箱莫子睿:《非你莫属》招聘多过..
  • 中国电信推广189邮箱绿色账单
  • 最新专题
  • 鸟哥的Linux私房菜之Mail服务器
  • Exchange Server 2010技术专题
  • Windows 7 技术专题
  • Sendmail 邮件系统配置
  • 组建Exchange 2003邮件系统
  • Windows Server 2008 专题
  • ORF 反垃圾邮件系统
  • Exchange Server 2007 专题
  • ISA Server 2006 教程专题
  • Windows Vista 技术专题
  • “黑莓”(BlackBerry)专题
  • Apache James 专题
  • 分类导航
    邮件新闻资讯:
    IT业界 | 邮件服务器 | 邮件趣闻 | 移动电邮
    电子邮箱 | 反垃圾邮件|邮件客户端|网络安全
    行业数据 | 邮件人物 | 网站公告 | 行业法规
    网络技术:
    邮件原理 | 网络协议 | 网络管理 | 传输介质
    线路接入 | 路由接口 | 邮件存储 | 华为3Com
    CISCO技术 | 网络与服务器硬件
    操作系统:
    Windows 9X | Linux&Uinx | Windows NT
    Windows Vista | FreeBSD | 其它操作系统
    邮件服务器:
    程序与开发 | Exchange | Qmail | Postfix
    Sendmail | MDaemon | Domino | Foxmail
    KerioMail | JavaMail | Winwebmail |James
    Merak&VisNetic | CMailServer | WinMail
    金笛邮件系统 | 其它 |
    反垃圾邮件:
    综述| 客户端反垃圾邮件|服务器端反垃圾邮件
    邮件客户端软件:
    Outlook | Foxmail | DreamMail| KooMail
    The bat | 雷鸟 | Eudora |Becky! |Pegasus
    IncrediMail |其它
    电子邮箱: 个人邮箱 | 企业邮箱 |Gmail
    移动电子邮件:服务器 | 客户端 | 技术前沿
    邮件网络安全:
    软件漏洞 | 安全知识 | 病毒公告 |防火墙
    攻防技术 | 病毒查杀| ISA | 数字签名
    邮件营销:
    Email营销 | 网络营销 | 营销技巧 |营销案例
    邮件人才:招聘 | 职场 | 培训 | 指南 | 职场
    解决方案:
    邮件系统|反垃圾邮件 |安全 |移动电邮 |招标
    产品评测:
    邮件系统 |反垃圾邮件 |邮箱 |安全 |客户端
    广告联系 | 合作联系 | 关于我们 | 联系我们 | 繁體中文
    版权所有:邮件技术资讯网©2003-2010 www.5dmail.net, All Rights Reserved
    www.5Dmail.net Web Team   粤ICP备05009143号