[源碼下載]
在asp.net 2.0中發送郵件
作者:webabcd
1、在web.config中的<configuration>內加入如下配置資訊(host—smtp服務地址;port—連接埠號碼;userName—使用者名稱;password—密碼。請自行修改)。
<system.net>
<mailSettings>
<smtp>
<network host="smtpserver" port="25" userName="uid" password="pwd" />
</smtp>
</mailSettings>
</system.net>
2、aspx頁面HTML代碼 <table border="0">
<tr>
<td>
寄件者
</td>
<td>
<asp:TextBox runat="server" ID="emailfrom"></asp:TextBox>
</td>
</tr>
<tr>
<td>
收件者
</td>
<td>
<asp:TextBox runat="server" ID="emailto"></asp:TextBox>
</td>
</tr>
<tr>
<td>
主題
</td>
<td>
<asp:TextBox runat="server" ID="subject"></asp:TextBox>
</td>
</tr>
<tr>
<td>
附件
</td>
<td>
<asp:FileUpload ID="attachment" runat="server" />
</td>
</tr>
<tr>
<td>
內容
</td>
<td>
<asp:TextBox runat="server" ID="body" TextMode="MultiLine" Columns="50" Rows="10"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button runat="server" ID="btnSend" Text="發送" OnClick="btnSend_Click" />
</td>
</tr>
</table>
3、執行個體化一個MailMessage並設定其屬性 MailMessage mm = new MailMessage(emailfrom.Text, emailto.Text);
mm.Subject = subject.Text;
mm.Body = body.Text;
// HTML格式
mm.IsBodyHtml = true;
// 添加附件
mm.Attachments.Add(new Attachment(attachment.PostedFile.InputStream, attachment.FileName));
/**//*其他如抄送、優先順序之類的都可以在MailMessage類的屬性中設定*/
4、執行個體化一個SmtpClient,調用其Send方法,參數為MailMessage對象 SmtpClient sc = new SmtpClient();
// 編程方式設定smtp(不用web.config)
// sc.Host = "";
// sc.Port = 25;
// sc.Credentials = new NetworkCredential("username", "password");
try
{
sc.Send(mm);
Response.Write("ok");
}
catch (Exception ex)
{
// 與smtp相關的錯誤
if (ex is SmtpException)
{
// ex.ToString();
Response.Write("smtp發信失敗");
}
else
{
Response.Write(ex.ToString());
}
}
OK
[源碼下載]