有時我們需要在網站中加入發送郵件的功能
實現發送郵件功能
首先說一下在
/// <summary>
/// 郵件通知服務類
/// </summary>
public class EmailNotificationService {
/// <summary>
/// 構造一個郵件通知服務類的實例
/// </summary>
/// <param name=
/// <param name=
/// <param name=
/// <param name=
/// <param name=
public EmailNotificationService(
string smtpService
bool enableSSL
int port
string loginName
string password) {
this
this
this
this
this
}
private readonly string m_smtpService;
private readonly string m_loginName;
private readonly string m_password;
private readonly bool m_enableSSL;
private readonly int m_port;
/// <summary>
/// 發送郵件通知到指定的EMAIL地址
/// </summary>
/// <param name=
/// <param name=
/// <param name=
/// <param name=
public void SendTo(string senderName
MailMessage mail = new MailMessage();
mail
mail
mail
mail
mail
mail
mail
SmtpClient smtp = new SmtpClient();
smtp
smtp
smtp
smtp
smtp
}
}
在使用時
EmailNotificationService mailNotificationService = new EmailNotificationService(
mailNotificationService
發送郵件實現方案
上面創建好了一個負責發送郵件的類
SmtpClient還有一個SendAsync方法
由於ASP
實現發送郵件功能
基本的構思已經確定好了
/// <summary>
/// 封裝發送郵件時所需信息的類
/// </summary>
public class MailNotifyInfo {
/// <summary>
/// 獲取或設置稿件的標題
/// </summary>
public string Title {
get;
set;
}
/// <summary>
/// 獲取或設置稿件的作者名稱
/// </summary>
public string Author {
get;
set;
}
/// <summary>
/// 獲取或設置作者的電子郵件地址
/// </summary>
public string EmailAddress {
get;
set;
}
/// <summary>
/// 獲取或設置稿件的狀態
/// </summary>
public ArticleStatus ArticleStatus {
get;
set;
}
}
然後是全局對象類的定義
/// <summary>
/// 處理郵件發送功能的類
/// </summary>
public class NotificationHandler {
/// <summary>
/// 該類的靜態實例
/// </summary>
private static readonly NotificationHandler g_instance = new NotificationHandler();
/// <summary>
/// 獲取該類的唯一實例
/// </summary>
public static NotificationHandler Instance {
get {
return g_instance;
}
}
/// <summary>
/// 默認構造方法
/// </summary>
private NotificationHandler() {
this
this
this
this
this
}
private readonly LinkedList<MailNotifyInfo> m_mailNotifyInfos;
private readonly Thread m_workThread;
private readonly ManualResetEvent m_threadEvent;
private readonly Object m_lockObject;
/// <summary>
/// 添加待發送郵件的相關信息
/// </summary>
public void AppendNotification(MailNotifyInfo mailNotifyInfo) {
lock (this
this
if (this
this
}
}
}
/// <summary>
/// 發送郵件線程的執行方法
/// </summary>
private void ThreadStart() {
while (true) {
this
MailNotifyInfo mailNotifyInfo = this
EmailNotificationService mailNotificationService = new EmailNotificationService(
mailNotificationService
mailNotifyInfo
String
lock (this
this
if (this
this
}
}
}
}
該類比較簡單
當外部調用AppendNotification方法時
發送郵件線程喚醒後進入一個死循環
至此
MailNotifyInfo mailNotifyInfo = new MailNotifyInfo();
NotificationHandler
這只是一個很粗陋的框架
From:http://tw.wingwit.com/Article/program/net/201311/11381.html