在Asp.Net中使用SmtpMail發送郵件的方法:執行個體

來源:互聯網
上載者:User

.NET裡,發送郵件的功能已經封裝進.NET Framework的System.Web.Mail的命名空間裡了,使用這個命名空間下類,就可以很容易的構建一個發送郵件的程式,所需要僅僅是在windows中架構好SMTP伺服器。

  System.Web.Mail命名空間。這個命名控制項下包含了以下的對象和三個屬性:  
  包含的對象:

  MailAttachment:與郵件附件有關的對象類
  MailMessage :郵件主體
  SmtpMail :負責發送郵件的SMTP協議。

  屬性列表:

  MailEncoding :郵件的編碼(Base64,UUEncode)
  MailFormat :郵件的格式(Html超文字格式設定,Text純文字格式)
  MailPriority :郵件優先順序(High, Medium, Low)

  構建MailMessage對象:
  
  MailMessage對象是郵件的承載主體,通常可以先構建好MailMessage對象,然後設定它的屬性的方式來

  構建郵件程式,下面列出了的是一些常用的屬性:

  Attachments :郵件附件
  Bcc :暗送地址
  Body :郵件主體
  BodyFormat :郵件格式(html,text)
  Cc :抄送地址
  From :發信人地址
  Priority :郵件優先順序(High, Medium,Low)
  Subject :郵件主題
  To :接收人地址
  UrlContentBase :在HTML格式郵件中的URL編碼方式
  UrlContentLocation:郵件資訊的優先順序(High, Medium,Low)

  使用SMTPMail發送郵件
  
  構建好MailMessage對象之後,還需要使用另外一個對象-SMTPMail-來發送郵件,SMTPMAIL有一個很

  重要的方法:Send,該方法有兩個不同用法,其中一個可以僅僅發送整個的MailMessage對象:
  SmtpMail.Send(myEmailObject);

  另外一個允許你分別指定寄件者,收郵件地址,郵件主題,郵件主題,然後再發送出去:

  SmtpMail.Send(strFrom, strTo, strSubject, strBody);
現在,讓我們來看看一個完整的例子,在這個例子中,我先建立一個MailMessage對象,然後設定部分屬性,最後使用SmtpMail對象把它發送出去:

<%@ Page Language="C#" %>
<script language="C#" runat="server">


void Page_Load()
{
    // CREATE A MAIL MESSAGE
    System.Web.Mail.MailMessage myEmail = new System.Web.Mail.MailMessage();


    // SET MESSAGE PARAMETERS
    myEmail.From = "agent@mypersonalshoppers.com";
    myEmail.To = "john@johnsmith.com";
    myEmail.Subject = "Product Availability Notice";
    myEmail.BodyFormat = System.Web.Mail.MailFormat.Html;
    myEmail.Body = "The sunglasses you expressed interest in are now in stock.";


    //SEND THE MESSAGE
    System.Web.Mail.SmtpMail.Send(myEmail);


    //UPDATE STATUS
    lblMailStatus.Text = "Mail successfully sent.";
}


</script>


<html>
<body>


<asp:Label id="lblMailStatus" runat="server" />


</body>
</html>
<%@ Page Language="VB" %>


<script language="VB" runat="server">


Sub Page_Load()
    'CREATE A MAIL MESSAGE
    Dim myEmail as System.Web.Mail.MailMessage = new System.Web.Mail.MailMessage()


    'SET MESSAGE PARAMETERS
    myEmail.From = "agent@mypersonalshoppers.com"
    myEmail.To = "john@johnsmith.com"
    myEmail.Subject = "Product Availability Notice"
    myEmail.BodyFormat = System.Web.Mail.MailFormat.Html
    myEmail.Body = "The sunglasses you expressed interest in are now in stock."


    'SEND THE MESSAGE
    System.Web.Mail.SmtpMail.Send(myEmail)


    'UPDATE STATUS
    lblMailStatus.Text = "Mail successfully sent."
End Sub


</script>


<html>
<body>
    <asp:Label id="lblMailStatus" runat="server" />
</body>
</html>

 

 二.....................

在ASP中,就可以通過調用CDONTS組件發送簡單郵件,在ASP.Net中,自然也可以。不同的是,.Net Framework中,將這一組件封裝到了System.Web.Mail命名空間中。


一個典型的郵件發送程式如下:
<%@ Import Namespace="System.Web.Mail" %>
<script runat="server">
MailMessage mail=new MailMessage();
 mail.From="service@brookes.com";
 mail.To="brookes@brookes..com";
 mail.BodyFormat=MailFormat.Text;
 mail.Body="a test smtp mail.";
 mail.Subject="r u ok?";
 SmtpMail.SmtpServer="localhost";
 SmtpMail.Send(mail);
</script>


通常情況下,系統調用IIS內建的預設SMTP虛擬伺服器就可以實現郵件的發送。但是也經常會遇到這樣的錯誤提示:

The server rejected one or more recipient addresses. The server response was: 550 5.7.1 Unable to relay for brookes@brookes.com

 產生這個錯誤的原因除了地址錯誤的可能外,還有一個重要原因。如上文提到的,IIS並不帶有真正的郵件功能,只是借用一個“SMTP虛擬伺服器”實現郵件的轉寄。在MSDN中,有如下提示:

如果本地 SMTP 伺服器(包括在 Windows 2000 和 Windows Server 2003 中)位於阻塞任何直接 SMTP 通訊量(通過連接埠 25)的防火牆之後,則需要尋找網路上是否有可用的智慧主機能用來中轉寄往 Internet 的 SMTP 訊息。
智慧主機是一個 SMTP 伺服器,它能夠中轉從內部 SMTP 伺服器直接發送到 Internet 的外出電子郵件。智慧主機應能同時串連到內部網路和網際網路,以用作電子郵件網關。

開啟預設SMTP虛擬伺服器-屬性-訪問-中繼限制,可以看到,這種轉寄或者中繼功能受到了限制。在限制列表中,添加需要使用此伺服器的主機的IP地址,就可以解決上文提到的問題。

如果不使用IIS內建的SMTP虛擬伺服器而使用其他真正的郵件伺服器,如IMail,Exchange等,常常遇到伺服器需要寄送者身分識別驗證的問題(ESMTP)。在使用需要驗證寄送者身份的伺服器時,會出現錯誤:

The server rejected one or more recipient addresses. The server response was: 550 not local host ckocoo.com, not a gateway

以前在ASP中,遇到這種問題沒有什麼解決的可能,只能直接使用CDO組件(CDONTS的父級組件):
 conf.Fields[CdoConfiguration.cdoSMTPAuthenticate].Value=CdoProtocolsAuthentication.cdoBasic;
 conf.Fields[CdoConfiguration.cdoSendUserName].Value="brookes";
 conf.Fields[CdoConfiguration.cdoSendPassword].Value="XXXXXXX";

在.Net Framework 1.1中,顯然對這一需求有了考慮,在MailMessage組件中增加了Fields集合易增加ESMTP郵件伺服器中的寄送者身分識別驗證的問題。不過,這一方法僅適用於.Net Framework 1.1,不適用於.Net Framework 1.0版本。帶有寄送者身分識別驗證的郵件發送程式如下:


<%@ Import Namespace="System.Web.Mail" %>
<script runat="server">
MailMessage mail=new MailMessage();
 mail.From="service@brookes.com";
 mail.To="brookes@brookes.com";
 mail.BodyFormat=MailFormat.Text;
 mail.Body="a test smtp mail.";
 mail.Subject="r u ok?";
 mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1"); //basic authentication
 mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "brookes"); //set your username here
 mail.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "walkor"); //set your password here
 SmtpMail.SmtpServer="lsg.moon.net";
 SmtpMail.Send(mail);
</script>


有了這種方法,終於可以不必再藉助於Jmail、EasyMail等第三方組件,而只簡單使用SmtpMai就可以l完成郵件的發送了。

 三,,,,,,,,,,,,,,,,

<%@Import Namespace="System.Web.Mail" %> 
   <script language="C#" runat="server"> 
   void sendButton_Click(Object sender,EventArgs e)  
   {  
    MailMessage mailObj = new MailMessage(); 
    string strFileName;
      strFileName="";
   if (EmailFrom.Text!="")
      {
          mailObj.From = EmailFrom.Text; 
      }
   
   if (EmailTo.Text!="")
   {
        mailObj.To = EmailTo.Text ;
   }
  
   if (EmailCc.Text!="")
   {
       mailObj.Cc = EmailCc.Text ;
   }
  
   if (EmailBcc.Text!="")
   {
       mailObj.Bcc = EmailBcc.Text ;
       mailObj.BodyFormat = MailFormat.Text ;
       mailObj.Priority = MailPriority.Normal ;
       mailObj.Subject = EmailSubject.Text ;
       mailObj.Body = EmailBody.Text ;    
       strFileName=Emailfile.PostedFile.FileName;
    } 
   if (strFileName!="")
   {
       mailObj.Attachments.Add(new MailAttachment(strFileName)); 
       SmtpMail.SmtpServer = ""; 
   SmtpMail.Send(mailObj) ;
   panelSendEmail.Visible = false ;
   panelMailSent.Visible = true ;
   }
   }
   </script>
   <html> 
   <body> 
   <asp:panel id="panelSendEmail" runat="server"> 
   <form Method="Post" EncType="Multipart/Form-Data" runat="server"> 
   <h2>歡迎用ASP.NET來發送E-mail</h2> 
   <b>請輸入郵件發送地址:</b> 
   <asp:Textbox id="EmailFrom" size="30" runat="server" /> 
   <p> 
   <b>請輸入郵件目的地址:</b> 
   <asp:Textbox id="EmailTo" size="30" runat="server" /> 
   <p> 
   <b>請輸入郵件抄送地址:</b> 
   <asp:Textbox id="EmailCc" size="30" runat="server" /> 
   <p> 
   <b>請輸入郵件密送地址:</b> 
   <asp:Textbox id="EmailBcc" size="30" runat="server" /> 
   <p> 
   <b>請輸入郵件主題:</b> 
   <asp:Textbox id="EmailSubject" size="30" runat="server" /> 
   <p> 
   <b>請輸入郵件主體:</b> 
   <asp:Textbox id="EmailBody" TextMode="MultiLine" 
         Columns="40" Rows="10" runat="server" /> 
   <p> 
   <b>請加入附件名稱:</b> 
   <input id="Emailfile" type="file" runat="server" size="40" /> 
   <asp:button runat="server" id="sendButton" Text="發送" 
         OnClick="sendButton_Click" /> 
   </form> 
   </asp:panel> 
   <asp:panel id="panelMailSent" runat="server" Visible="False"> 
   您的郵件已經成功發送,歡迎您的再次使用。 
   </asp:panel> 
   </body> 
   </html> 

 

四.using System.Web.Mail;
2)
  MailMessage mail  =   new  MailMessage();
       mail.To  =   " me@mycompany.com " ;
       mail.From  =   " you@yourcompany.com " ;
       mail.Subject  =   " this is a test email. " ;
       mail.Body  =   " Some text goes here " ;
          mail.BodyFormat = MailFormat.Html;//設定為HTML格式 
         //設定為需要使用者驗證
      mail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/smtpauthenticate ",  " 1 " );   
         //設定驗證使用者名稱(把my_username_here改為你的驗證使用者名稱)
      mail.Fields.Add(" http://schemas.microsoft.com/cdo/configuration/sendusername" ,  " my_username_here " ); 
         //設定驗證密碼(把password改為你的驗證密碼)
      mail.Fields.Add( " http://schemas.microsoft.com/cdo/configuration/sendpassword " ,  "password " ); 
      SmtpMail.SmtpServer  =   " mail.mycompany.com " ;   // 郵件伺服器地址
      SmtpMail.Send( mail );

五.................

本文舉例說明在ASP.NET中發送Email的眾多可能性,內容覆蓋了諸如Email格式、優先權、附件及Email編碼等方面。

ASP.NET被賦予了一個發送Email的新對象,名為SmtpMail。使用SmtpMail對象從ASP.NET頁面中發送Email時,可以遵循以下簡單步驟:

▲包含與郵件有關類所需要的名稱空間;
▲例示一個資訊對象,設定屬性;
▲使用SmtpMail對象執行個體的send方法發送郵件。

現在我們就來一步一步地研究從一個ASP.NET頁面發送Email的過程。我們使用了VB來說明這個例子,最後將包含VB和C#的完整代碼。

第一步:包含名稱空間

在ASP.NET 頁面中引入System.Web.Util 名稱空間,這個名稱空間中包括了發送一個email所必須的所有對象。這些對象是:

SmtpMail:代表郵件系統,用於發送email。
MailMessage:代表一個資訊,其屬性包括髮件人地址、收件者地址等。
MailFormat:代表資訊的格式:HTML、文本等。
MailAttachment:代表一個email附件。
MailEncoding enum:代表Base64 或Uuencode的任何編碼。取值範圍:Base64、UUencode
MailPriority enum:用來為資訊設定優先權。值為:高、低、一般。
<% @Import Namespace = "System.Web.Util" %>

第二步:例示 MailMessage 對象

使用以下語句來例示MailMessage對象:

Dim mailObj AS new MailMessage

用MailMessage對象的屬性來準備郵件。MailMessage對象有下列屬性:

From:寄件者的Email地址
To:收件者的Email地址
Subject:email的主題
Body:email的主體
CC:email抄送的收件者清單
BCC:email暗送的收件者清單
Priority:資訊的優先權:高、低或一般
BodyEncoding:資訊體的編碼,如果有的話,就是Base64或UUencode
BodyFormat:資訊的格式:Html 或text
Attachments:附加到email 的MailAttachment對象列表,主要就是對這個對象集合的一個引用

下面這段代碼示範了使用MailMessage 對象屬性的方法,它們代表了將在本例中建立的一個資訊,這個資訊要用SmtpMail對象來發送。在例子中,mailObj引用了資訊對象的例示:

mailObj.From = "abc@mydomain.com"
mailObj.To = Request.Form ("to")
mailObj.Subject = "subject of the mail"
mailObj.Body = "Message of the mail"

第三步:發送Email

這時,我們就可以使用SmtpMail 對象的Send方法來發送郵件了:

SmtpMail.Send(mailObj)

完整執行個體

最後,我們把以上解釋的屬性結合在一個完整的例子中。為了說明用ASP.NET 發送一個email 的全部可能性,我們還包含了一些“小技巧”。下面是使用VB.NET的完整例子:

<%@page language="VB" %>
<%@Import Namespace="System.Web.Util" %>
<HTML><BODY>
<SCRIPT LANGUAGE="VB" RUNAT="server">
' This method is called on the server when the submit
' button is clicked on the client and when the page
' posts back to itself
Sub SendMail (Obj As Object, E As EventArgs)
' Instantiate a MailMessage object. This serves as a message object
' on which we can set properties.
Dim mailObj AS new MailMessage
' Set the from and to address on the email
mailObj.From = Request.Form("From")
mailObj.To = Request.Form("To")
mailObj.Subject = "Subject Of the Mail"
mailObj.Body = "Body of the Mail"
' Optional: HTML format for the email
mailObj.BodyFormat = MailFormat.Html
' Optional: Encoding for the message
mailObj.BodyEncoding = MailFormat.Base64
' Optional: Set the priority of the message to high
mailObj.Priority = MailPriority.High
' Optional: Attach a file to the email.
' Note here that we have created a MailAttachment object to
' attach a file to the email
mailObj.Attachments.Add(new MailAttachment("c:/test.doc"))
' Send the email using the SmtpMail object
SmtpMail.Send(mailObj)
End Sub
</SCRIPT>
<asp:label ID="Headingmsg" Text="Enter Your Email Address:" RUNAT="server"/>
<FORM METHOD="post" RUNAT="server">
Email Recipient: <INPUT TYPE="text" NAME="to"> <br>
Email Sender: <INPUT TYPE="text" NAME="from">
<INPUT TYPE="submit" NAME="Submit" VALUE="Send Mail" RUNAT="server" OnServerClick="SendMail">
</FORM>
</BODY>

在以上例子中,From(寄件者)和 To(收件者)的Email地址是從相應的文字框中收集的,點擊“Send Mail”(發送郵件)按鈕時,郵件就被發送出去。當“Send Mail”(發送郵件)按鈕被點擊時,表單回遞到它自己,在伺服器上“SendMail”(發送郵件)程式被觸發,郵件被發送。下面是使用C#的例子:

<%@page language="C#" %>
<%@Import Namespace="System.Web.Util" %>
<HTML><BODY>
<SCRIPT LANGUAGE="C#" RUNAT="server">
// This method is called on the server when the submit
// button is clicked on the client and when the page
// posts back to itself
public void SendMail (Object Obj, EventArgs E)
{
// Instantiate a MailMessage object. This serves as a message object
// on which we can set properties.
MailMessage mailObj = new MailMessage();
// Set the from and to address on the email
mailObj.From = Request.Form("From");
mailObj.To = Request.Form("To");
mailObj.Subject = "Subject Of the Mail";
mailObj.Body = "Body of the Mail";
// Optional: HTML format for the email
mailObj.BodyFormat = MailFormat.Html;
// Optional: Encoding for the message
mailObj.BodyEncoding = MailFormat.Base64;
// Optional: Set the priority of the message to high
mailObj.Priority = MailPriority.High;
// Optional: Attach a file to the email.
// Note here that we have created a MailAttachment object to
// attach a file to the email
mailObj.Attachments.Add(new MailAttachment("c://test.doc"));
// Send the email using the SmtpMail object
SmtpMail.Send(mailObj);
}
</SCRIPT>
<asp:label ID="Headingmsg" Text="Enter Your Email Address:" RUNAT="server"/>
<FORM METHOD="post" RUNAT="server">
Email Recipient: <INPUT TYPE="text" NAME="to"> <br>
Email Sender: <INPUT TYPE="text" NAME="from">
<INPUT TYPE="submit" NAME="Submit" VALUE="Send Mail" RUNAT="server" OnServerClick="SendMail">
</FORM>
</BODY>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.