首页 > 开发 > 综合 > 正文

C#邮件发送组件源代码

2024-07-21 02:26:26
字体:
来源:转载
供稿:网友

//============================================================
// 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).filename + """); // 文件格式
  writestring (tcp.getstream(), "content-transfer-encoding: base64"); // 内容的编码
  writestring (tcp.getstream(), "content-disposition:attachment;filename="" + ((attachmentinfo)attachments).filename + """); // 文件名
  writestring (tcp.getstream(), "");
  writestring (tcp.getstream(), ((attachmentinfo)attachments).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 + " "; // 加入换行符

  // 将命令行转化为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 = "[email protected]";
 ms.to = "[email protected]";
 ms.subject = "subject";
 ms.body = "body text";
 ms.username = "########"; // 怎么能告诉你呢
 ms.password = "********"; // 怎么能告诉你呢
 ms.server = "smtp.tom.com";

 ms.attachments.add (new mailsender.attachmentinfo (@"d: est.txt"));

 console.writeline ("mail sending...");
 try
 {
  ms.sendmail ();
  console.writeline ("mail sended.");
 }
 catch (exception e)
 {
  console.writeline (e);
 }

 

 

最大的网站源码资源下载站,

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表