在asp.NET 中使用SMTP發(fā)送郵件的實(shí)現(xiàn)代碼
更新時(shí)間:2011年05月19日 21:46:18 作者:
本文簡(jiǎn)單介紹了SMTP協(xié)議(RFC2554)發(fā)送郵件的過(guò)程,并討論了在 .NET 中使用SMTP發(fā)送郵件由簡(jiǎn)到繁的三種不同方案、各自可能遇到的問(wèn)題及其解決辦法
核心代碼:
public class Mail
{
#region 郵件參數(shù)
static public string accountName = System.Configuration.ConfigurationManager.AppSettings["SmtpAccountName"];
static public string password = System.Configuration.ConfigurationManager.AppSettings["SmtpAccountPW"];
static public string smtpServer = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"];
static public int smtpPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["SmtpPort"]);
#endregion
/// <summary>
/// 郵件發(fā)送方法一
/// </summary>
/// <param name="sendTo"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
static public void SendMail(string sendTo, string subject, string body)
{
//.net smtp
System.Web.Mail.MailMessage mailmsg = new System.Web.Mail.MailMessage();
mailmsg.To = sendTo;
//mailmsg.Cc = cc;
mailmsg.Subject = subject;
mailmsg.Body = body;
mailmsg.BodyFormat = MailFormat.Html;
//sender here
mailmsg.From = Mail.accountName;
// certify needed
mailmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");//1 is to certify
//the user id
mailmsg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendusername",
Mail.accountName);
//the password
mailmsg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendpassword",
Mail.password);
System.Web.Mail.SmtpMail.SmtpServer = Mail.smtpServer;
System.Web.Mail.SmtpMail.Send(mailmsg);
}
/// <summary>
/// 郵件發(fā)送方法二
/// </summary>
/// <param name="sendTo"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
static public void SendMail2(string sendTo, string subject, string body)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(accountName, sendTo, subject, body);
msg.From = new System.Net.Mail.MailAddress(accountName, "Mail");
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpServer);
msg.IsBodyHtml = true;
client.Credentials = new System.Net.NetworkCredential(accountName, password);
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.Send(msg);
}
}
摘要
本文簡(jiǎn)單介紹了SMTP協(xié)議(RFC2554)發(fā)送郵件的過(guò)程,并討論了在 .NET 中使用SMTP發(fā)送郵件由簡(jiǎn)到繁的三種不同方案、各自可能遇到的問(wèn)題及其解決辦法。
目錄
? .NET的SMTP類(lèi)
? 使用CDO組件發(fā)送郵件
? 使用Socket撰寫(xiě)郵件發(fā)送程序
總結(jié)
簡(jiǎn)介
郵件發(fā)送功能常常是許多.NET應(yīng)用,尤其是帶網(wǎng)絡(luò)功能的應(yīng)用中不可缺少的模塊之一,本文就此介紹了使用.NET的SMTP類(lèi)庫(kù)和另兩種分別通過(guò)CDO(Collaboration Data Objects)及Socket來(lái)實(shí)現(xiàn)發(fā)送郵件功能的方法。
.NET的SMTP類(lèi)
首先,我們來(lái)介紹一下.NET類(lèi)庫(kù)種自帶的SMTP類(lèi)。在.NET中的System.Web.Mail名字空間下,有一個(gè)專(zhuān)門(mén)使用SMTP協(xié)議來(lái)發(fā)送郵件的類(lèi):SmtpMail,它已能滿足最普通的發(fā)送郵件的需求。這個(gè)類(lèi)只有一個(gè)自己的公共函數(shù)--Send()和一個(gè)公共屬性—SmtpServer,如下圖:
您必須通過(guò)SmtpServer屬性來(lái)指定發(fā)送郵件的服務(wù)器的名稱(chēng)(或IP地址),然后再調(diào)用
Send()函數(shù)來(lái)發(fā)送郵件。
代碼示例如下:
(in C#)
using System.Web.Mail;
public void sendMail()
{
try
{
System.Web.Mail.MailMessage myMail=new MailMessage();
myMail.From = "myaccount@test.com";
myMail.To = "myaccount@test.com";
myMail.Subject = "MailTest";
myMail.Priority = MailPriority.Low;
myMail.BodyFormat = MailFormat.Text;
myMail.Body = "Test";
SmtpMail.SmtpServer="smarthost"; //your smtp server here
SmtpMail.Send(myMail);
}
catch(Exception e)
{
throw e;
}
}
您可以在Send函數(shù)的參數(shù)MailMessage對(duì)象中設(shè)置郵件的相關(guān)屬性,如優(yōu)先級(jí)、附件等等。除了以MailMessage對(duì)象為參數(shù)(如上述代碼),Send函數(shù)還可以簡(jiǎn)單的直接以郵件的4個(gè)主要信息(from,to,subject,messageText)作為字符串參數(shù)來(lái)調(diào)用。
使用CDO組件發(fā)送郵件
CDO是Collaboration Data Objects的簡(jiǎn)稱(chēng),它是一組高層的COM對(duì)象集合,并經(jīng)歷了好幾個(gè)版本的演化,現(xiàn)在在Windows2000和Exchange2000中使用的都是CDO2.0的版本(分別為cdosys.dll和cdoex.dll)。CDOSYS構(gòu)建在SMTP協(xié)議和NNTP協(xié)議之上,并且作為Windows2000 Server的組件被安裝,您可以在系統(tǒng)目錄(如c:\winnt或c:\windows)的system32子目錄中找到它(cdosys.dll)。
CDO組件相對(duì)于先前介紹的SmtpMail對(duì)象功能更為豐富,并提供了一些SmtpMail類(lèi)所沒(méi)有提供的功能,如通過(guò)需要認(rèn)證的SMTP服務(wù)器發(fā)送郵件等。
下面一段代碼就展示了如何使用CDO組件通過(guò)需要認(rèn)證的SMTP服務(wù)器發(fā)送郵件的過(guò)程:
(in C#)
public void CDOsendMail()
{
try
{
CDO.Message oMsg = new CDO.Message();
oMsg.From = "myaccount@test.com";
oMsg.To = "myaccount@test.com";
oMsg.Subject = "MailTest";
oMsg.HTMLBody = "<html><body>Test</body></html>";
CDO.IConfiguration iConfg = oMsg.Configuration;
ADODB.Fields oFields = iConfg.Fields;
oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value=2;
oFields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value="myaccount@test.com"; //sender mail oFields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value="myaccount@test.com"; //email account oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value="username"; oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value="password"; oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value=1;
//value=0 代表Anonymous驗(yàn)證方式(不需要驗(yàn)證)
//value=1 代表Basic驗(yàn)證方式(使用basic (clear-text) authentication.
//The configuration sendusername/sendpassword or postusername/postpassword fields are used to specify credentials.)
//Value=2 代表NTLM驗(yàn)證方式(Secure Password Authentication in Microsoft Outlook Express)
oFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value=0x0804;
oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value="smtp.21cn.com";
oFields.Update();
oMsg.BodyPart.Charset="gb2312";
oMsg.HTMLBodyPart.Charset="gb2312";
oMsg.Send();
oMsg = null;
}
catch (Exception e)
{
throw e;
}
}
注意:由于Exchange2000的CDO組件cdoex.dll會(huì)更新原有的Windows2000的CDO組件cdosys.dll,所以如果您希望繼續(xù)使用cdosys.dll,您必須先通過(guò)regsrv32.exe卸載掉cdoex.dll。
使用Socket撰寫(xiě)郵件發(fā)送程序
當(dāng)然,如果您覺(jué)得SmtpMail不能滿足您的需求,CDO又不夠直截了當(dāng),那就只能自己動(dòng)手了;其實(shí)如果您很熟悉Socket編程,自己寫(xiě)一個(gè)發(fā)送郵件的程序并不很難,以下就是一個(gè)例子。
首先,我們簡(jiǎn)單介紹一下帶驗(yàn)證的SMTP服務(wù)器如何使用AUTH原語(yǔ)進(jìn)行身份驗(yàn)證,其詳細(xì)的定義可以參考RFC2554。
具體如下:
1)首先,需要使用EHLO而不是原先的HELO。
2)EHLO成功以后,客戶端需要發(fā)送AUTH原語(yǔ),與服務(wù)器就認(rèn)證時(shí)用戶名和密碼的傳遞方式進(jìn)行協(xié)商。
3)如果協(xié)商成功,服務(wù)器會(huì)返回以3開(kāi)頭的結(jié)果碼,這是就可以把用戶名和密碼傳給服務(wù)器。
4)最后,如果驗(yàn)證成功,就可以開(kāi)始發(fā)信了。
下面是一個(gè)實(shí)際的例子,客戶端在WinXP的Command窗口中通過(guò)“telnet smtp.263.NET 25="命令連接到263的smtp服務(wù)器發(fā)信:
220 Welcome to coremail System(With Anti-Spam) 2.1
EHLO 263.NET
250-192.168.30.29
250-PIPELINING
250-SIZE 10240000
250-ETRN
250-AUTH LOGIN
250 8BITMIME
AUTH LOGIN
334 VXNlcm5hbWU6
bXlhY2NvdW50
334 UGFzc3dvcmQ6
bXlwYXNzd29yZA==
235 Authentication successful
MAIL FROM:myaccount@263.NET
250 Ok
RCPT TO:myaccount@263.NET
250 Ok
Data
354 End data with <CR><LF>.<CR><LF>
This is a testing email.
haha.
.
250 Ok: queued as AC5291D6406C4
QUIT
221 Bye
上面的內(nèi)容就是發(fā)信的全過(guò)程。其中與身份驗(yàn)證有關(guān)的主要是第九到第十四行:
AUTH LOGIN ';';';';客戶端輸入
334 VXNlcm5hbWU6 ';';';';服務(wù)器提示“Username:="
bXlhY2NvdW50 ';';';';客戶端輸入“myaccount="的Base64編碼
334 UGFzc3dvcmQ6 ';';';';服務(wù)器提示“Password:="
bXlwYXNzd29yZA== ';';';';客戶端輸入“mypassword="的Base64編碼
235 Authentication successful ';';';';服務(wù)器端通過(guò)驗(yàn)證
從上面的分析可以看出,在這個(gè)身份驗(yàn)證過(guò)程中,服務(wù)器和客戶端都直接通過(guò)Socket傳遞經(jīng)過(guò)標(biāo)準(zhǔn)Base64編碼的純文本。這個(gè)過(guò)程可以非常方便的用C#實(shí)現(xiàn),或者直接添加到原有的源代碼中。
另外,有些ESMTP服務(wù)器不支持AUTH LOGIN方式的認(rèn)證,只支持AUTH CRAM-MD5方式驗(yàn)證。但是這兩者之間的區(qū)別只是文本的編碼方式不同。
實(shí)現(xiàn)此功能的源代碼可以在SourceForge.NET http://sourceforge.NET/projects/opensmtp-net/ 上找到下載。下面給出了一個(gè)簡(jiǎn)單的偽碼:
public void SendMail(MailMessage msg)
{
NetworkStream nwstream = GetConnection();
WriteToStream(ref nwstream, "EHLO " + smtpHost + "\r\n");
string welcomeMsg = ReadFromStream(ref nwstream);
// implement HELO command if EHLO is unrecognized.
if (IsUnknownCommand(welcomeMsg))
{
WriteToStream(ref nwstream, "HELO " + smtpHost + "\r\n");
}
CheckForError(welcomeMsg, ReplyConstants.OK);
// Authentication is used if the u/p are supplied
AuthLogin(ref nwstream);
WriteToStream(ref nwstream, "MAIL FROM: <" + msg.From.Address + ">\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.OK);
SendRecipientList(ref nwstream, msg.To);
SendRecipientList(ref nwstream, msg.CC);
SendRecipientList(ref nwstream, msg.BCC);
WriteToStream(ref nwstream, "DATA\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.START_INPUT);
if (msg.ReplyTo.Name != null && msg.ReplyTo.Name.Length != 0)
{ WriteToStream(ref nwstream, "Reply-To: \"" + msg.ReplyTo.Name + "\" <" +
msg.ReplyTo.Address + ">\r\n"); }
else
{ WriteToStream(ref nwstream, "Reply-To: <" + msg.ReplyTo.Address + ">\r\n"); }
if (msg.From.Name != null && msg.From.Name.Length != 0)
{ WriteToStream(ref nwstream, "From: \"" + msg.From.Name + "\" <" +
msg.From.Address + ">\r\n"); }
else
{ WriteToStream(ref nwstream, "From: <" + msg.From.Address + ">\r\n"); }
WriteToStream(ref nwstream, "To: " + CreateAddressList(msg.To) + "\r\n");
if (msg.CC.Count != 0)
{ WriteToStream(ref nwstream, "CC: " + CreateAddressList(msg.CC) + "\r\n"); }
WriteToStream(ref nwstream, "Subject: " + msg.Subject + "\r\n");
if (msg.Priority != null)
{ WriteToStream(ref nwstream, "X-Priority: " + msg.Priority + "\r\n"); }
if (msg.Headers.Count > 0)
{
SendHeaders(ref nwstream, msg);
}
if (msg.Attachments.Count > 0 || msg.HtmlBody != null)
{
SendMessageBody(ref nwstream, msg);
}
else
{
WriteToStream(ref nwstream, msg.Body + "\r\n");
}
WriteToStream(ref nwstream, "\r\n.\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.OK);
WriteToStream(ref nwstream, "QUIT\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.QUIT);
CloseConnection();
}
private bool AuthLogin(ref NetworkStream nwstream)
{
if (username != null && username.Length > 0 && password != null && password.Length > 0)
{
WriteToStream(ref nwstream, "AUTH LOGIN\r\n");
if (AuthImplemented(ReadFromStream(ref nwstream)))
{
WriteToStream(ref nwstream, Convert.ToBase64String(
Encoding.ASCII.GetBytes(this.username.ToCharArray())) + "\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.SERVER_CHALLENGE);
WriteToStream(ref nwstream, Convert.ToBase64String(Encoding.ASCII.GetBytes(
this.password.ToCharArray())) + "\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.AUTH_SUCCESSFUL);
return true;
}
}
return false;
}
總結(jié)
本文介紹了.NET中三種不同的使用SMTP協(xié)議發(fā)送郵件的方法,其中第一種(使用SmtpMail類(lèi))方案能滿足大部分基本的發(fā)送郵件的功能需求,而第二種(使用CDO組件)和第三種(使用Socket自己撰寫(xiě)SMTP類(lèi))方案提供更自由和完整的定制方法,比如他們都能實(shí)現(xiàn)第一種方案不能做到的通過(guò)帶認(rèn)證的SMTP服務(wù)器發(fā)送郵件的功能。
復(fù)制代碼 代碼如下:
public class Mail
{
#region 郵件參數(shù)
static public string accountName = System.Configuration.ConfigurationManager.AppSettings["SmtpAccountName"];
static public string password = System.Configuration.ConfigurationManager.AppSettings["SmtpAccountPW"];
static public string smtpServer = System.Configuration.ConfigurationManager.AppSettings["SmtpServer"];
static public int smtpPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["SmtpPort"]);
#endregion
/// <summary>
/// 郵件發(fā)送方法一
/// </summary>
/// <param name="sendTo"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
static public void SendMail(string sendTo, string subject, string body)
{
//.net smtp
System.Web.Mail.MailMessage mailmsg = new System.Web.Mail.MailMessage();
mailmsg.To = sendTo;
//mailmsg.Cc = cc;
mailmsg.Subject = subject;
mailmsg.Body = body;
mailmsg.BodyFormat = MailFormat.Html;
//sender here
mailmsg.From = Mail.accountName;
// certify needed
mailmsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");//1 is to certify
//the user id
mailmsg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendusername",
Mail.accountName);
//the password
mailmsg.Fields.Add(
"http://schemas.microsoft.com/cdo/configuration/sendpassword",
Mail.password);
System.Web.Mail.SmtpMail.SmtpServer = Mail.smtpServer;
System.Web.Mail.SmtpMail.Send(mailmsg);
}
/// <summary>
/// 郵件發(fā)送方法二
/// </summary>
/// <param name="sendTo"></param>
/// <param name="subject"></param>
/// <param name="body"></param>
static public void SendMail2(string sendTo, string subject, string body)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(accountName, sendTo, subject, body);
msg.From = new System.Net.Mail.MailAddress(accountName, "Mail");
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpServer);
msg.IsBodyHtml = true;
client.Credentials = new System.Net.NetworkCredential(accountName, password);
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.Send(msg);
}
}
摘要
本文簡(jiǎn)單介紹了SMTP協(xié)議(RFC2554)發(fā)送郵件的過(guò)程,并討論了在 .NET 中使用SMTP發(fā)送郵件由簡(jiǎn)到繁的三種不同方案、各自可能遇到的問(wèn)題及其解決辦法。
目錄
? .NET的SMTP類(lèi)
? 使用CDO組件發(fā)送郵件
? 使用Socket撰寫(xiě)郵件發(fā)送程序
總結(jié)
簡(jiǎn)介
郵件發(fā)送功能常常是許多.NET應(yīng)用,尤其是帶網(wǎng)絡(luò)功能的應(yīng)用中不可缺少的模塊之一,本文就此介紹了使用.NET的SMTP類(lèi)庫(kù)和另兩種分別通過(guò)CDO(Collaboration Data Objects)及Socket來(lái)實(shí)現(xiàn)發(fā)送郵件功能的方法。
.NET的SMTP類(lèi)
首先,我們來(lái)介紹一下.NET類(lèi)庫(kù)種自帶的SMTP類(lèi)。在.NET中的System.Web.Mail名字空間下,有一個(gè)專(zhuān)門(mén)使用SMTP協(xié)議來(lái)發(fā)送郵件的類(lèi):SmtpMail,它已能滿足最普通的發(fā)送郵件的需求。這個(gè)類(lèi)只有一個(gè)自己的公共函數(shù)--Send()和一個(gè)公共屬性—SmtpServer,如下圖:
您必須通過(guò)SmtpServer屬性來(lái)指定發(fā)送郵件的服務(wù)器的名稱(chēng)(或IP地址),然后再調(diào)用
Send()函數(shù)來(lái)發(fā)送郵件。
代碼示例如下:
(in C#)
復(fù)制代碼 代碼如下:
using System.Web.Mail;
public void sendMail()
{
try
{
System.Web.Mail.MailMessage myMail=new MailMessage();
myMail.From = "myaccount@test.com";
myMail.To = "myaccount@test.com";
myMail.Subject = "MailTest";
myMail.Priority = MailPriority.Low;
myMail.BodyFormat = MailFormat.Text;
myMail.Body = "Test";
SmtpMail.SmtpServer="smarthost"; //your smtp server here
SmtpMail.Send(myMail);
}
catch(Exception e)
{
throw e;
}
}
您可以在Send函數(shù)的參數(shù)MailMessage對(duì)象中設(shè)置郵件的相關(guān)屬性,如優(yōu)先級(jí)、附件等等。除了以MailMessage對(duì)象為參數(shù)(如上述代碼),Send函數(shù)還可以簡(jiǎn)單的直接以郵件的4個(gè)主要信息(from,to,subject,messageText)作為字符串參數(shù)來(lái)調(diào)用。
使用CDO組件發(fā)送郵件
CDO是Collaboration Data Objects的簡(jiǎn)稱(chēng),它是一組高層的COM對(duì)象集合,并經(jīng)歷了好幾個(gè)版本的演化,現(xiàn)在在Windows2000和Exchange2000中使用的都是CDO2.0的版本(分別為cdosys.dll和cdoex.dll)。CDOSYS構(gòu)建在SMTP協(xié)議和NNTP協(xié)議之上,并且作為Windows2000 Server的組件被安裝,您可以在系統(tǒng)目錄(如c:\winnt或c:\windows)的system32子目錄中找到它(cdosys.dll)。
CDO組件相對(duì)于先前介紹的SmtpMail對(duì)象功能更為豐富,并提供了一些SmtpMail類(lèi)所沒(méi)有提供的功能,如通過(guò)需要認(rèn)證的SMTP服務(wù)器發(fā)送郵件等。
下面一段代碼就展示了如何使用CDO組件通過(guò)需要認(rèn)證的SMTP服務(wù)器發(fā)送郵件的過(guò)程:
(in C#)
復(fù)制代碼 代碼如下:
public void CDOsendMail()
{
try
{
CDO.Message oMsg = new CDO.Message();
oMsg.From = "myaccount@test.com";
oMsg.To = "myaccount@test.com";
oMsg.Subject = "MailTest";
oMsg.HTMLBody = "<html><body>Test</body></html>";
CDO.IConfiguration iConfg = oMsg.Configuration;
ADODB.Fields oFields = iConfg.Fields;
oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value=2;
oFields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value="myaccount@test.com"; //sender mail oFields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value="myaccount@test.com"; //email account oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value="username"; oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value="password"; oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value=1;
//value=0 代表Anonymous驗(yàn)證方式(不需要驗(yàn)證)
//value=1 代表Basic驗(yàn)證方式(使用basic (clear-text) authentication.
//The configuration sendusername/sendpassword or postusername/postpassword fields are used to specify credentials.)
//Value=2 代表NTLM驗(yàn)證方式(Secure Password Authentication in Microsoft Outlook Express)
oFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value=0x0804;
oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value="smtp.21cn.com";
oFields.Update();
oMsg.BodyPart.Charset="gb2312";
oMsg.HTMLBodyPart.Charset="gb2312";
oMsg.Send();
oMsg = null;
}
catch (Exception e)
{
throw e;
}
}
注意:由于Exchange2000的CDO組件cdoex.dll會(huì)更新原有的Windows2000的CDO組件cdosys.dll,所以如果您希望繼續(xù)使用cdosys.dll,您必須先通過(guò)regsrv32.exe卸載掉cdoex.dll。
使用Socket撰寫(xiě)郵件發(fā)送程序
當(dāng)然,如果您覺(jué)得SmtpMail不能滿足您的需求,CDO又不夠直截了當(dāng),那就只能自己動(dòng)手了;其實(shí)如果您很熟悉Socket編程,自己寫(xiě)一個(gè)發(fā)送郵件的程序并不很難,以下就是一個(gè)例子。
首先,我們簡(jiǎn)單介紹一下帶驗(yàn)證的SMTP服務(wù)器如何使用AUTH原語(yǔ)進(jìn)行身份驗(yàn)證,其詳細(xì)的定義可以參考RFC2554。
具體如下:
1)首先,需要使用EHLO而不是原先的HELO。
2)EHLO成功以后,客戶端需要發(fā)送AUTH原語(yǔ),與服務(wù)器就認(rèn)證時(shí)用戶名和密碼的傳遞方式進(jìn)行協(xié)商。
3)如果協(xié)商成功,服務(wù)器會(huì)返回以3開(kāi)頭的結(jié)果碼,這是就可以把用戶名和密碼傳給服務(wù)器。
4)最后,如果驗(yàn)證成功,就可以開(kāi)始發(fā)信了。
下面是一個(gè)實(shí)際的例子,客戶端在WinXP的Command窗口中通過(guò)“telnet smtp.263.NET 25="命令連接到263的smtp服務(wù)器發(fā)信:
220 Welcome to coremail System(With Anti-Spam) 2.1
EHLO 263.NET
250-192.168.30.29
250-PIPELINING
250-SIZE 10240000
250-ETRN
250-AUTH LOGIN
250 8BITMIME
AUTH LOGIN
334 VXNlcm5hbWU6
bXlhY2NvdW50
334 UGFzc3dvcmQ6
bXlwYXNzd29yZA==
235 Authentication successful
MAIL FROM:myaccount@263.NET
250 Ok
RCPT TO:myaccount@263.NET
250 Ok
Data
354 End data with <CR><LF>.<CR><LF>
This is a testing email.
haha.
.
250 Ok: queued as AC5291D6406C4
QUIT
221 Bye
上面的內(nèi)容就是發(fā)信的全過(guò)程。其中與身份驗(yàn)證有關(guān)的主要是第九到第十四行:
AUTH LOGIN ';';';';客戶端輸入
334 VXNlcm5hbWU6 ';';';';服務(wù)器提示“Username:="
bXlhY2NvdW50 ';';';';客戶端輸入“myaccount="的Base64編碼
334 UGFzc3dvcmQ6 ';';';';服務(wù)器提示“Password:="
bXlwYXNzd29yZA== ';';';';客戶端輸入“mypassword="的Base64編碼
235 Authentication successful ';';';';服務(wù)器端通過(guò)驗(yàn)證
從上面的分析可以看出,在這個(gè)身份驗(yàn)證過(guò)程中,服務(wù)器和客戶端都直接通過(guò)Socket傳遞經(jīng)過(guò)標(biāo)準(zhǔn)Base64編碼的純文本。這個(gè)過(guò)程可以非常方便的用C#實(shí)現(xiàn),或者直接添加到原有的源代碼中。
另外,有些ESMTP服務(wù)器不支持AUTH LOGIN方式的認(rèn)證,只支持AUTH CRAM-MD5方式驗(yàn)證。但是這兩者之間的區(qū)別只是文本的編碼方式不同。
實(shí)現(xiàn)此功能的源代碼可以在SourceForge.NET http://sourceforge.NET/projects/opensmtp-net/ 上找到下載。下面給出了一個(gè)簡(jiǎn)單的偽碼:
復(fù)制代碼 代碼如下:
public void SendMail(MailMessage msg)
{
NetworkStream nwstream = GetConnection();
WriteToStream(ref nwstream, "EHLO " + smtpHost + "\r\n");
string welcomeMsg = ReadFromStream(ref nwstream);
// implement HELO command if EHLO is unrecognized.
if (IsUnknownCommand(welcomeMsg))
{
WriteToStream(ref nwstream, "HELO " + smtpHost + "\r\n");
}
CheckForError(welcomeMsg, ReplyConstants.OK);
// Authentication is used if the u/p are supplied
AuthLogin(ref nwstream);
WriteToStream(ref nwstream, "MAIL FROM: <" + msg.From.Address + ">\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.OK);
SendRecipientList(ref nwstream, msg.To);
SendRecipientList(ref nwstream, msg.CC);
SendRecipientList(ref nwstream, msg.BCC);
WriteToStream(ref nwstream, "DATA\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.START_INPUT);
if (msg.ReplyTo.Name != null && msg.ReplyTo.Name.Length != 0)
{ WriteToStream(ref nwstream, "Reply-To: \"" + msg.ReplyTo.Name + "\" <" +
msg.ReplyTo.Address + ">\r\n"); }
else
{ WriteToStream(ref nwstream, "Reply-To: <" + msg.ReplyTo.Address + ">\r\n"); }
if (msg.From.Name != null && msg.From.Name.Length != 0)
{ WriteToStream(ref nwstream, "From: \"" + msg.From.Name + "\" <" +
msg.From.Address + ">\r\n"); }
else
{ WriteToStream(ref nwstream, "From: <" + msg.From.Address + ">\r\n"); }
WriteToStream(ref nwstream, "To: " + CreateAddressList(msg.To) + "\r\n");
if (msg.CC.Count != 0)
{ WriteToStream(ref nwstream, "CC: " + CreateAddressList(msg.CC) + "\r\n"); }
WriteToStream(ref nwstream, "Subject: " + msg.Subject + "\r\n");
if (msg.Priority != null)
{ WriteToStream(ref nwstream, "X-Priority: " + msg.Priority + "\r\n"); }
if (msg.Headers.Count > 0)
{
SendHeaders(ref nwstream, msg);
}
if (msg.Attachments.Count > 0 || msg.HtmlBody != null)
{
SendMessageBody(ref nwstream, msg);
}
else
{
WriteToStream(ref nwstream, msg.Body + "\r\n");
}
WriteToStream(ref nwstream, "\r\n.\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.OK);
WriteToStream(ref nwstream, "QUIT\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.QUIT);
CloseConnection();
}
private bool AuthLogin(ref NetworkStream nwstream)
{
if (username != null && username.Length > 0 && password != null && password.Length > 0)
{
WriteToStream(ref nwstream, "AUTH LOGIN\r\n");
if (AuthImplemented(ReadFromStream(ref nwstream)))
{
WriteToStream(ref nwstream, Convert.ToBase64String(
Encoding.ASCII.GetBytes(this.username.ToCharArray())) + "\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.SERVER_CHALLENGE);
WriteToStream(ref nwstream, Convert.ToBase64String(Encoding.ASCII.GetBytes(
this.password.ToCharArray())) + "\r\n");
CheckForError(ReadFromStream(ref nwstream), ReplyConstants.AUTH_SUCCESSFUL);
return true;
}
}
return false;
}
總結(jié)
本文介紹了.NET中三種不同的使用SMTP協(xié)議發(fā)送郵件的方法,其中第一種(使用SmtpMail類(lèi))方案能滿足大部分基本的發(fā)送郵件的功能需求,而第二種(使用CDO組件)和第三種(使用Socket自己撰寫(xiě)SMTP類(lèi))方案提供更自由和完整的定制方法,比如他們都能實(shí)現(xiàn)第一種方案不能做到的通過(guò)帶認(rèn)證的SMTP服務(wù)器發(fā)送郵件的功能。
您可能感興趣的文章:
- Asp.net發(fā)送郵件的兩種方法小結(jié)
- asp.net2.0實(shí)現(xiàn)郵件發(fā)送(測(cè)試成功)
- asp.net System.Net.Mail 發(fā)送郵件
- 在ASP.NET2.0中通過(guò)Gmail發(fā)送郵件的代碼
- Asp.Net類(lèi)庫(kù)中發(fā)送電子郵件的代碼
- asp.net mvc發(fā)送郵件實(shí)例講解
- 用ASP.NET做的個(gè)性化的郵件發(fā)送系統(tǒng)
- asp.net發(fā)送郵件實(shí)現(xiàn)方法
- ASP.NET郵件發(fā)送system.Net.Mail案例
- .NET發(fā)送郵件的實(shí)現(xiàn)方法示例
相關(guān)文章
asp.net利用后臺(tái)實(shí)現(xiàn)直接生成html分頁(yè)的方法
這篇文章主要介紹了asp.net利用后臺(tái)實(shí)現(xiàn)直接生成html分頁(yè)的方法,比較簡(jiǎn)潔實(shí)用,需要的朋友可以參考下2014-08-08
ASP.NET MVC下基于異常處理的完整解決方案總結(jié)
ASP.NET MVC是一個(gè)極具可擴(kuò)展開(kāi)發(fā)框架,在這篇文章中我將通過(guò)它的擴(kuò)展實(shí)現(xiàn)與EntLib的集成,并提供一個(gè)完整的解決異常處理解決方案。2017-01-01
.Net Core3.0 配置Configuration的實(shí)現(xiàn)
這篇文章主要介紹了.Net Core3.0 配置Configuration的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
asp.net上傳Excel文件并讀取數(shù)據(jù)的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于asp.net上傳Excel文件并讀取數(shù)據(jù)的實(shí)現(xiàn)方法,文中通過(guò)示例代碼以及圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
ASP.NET沒(méi)有魔法_ASP.NET MVC 模型驗(yàn)證方法
下面小編就為大家分享一篇ASP.NET沒(méi)有魔法_ASP.NET MVC 模型驗(yàn)證方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-02-02
asp.net Cookie值中文亂碼問(wèn)題解決方法
cookie里面不能寫(xiě)中文,是由于cookie先天的編碼方式造成的,所以有必要存在一種中間的編碼方式:URLEncode是最好的選擇,感興趣的你可千萬(wàn)不要錯(cuò)過(guò)了哈,或許本文提供的知識(shí)點(diǎn)對(duì)你學(xué)習(xí)cookie有所幫助2013-02-02

