这个是对于
email发送系统(c#+基于smtp认证) 1.0
的改版这个第一版是2002年11月写的,过了一年半了,才有人提意见,就修正了一下,因为后来做的项目一直用不上,也就没有注意到
前段时间有网友反馈了一些问题,这次主要做了一些修正
1,text模式下发往163的邮件内容不见了
2,如果用outlook接收而不是在网上看邮件的话,会发现正文内容,但其后跟着一些乱码.
3,一些新开通的邮箱收到的是乱码,如*@126.com
4,修正了带附件的邮件,打开附件时内容混乱的问题
感谢 lion互动网络论坛 的smhy8187和邮箱是grassdragon_china@yahoo.com.cn的朋友提供意见
欢迎大家提出修改建议,[注:]最好能把修改稿mail给我一份,我们共同学习
我的email:lion-a@sohu.com lion.net@163.com
------------------------------------------
源码下载:点击下载
以下是程序源码:
using system;
using system.text;
using system.io;
using system.net;
using system.net.sockets;
using system.collections;
namespace lion.web.mail
{
/*
create by lion
2004-04-23 19:00
copyright (c) 2001,2002 www.lionsky.net. all rights reserved.
web: http://www.lionsky.net ;;
email: lion-a@sohu.com
support .net framework beta 2
*/
#region aspnetpager server control
/// <summary>
/// 邮件可以通过 microsoft windows 2000 中内置的 smtp 邮件服务或任意 smtp 服务器来传送
/// </summary>
public class smtpmail
{
private string enter="\r\n";
/// <summary>
/// 设定语言代码,默认设定为gb2312,如不需要可设置为""
/// </summary>
private string _charset="gb2312";
/// <summary>
/// 发件人地址
/// </summary>
private string _from="";
/// <summary>
/// 发件人姓名
/// </summary>
private string _fromname="";
/// <summary>
/// 回复邮件地址
/// </summary>
///public string replyto="";
/// <summary>
/// 收件人姓名
/// </summary>
private string _recipientname="";
/// <summary>
/// 收件人列表
/// </summary>
private hashtable recipient=new hashtable();
/// <summary>
/// 邮件服务器域名
/// </summary>
private string mailserver="";
/// <summary>
/// 邮件服务器端口号
/// </summary>
private int mailserverport=25;
/// <summary>
/// smtp认证时使用的用户名
/// </summary>
private string username="";
/// <summary>
/// smtp认证时使用的密码
/// </summary>
private string password="";
/// <summary>
/// 是否需要smtp验证
/// </summary>
private bool esmtp=false;
/// <summary>
/// 是否html邮件
/// </summary>
private bool _html=false;
/// <summary>
/// 邮件附件列表
/// </summary>
private ilist attachments;
/// <summary>
/// 邮件发送优先级,可设置为"high","normal","low"或"1","3","5"
/// </summary>
private string priority="normal";
/// <summary>
/// 邮件主题
/// </summary>
private string _subject;
/// <summary>
/// 邮件正文
/// </summary>
private string _body;
/// <summary>
/// 密送收件人列表
/// </summary>
///private hashtable recipientbcc=new hashtable();
/// <summary>
/// 收件人数量
/// </summary>
private int recipientnum=0;
/// <summary>
/// 最多收件人数量
/// </summary>
private int recipientmaxnum=5;
/// <summary>
/// 密件收件人数量
/// </summary>
///private int recipientbccnum=0;
/// <summary>
/// 错误消息反馈
/// </summary>
private string errmsg;
/// <summary>
/// tcpclient对象,用于连接服务器
/// </summary>
private tcpclient tc;
/// <summary>
/// networkstream对象
/// </summary>
private networkstream ns;
/// <summary>
/// 服务器交互记录
/// </summary>
private string logs="";
/// <summary>
/// smtp错误代码哈希表
/// </summary>
private hashtable errcodeht = new hashtable();
/// <summary>
/// smtp正确代码哈希表
/// </summary>
private hashtable rightcodeht = new hashtable();
/// <summary>
/// 初始化 <see cref="lion.web.mail.smtpmail"/> 类的新实例
/// </summary>
public smtpmail()
{
attachments = new system.collections.arraylist();
}
#region properties
/// <summary>
/// 邮件主题
/// </summary>
public string subject
{
get
{
return this._subject;
}
set
{
this._subject = value;
}
}
/// <summary>
/// 邮件正文
/// </summary>
public string body
{
get
{
return this._body;
}
set
{
this._body = value;
}
}
/// <summary>
/// 发件人地址
/// </summary>
public string from
{
get
{
return _from;
}
set
{
this._from = value;
}
}
/// <summary>
/// 设定语言代码,默认设定为gb2312,如不需要可设置为""
/// </summary>
public string charset
{
get
{
return this._charset;
}
set
{
this._charset = value;
}
}
/// <summary>
/// 发件人姓名
/// </summary>
public string fromname
{
get
{
return this._fromname;
}
set
{
this._fromname = value;
}
}
/// <summary>
/// 收件人姓名
/// </summary>
public string recipientname
{
get
{
return this._recipientname;
}
set
{
this._recipientname = value;
}
}
/// <summary>
/// 邮件服务器域名和验证信息
/// 形如:"user:pass@www.server.com:25",也可省略次要信息。如"user:pass@www.server.com"或"www.server.com"
/// </summary>
public string maildomain
{
set
{
string maidomain=value.trim();
int tempint;
if(maidomain!="")
{
tempint=maidomain.indexof("@");
if(tempint!=-1)
{
string str=maidomain.substring(0,tempint);
mailserverusername=str.substring(0,str.indexof(":"));
mailserverpassword=str.substring(str.indexof(":")+1,str.length-str.indexof
(":")-1);
maidomain=maidomain.substring(tempint+1,maidomain.length-tempint-1);
}
tempint=maidomain.indexof(":");
if(tempint!=-1)
{
mailserver=maidomain.substring(0,tempint);
mailserverport=system.convert.toint32(maidomain.substring
(tempint+1,maidomain.length-tempint-1));
}
else
{
mailserver=maidomain;
}
}
}
}
/// <summary>
/// 邮件服务器端口号
/// </summary>
public int maildomainport
{
set
{
mailserverport=value;
}
}
/// <summary>
/// smtp认证时使用的用户名
/// </summary>
public string mailserverusername
{
set
{
if(value.trim()!="")
{
username=value.trim();
esmtp=true;
}
else
{
username="";
esmtp=false;
}
}
}
/// <summary>
/// smtp认证时使用的密码
/// </summary>
public string mailserverpassword
{
set
{
password=value;
}
}
/// <summary>
/// 邮件发送优先级,可设置为"high","normal","low"或"1","3","5"
/// </summary>
public string priority
{
set
{
switch(value.tolower())
{
case "high":
priority="high";
break;
case "1":
priority="high";
break;
case "normal":
priority="normal";
break;
case "3":
priority="normal";
break;
case "low":
priority="low";
break;
case "5":
priority="low";
break;
default:
priority="normal";
break;
}
}
}
/// <summary>
/// 是否html邮件
/// </summary>
public bool html
{
get
{
return this._html;
}
set
{
this._html = value;
}
}
/// <summary>
/// 错误消息反馈
/// </summary>
public string errormessage
{
get
{
return errmsg;
}
}
/// <summary>
/// 服务器交互记录,如发现本组件不能使用的smtp服务器,请将出错时的logs发给我(lion-a@sohu.com),我将尽快查明
原因。
/// </summary>
public string logs
{
get
{
return logs;
}
}
/// <summary>
/// 最多收件人数量
/// </summary>
public int recipientmaxnum
{
set
{
recipientmaxnum = value;
}
}
#endregion
#region methods
/// <summary>
/// 添加邮件附件
/// </summary>
/// <param name="filepath">附件绝对路径</param>
public void addattachment(params string[] filepath)
{
if(filepath==null)
{
throw(new argumentnullexception("filepath"));
}
for(int i=0;i<filepath.length;i++)
{
attachments.add(filepath[i]);
}
}
/// <summary>
/// 添加一组收件人(不超过recipientmaxnum个),参数为字符串数组
/// </summary>
/// <param name="recipients">保存有收件人地址的字符串数组(不超过recipientmaxnum个)</param>
public bool addrecipient(params string[] recipients)
{
if(recipient==null)
{
dispose();
throw(new argumentnullexception("recipients"));
}
for(int i=0;i<recipients.length;i++)
{
string recipient = recipients[i].trim();
if(recipient==string.empty)
{
dispose();
throw(new argumentnullexception("recipients["+ i +"]"));
}
if(recipient.indexof("@")==-1)
{
dispose();
throw(new argumentexception("recipients.indexof(\"@\")==-1","recipients"));
}
if(!addrecipient(recipient))
{
return false;
}
}
return true;
}
/// <summary>
/// 发送邮件方法,所有参数均通过属性设置。
/// </summary>
public bool send()
{
if(mailserver.trim()=="")
{
throw(new argumentnullexception("recipient","必须指定smtp服务器"));
}
return sendemail();
}
/// <summary>
/// 发送邮件方法
/// </summary>
/// <param name="smtpserver">smtp服务器信息,如"username:password@www.smtpserver.com:25",也可去掉部分次要信
息,如"www.smtpserver.com"</param>
public bool send(string smtpserver)
{
maildomain=smtpserver;
return send();
}
/// <summary>
/// 发送邮件方法
/// </summary>
/// <param name="smtpserver">smtp服务器信息,如"username:password@www.smtpserver.com:25",也可去掉部分次要信
息,如"www.smtpserver.com"</param>
/// <param name="from">发件人mail地址</param>
/// <param name="fromname">发件人姓名</param>
/// <param name="to">收件人地址</param>
/// <param name="toname">收件人姓名</param>
/// <param name="html">是否html邮件</param>
/// <param name="subject">邮件主题</param>
/// <param name="body">邮件正文</param>
public bool send(string smtpserver,string from,string fromname,string to,string toname,bool html,string
subject,string body)
{
maildomain=smtpserver;
from=from;
fromname=fromname;
addrecipient(to);
recipientname=toname;
html=html;
subject=subject;
body=body;
return send();
}
#endregion
#region private helper functions
/// <summary>
/// 添加一个收件人
/// </summary>
/// <param name="recipients">收件人地址</param>
private bool addrecipient(string recipients)
{
if(recipientnum<recipientmaxnum)
{
recipient.add(recipientnum,recipients);
recipientnum++;
return true;
}
else
{
dispose();
throw(new argumentoutofrangeexception("recipients","收件人过多不可多于 "+ recipientmaxnum +"
个"));
}
}
void dispose()
{
if(ns!=null)ns.close();
if(tc!=null)tc.close();
}
/// <summary>
/// smtp回应代码哈希表
/// </summary>
private void smtpcodeadd()
{
errcodeht.add("500","邮箱地址错误");
errcodeht.add("501","参数格式错误");
errcodeht.add("502","命令不可实现");
errcodeht.add("503","服务器需要smtp验证");
errcodeht.add("504","命令参数不可实现");
errcodeht.add("421","服务未就绪,关闭传输信道");
errcodeht.add("450","要求的邮件操作未完成,邮箱不可用(例如,邮箱忙)");
errcodeht.add("550","要求的邮件操作未完成,邮箱不可用(例如,邮箱未找到,或不可访问)");
errcodeht.add("451","放弃要求的操作;处理过程中出错");
errcodeht.add("551","用户非本地,请尝试<forward-path>");
errcodeht.add("452","系统存储不足,要求的操作未执行");
errcodeht.add("552","过量的存储分配,要求的操作未执行");
errcodeht.add("553","邮箱名不可用,要求的操作未执行(例如邮箱格式错误)");
errcodeht.add("432","需要一个密码转换");
errcodeht.add("534","认证机制过于简单");
errcodeht.add("538","当前请求的认证机制需要加密");
errcodeht.add("454","临时认证失败");
errcodeht.add("530","需要认证");
rightcodeht.add("220","服务就绪");
rightcodeht.add("250","要求的邮件操作完成");
rightcodeht.add("251","用户非本地,将转发向<forward-path>");
rightcodeht.add("354","开始邮件输入,以<enter>.<enter>结束");
rightcodeht.add("221","服务关闭传输信道");
rightcodeht.add("334","服务器响应验证base64字符串");
rightcodeht.add("235","验证成功");
}
/// <summary>
/// 将字符串编码为base64字符串
/// </summary>
/// <param name="str">要编码的字符串</param>
private string base64encode(string str)
{
byte[] barray;
barray=encoding.default.getbytes(str);
return convert.tobase64string(barray);
}
/// <summary>
/// 将base64字符串解码为普通字符串
/// </summary>
/// <param name="str">要解码的字符串</param>
private string base64decode(string str)
{
byte[] barray;
barray=convert.frombase64string(str);
return encoding.default.getstring(barray);
}
/// <summary>
/// 得到上传附件的文件流
/// </summary>
/// <param name="filepath">附件的绝对路径</param>
private string getstream(string filepath)
{
//建立文件流对象
system.io.filestream filestr=new system.io.filestream(filepath,system.io.filemode.open);
byte[] by=new byte[system.convert.toint32(filestr.length)];
filestr.read(by,0,by.length);
filestr.close();
return(system.convert.tobase64string(by));
}
/// <summary>
/// 发送smtp命令
/// </summary>
private bool sendcommand(string str)
{
byte[] writebuffer;
if(str==null||str.trim()==string.empty)
{
return true;
}
logs+=str;
writebuffer = encoding.default.getbytes(str);
try
{
ns.write(writebuffer,0,writebuffer.length);
}
catch
{
errmsg="网络连接错误";
return false;
}
return true;
}
/// <summary>
/// 接收smtp服务器回应
/// </summary>
private string recvresponse()
{
int streamsize;
string returnvalue = string.empty;
byte[] readbuffer = new byte[1024] ;
try
{
streamsize=ns.read(readbuffer,0,readbuffer.length);
}
catch
{
errmsg="网络连接错误";
return "false";
}
if (streamsize==0)
{
return returnvalue ;
}
else
{
returnvalue = encoding.default.getstring(readbuffer).substring(0,streamsize);
logs+=returnvalue+this.enter;
return returnvalue;
}
}
/// <summary>
/// 与服务器交互,发送一条命令并接收回应。
/// </summary>
/// <param name="str">一个要发送的命令</param>
/// <param name="errstr">如果错误,要反馈的信息</param>
private bool dialog(string str,string errstr)
{
if(str==null||str.trim()=="")
{
return true;
}
if(sendcommand(str))
{
string rr=recvresponse();
if(rr=="false")
{
return false;
}
string rrcode=rr.substring(0,3);
if(rightcodeht[rrcode]!=null)
{
return true;
}
else
{
if(errcodeht[rrcode]!=null)
{
errmsg+=(rrcode+errcodeht[rrcode].tostring());
errmsg+=enter;
}
else
{
errmsg+=rr;
}
errmsg+=errstr;
return false;
}
}
else
{
return false;
}
}
/// <summary>
/// 与服务器交互,发送一组命令并接收回应。
/// </summary>
private bool dialog(string[] str,string errstr)
{
for(int i=0;i<str.length;i++)
{
if(!dialog(str[i],""))
{
errmsg+=enter;
errmsg+=errstr;
return false;
}
}
return true;
}
/// <summary>
/// sendemail
/// </summary>
/// <returns></returns>
private bool sendemail()
{
//连接网络
try
{
tc=new tcpclient(mailserver,mailserverport);
}
catch(exception e)
{
errmsg=e.tostring();
return false;
}
ns = tc.getstream();
smtpcodeadd();
//验证网络连接是否正确
if(rightcodeht[recvresponse().substring(0,3)]==null)
{
errmsg="网络连接失败";
return false;
}
string[] sendbuffer;
string sendbufferstr;
//进行smtp验证
if(esmtp)
{
sendbuffer=new string[4];
sendbuffer[0]="ehlo " + mailserver + enter;
sendbuffer[1]="auth login" + enter;
sendbuffer[2]=base64encode(username) + enter;
sendbuffer[3]=base64encode(password) + enter;
if(!dialog(sendbuffer,"smtp服务器验证失败,请核对用户名和密码。"))
return false;
}
else
{
sendbufferstr="helo " + mailserver + enter;
if(!dialog(sendbufferstr,""))
return false;
}
//
sendbufferstr="mail from:<" + from + ">" + enter;
if(!dialog(sendbufferstr,"发件人地址错误,或不能为空"))
return false;
//
sendbuffer=new string[recipientmaxnum];
for(int i=0;i<recipient.count;i++)
{
sendbuffer[i]="rcpt to:<" + recipient[i].tostring() +">" + enter;
}
if(!dialog(sendbuffer,"收件人地址有误"))
return false;
/*
sendbuffer=new string[10];
for(int i=0;i<recipientbcc.count;i++)
{
sendbuffer[i]="rcpt to:<" + recipientbcc[i].tostring() +">" + enter;
}
if(!dialog(sendbuffer,"密件收件人地址有误"))
return false;
*/
sendbufferstr="data" + enter;
if(!dialog(sendbufferstr,""))
return false;
sendbufferstr="from:" + fromname + "<" + from +">" +enter;
//if(replyto.trim()!="")
//{
// sendbufferstr+="reply-to: " + replyto + enter;
//}
//sendbufferstr+="to:" + recipientname + "<" + recipient[0] +">" +enter;
sendbufferstr += "to:=?"+charset.toupper()+"?b?"+base64encode(recipientname)+"?="+"<"+recipient[0]
+">"+enter;
sendbufferstr+="cc:";
for(int i=0;i<recipient.count;i++)
{
sendbufferstr+=recipient[i].tostring() + "<" + recipient[i].tostring() +">,";
}
sendbufferstr+=enter;
sendbufferstr+=((subject==string.empty || subject==null)?"subject:":((charset=="")?("subject:" +
subject):("subject:" + "=?" + charset.toupper() + "?b?" + base64encode(subject) +"?="))) + enter;
sendbufferstr+="x-priority:" + priority + enter;
sendbufferstr+="x-msmail-priority:" + priority + enter;
sendbufferstr+="importance:" + priority + enter;
sendbufferstr+="x-mailer: lion.web.mail.smtpmail pubclass [cn]" + enter;
sendbufferstr+="mime-version: 1.0" + enter;
if(attachments.count!=0)
{
sendbufferstr+="content-type: multipart/mixed;" + enter;
sendbufferstr += " boundary=\"====="+
(html?"001_dragon520636771063_":"001_dragon303406132050_")+"=====\""+enter+enter;
}
if(html)
{
if(attachments.count==0)
{
sendbufferstr += "content-type: multipart/alternative;"+enter;//内容格式和分隔符
sendbufferstr += " boundary=\"=====003_dragon520636771063_=====\""+enter+enter;
sendbufferstr += "this is a multi-part message in mime format."+enter+enter;
}
else
{
sendbufferstr +="this is a multi-part message in mime format."+enter+enter;
sendbufferstr += "–=====001_dragon520636771063_====="+enter;
sendbufferstr += "content-type: multipart/alternative;"+enter;//内容格式和分隔符
sendbufferstr += " boundary=\"=====003_dragon520636771063_=====\""+enter+enter;
}
sendbufferstr += "–=====003_dragon520636771063_====="+enter;
sendbufferstr += "content-type: text/plain;"+ enter;
sendbufferstr += ((charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" +
charset.tolower() + "\"")) + enter;
sendbufferstr+="content-transfer-encoding: base64" + enter + enter;
sendbufferstr+= base64encode("邮件内容为html格式,请选择html方式查看") + enter + enter;
sendbufferstr += "–=====003_dragon520636771063_====="+enter;
sendbufferstr+="content-type: text/html;" + enter;
sendbufferstr+=((charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" +
charset.tolower() + "\"")) + enter;
sendbufferstr+="content-transfer-encoding: base64" + enter + enter;
sendbufferstr+= base64encode(body) + enter + enter;
sendbufferstr += "–=====003_dragon520636771063_=====–"+enter;
}
else
{
if(attachments.count!=0)
{
sendbufferstr += "–=====001_dragon303406132050_====="+enter;
}
sendbufferstr+="content-type: text/plain;" + enter;
sendbufferstr+=((charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" +
charset.tolower() + "\"")) + enter;
sendbufferstr+="content-transfer-encoding: base64" + enter + enter;
sendbufferstr+= base64encode(body) + enter;
}
//sendbufferstr += "content-transfer-encoding: base64"+enter;
if(attachments.count!=0)
{
for(int i=0;i<attachments.count;i++)
{
string filepath = (string)attachments[i];
sendbufferstr += "–====="+
(html?"001_dragon520636771063_":"001_dragon303406132050_") +"====="+enter;
//sendbufferstr += "content-type: application/octet-stream"+enter;
sendbufferstr += "content-type: text/plain;"+enter;
sendbufferstr += " name=\"=?"+charset.toupper()+"?b?"+base64encode
(filepath.substring(filepath.lastindexof("\\")+1))+"?=\""+enter;
sendbufferstr += "content-transfer-encoding: base64"+enter;
sendbufferstr += "content-disposition: attachment;"+enter;
sendbufferstr += " filename=\"=?"+charset.toupper()+"?b?"+base64encode
(filepath.substring(filepath.lastindexof("\\")+1))+"?=\""+enter+enter;
sendbufferstr += getstream(filepath)+enter+enter;
}
sendbufferstr += "–====="+ (html?"001_dragon520636771063_":"001_dragon303406132050_")
+"=====–"+enter+enter;
}
sendbufferstr += enter + "." + enter;
if(!dialog(sendbufferstr,"错误信件信息"))
return false;
sendbufferstr="quit" + enter;
if(!dialog(sendbufferstr,"断开连接时错误"))
return false;
ns.close();
tc.close();
return true;
}
#endregion
#region
/*
/// <summary>
/// 添加一个密件收件人
/// </summary>
/// <param name="str">收件人地址</param>
public bool addrecipientbcc(string str)
{
if(str==null||str.trim()=="")
return true;
if(recipientbccnum<10)
{
recipientbcc.add(recipientbccnum,str);
recipientbccnum++;
return true;
}
else
{
errmsg+="收件人过多";
return false;
}
}
/// <summary>
/// 添加一组密件收件人(不超过10个),参数为字符串数组
/// </summary>
/// <param name="str">保存有收件人地址的字符串数组(不超过10个)</param>
public bool addrecipientbcc(string[] str)
{
for(int i=0;i<str.length;i++)
{
if(!addrecipientbcc(str[i]))
{
return false;
}
}
return true;
}
*/
#endregion
}
#endregion
}