本文實例講述了asp.net發送郵件的實現方法。分享給大家供大家參考。具體實現方法如下:
復制代碼 代碼如下:
MailMessage mailMsg = new MailMessage();
//設置收件人的郵件地址
mailMsg.To = "[email protected] ";
//設置發送者的郵件地址
mailMsg.From = "[email protected] ";
//設置郵件主題
mailMsg.Subject = "測試 ";
//設置郵件內容
mailMsg.Body = "內容 ";
mailMsg.BodyFormat = MailFormat.Text;
mailMsg.Priority = MailPriority.Normal;
try
{
//設置發送郵件服務器
SmtpMail.SmtpServer = "localhost";
//發送郵件
SmtpMail.Send(mailMsg);
}
catch
{
}
//一款完整發送郵件代碼
MailObj _mail = new MailObj();
_mail.sendMail("[email protected]", "測試", "<b>內容</b>");
_mail.Dispose();
//核心代碼
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Net.Mail;
using System.Text;
namespace EC
{
/// <summary>
///郵件發送
/// </summary>
public class MailObj
{
private string _strHost = string.Empty;
private string _strAccount = string.Empty;
private string _strPwd = string.Empty;
private string _strFrom = string.Empty;
#region 構造與析構函數
public MailObj()
{
_strHost = "smtp.163.com"; //STMP服務器地址
_strAccount = "aa"; //SMTP服務帳號
_strPwd = "123456"; //SMTP服務密碼
_strFrom = "[email protected]"; //發送方郵件地址
}
/// <summary>
/// 發送郵件購造函數
/// </summary>
/// <param name="strHost">STMP服務器地址:smtp.163.com</param>
/// <param name="strAccount">SMTP服務帳號:liugongxun</param>
/// <param name="strPwd">SMTP服務密碼:123456</param>
/// <param name="strFrom">發送方郵件地址:[email protected]</param>
public MailObj(string strHost, string strAccount, string strPwd, string strFrom)
{
_strHost = strHost;
_strAccount = strAccount;
_strPwd = strPwd;
_strFrom = strFrom;
}
~MailObj()
{
Dispose();
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
#endregion
#region 發送郵件
public bool sendMail(string to, string title, string content)
{
SmtpClient _smtpClient = new SmtpClient();
_smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定電子郵件發送方式
_smtpClient.Host = _strHost;//指定SMTP服務器
_smtpClient.Credentials = new System.Net.NetworkCredential(_strAccount, _strPwd);//用戶名和密碼
MailMessage _mailMessage = new MailMessage(_strFrom, to);
_mailMessage.Subject = title;//主題
_mailMessage.Body = content;//內容
_mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文編碼
_mailMessage.IsBodyHtml = true;//設置為HTML格式
_mailMessage.Priority = MailPriority.High;//優先級
try
{
_smtpClient.Send(_mailMessage);
return true;
}
catch
{
return false;
}
}
#endregion
}
}
希望本文所述對大家的asp.net程序設計有所幫助。