ASP.net發送Email

來源:互聯網
上載者:User
用socket 來發送email
http://www.z6688.com/info/47187-1.htm
Send mail from ASP.NET using your gmail account

Send & Receive Emails using Winsock and POP3
http://www.developerfusion.co.uk/show/2453/


 
A POP3 Client in C# .NET

Send mail using System.Web.Mail namespace 

POP3 Email Client with full MIME Support (.NET 2.0)

首先,我們來介紹一下.NET類庫種內建的SMTP類。
  在.NET中的System.Web.Mail名字空間下,有一個專門使用SMTP協議來發送郵件的類:SmtpMail,它已能滿足最普通的發送郵件的需求。這個類只有一個自己的公用函數--Send()和一個公用屬性—SmtpServer
您必須通過SmtpServer屬性來指定發送郵件的伺服器的名稱(或IP地址),然後再調用
Send()函數來發送郵件。
程式碼範例如下:
(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函數的參數MailMessage對象中設定郵件的相關屬性,如優先順序、附件等等。除了以MailMessage對象為參數(如上述代碼),Send函數還可以簡單的直接以郵件的4個主要資訊(from,to,subject,messageText)作為字串參數來調用。

第二、使用CDO組件發送郵件
  CDO是Collaboration Data Objects的簡稱,它是一組高層的COM對象集合,並經曆了好幾個版本的演化,現在在Windows2000和Exchange2000中使用的都是CDO2.0的版本(分別為cdosys.dll和cdoex.dll)。CDOSYS構建在SMTP協議和NNTP協議之上,並且作為Windows2000 Server的組件被安裝,您可以在系統目錄(如c:\winnt或c:\windows)的system32子目錄中找到它(cdosys.dll)。
  CDO組件相對於先前介紹的SmtpMail對象功能更為豐富,並提供了一些SmtpMail類所沒有提供的功能,如通過需要認證的SMTP伺服器發送郵件等。
  下面一段代碼就展示了如何使用CDO組件通過需要認證的SMTP伺服器發送郵件的過程:
(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驗證方式(不需要驗證)
//value=1 代表Basic驗證方式(使用basic (clear-text) authentication.
//The configuration sendusername/sendpassword or postusername/postpassword fields are used to specify credentials.)
//Value=2 代表NTLM驗證方式(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會更新原有的Windows2000的CDO組件cdosys.dll,所以如果您希望繼續使用cdosys.dll,您必須先通過regsrv32.exe卸載掉cdoex.dll。

第三、使用Socket撰寫郵件發送程式
  當然,如果您覺得SmtpMail不能滿足您的需求,CDO又不夠直截了當,那就只能自己動手了;其實如果您很熟悉Socket編程,自己寫一個發送郵件的程式並不很難,以下就是一個例子。
首先,我們簡單介紹一下帶驗證的SMTP伺服器如何使用AUTH原語進行身分識別驗證,其詳細的定義可以參考RFC2554。
具體如下:
1)首先,需要使用EHLO而不是原先的HELO。
2)EHLO成功以後,用戶端需要發送AUTH原語,與伺服器就認證時使用者名稱和密碼的傳遞方式進行協商。
3)如果協商成功,伺服器會返回以3開頭的結果碼,這是就可以把使用者名稱和密碼傳給伺服器。
4)最後,如果驗證成功,就可以開始發信了。
下面是一個實際的例子,用戶端在WinXP的Command視窗中通過"telnet smtp.263.NET 25"命令串連到263的smtp伺服器發信:
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

上面的內容就是發信的全過程。其中與身分識別驗證有關的主要是第九到第十四行:
AUTH LOGIN "用戶端輸入
334 VXNlcm5hbWU6 "伺服器提示“Username:="
bXlhY2NvdW50 "用戶端輸入“myaccount="的Base64編碼
334 UGFzc3dvcmQ6 "伺服器提示“Password:="
bXlwYXNzd29yZA== "用戶端輸入“mypassword="的Base64編碼
235 Authentication successful "伺服器端通過驗證
從上面的分析可以看出,在這個身分識別驗證過程中,伺服器和用戶端都直接通過Socket傳遞經過標準Base64編碼的純文字。這個過程可以非常方便的用C#實現,或者直接添加到原有的原始碼中。
另外,有些ESMTP伺服器不支援AUTH LOGIN方式的認證,只支援AUTH CRAM-MD5方式驗證。但是這兩者之間的區別只是文本的編碼方式不同。
實現此功能的原始碼可以在SourceForge.NET http://sourceforge.NET/projects/opensmtp-net/ 上找到下載。下面給出了一個簡單的偽碼:
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;
}
--------------------------------------------------------------------------------
總結
本文介紹了.NET中三種不同的使用SMTP協議發送郵件的方法,其中第一種(使用SmtpMail類)方案能滿足大部分基本的發送郵件的功能需求,而第二種(使用CDO組件)和第三種(使用Socket自己撰寫SMTP類)方案提供更自由和完整的定製方法,比如他們都能實現第一種方案不能做到的通過帶認證的SMTP伺服器發送郵件的功能。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.