C#.NET发EMAIL的几种方法 MailMessage/SmtpClient/CDO.Message

C#.NET发EMAIL的几种方法 MailMessage/SmtpClient/CDO.Message

源代码如下:

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Net.Mail;
using System.Net;

namespace Pub.Class
{
/// <summary>
/// 发送Email类
/// </summary>
public class Email
{
#region 私有成员
private static object lockHelper = new object();
private string _From;
private string _FromEmail;
private string _Subject;
private string _Body;
private string _SmtpServer;
private string _SmtpPort = "25";
private string _SmtpUserName;
private string _SmtpPassword;
private System.Web.Mail.MailFormat _Format = System.Web.Mail.MailFormat.Html;
private System.Text.Encoding _Encoding = System.Text.Encoding.Default;
#endregion

#region 属性
/// <summary>
/// 正文内容类型
/// </summary>
public System.Web.Mail.MailFormat Format { set { _Format = value; } }
/// <summary>
/// 正文内容编码
/// </summary>
public System.Text.Encoding Encoding { set { _Encoding = value; } }
/// <summary>
/// FromEmail 发送方地址(如test@163.com)
/// </summary>
public string FromEmail { set { _FromEmail = value; } }
/// <summary>
/// From
/// </summary>
public string From { set { _From = value; } }
/// <summary>
/// 主题
/// </summary>
public string Subject { set { _Subject = value; } }
/// <summary>
/// 内容
/// </summary>
public string Body { set { _Body = value; } }
/// <summary>
/// SmtpServer
/// </summary>
public string SmtpServer { set { _SmtpServer = value; } }
/// <summary>
/// SmtpPort
/// </summary>
public string SmtpPort { set { _SmtpPort = value; } }
/// <summary>
/// SmtpUserName
/// </summary>
public string SmtpUserName { set { _SmtpUserName = value; } }
/// <summary>
/// SmtpPassword
/// </summary>
public string SmtpPassword { set { _SmtpPassword = value; } }
#endregion

#region 构造器
/// <summary>
/// 构造器
/// </summary>
public Email() { }
#endregion

#region Send
/// <summary>
/// 发送EMAIL
/// </summary>
/// <example>
/// <code>
/// Email _Email = new Email();
/// _Email.FromEmail = "test@163.com";
/// _Email.Subject = "&lt;div>aaaa&lt;/div>";
/// _Email.Body = "aaaaaaaaaaaaa";
/// _Email.SmtpServer = "smtp.163.com";
/// _Email.SmtpUserName = "aaa";
/// _Email.SmtpPassword = "aaa";
/// _Email.Send("test@163.com");
/// </code>
/// </example>
/// <param name="toEmail">收信人 接收方地址</param>
/// <returns>成功否</returns>
public bool SmtpMailSend(string toEmail) {
lock (lockHelper) {
System.Web.Mail.MailMessage msg
= new System.Web.Mail.MailMessage();
try {
msg.From
= _FromEmail;//发送方地址(如test@163.com)
msg.To = toEmail;//接收方地址
msg.BodyFormat = _Format;//正文内容类型
msg.BodyEncoding = _Encoding;//正文内容编码
msg.Subject = _Subject;//主题
msg.Body = _Body;//内容
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");//设置为需要用户验证
if (!_SmtpPort.Equals("25")) msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", _SmtpPort);//设置端口
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", _SmtpUserName);//设置验证用户名
msg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", _SmtpPassword);//设置验证密码
System.Web.Mail.SmtpMail.SmtpServer = _SmtpServer;//邮件服务器地址(如smtp.163.com)
System.Web.Mail.SmtpMail.Send(msg);//发送
return true;
}
catch { } finally {

}
}
return false;
}

/// <summary>
/// 发送EMAIL
/// </summary>
/// <param name="toEmail">Email</param>
/// <returns>是否成功</returns>
public bool CDOMessageSend(string toEmail) {
lock (lockHelper) {
CDO.Message objMail
= new CDO.Message();
try {
objMail.To
= toEmail;
objMail.From
= _FromEmail;
objMail.Subject
= _Subject;
if (_Format.Equals(System.Web.Mail.MailFormat.Html)) objMail.HTMLBody = _Body; else objMail.TextBody = _Body;
//if (!_SmtpPort.Equals("25")) objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = _SmtpPort; //设置端口
objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = _SmtpServer;
objMail.Configuration.Fields[
"http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 1;
objMail.Configuration.Fields[
"http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"].Value = 10;
objMail.Configuration.Fields.Update();
objMail.Send();
return true;
}
catch {} finally{

}
System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail);
objMail
= null;
}
return false;
}
/// <summary>
/// CDOMessageSend
/// </summary>
/// <param name="toEmail"></param>
/// <param name="sendusing"></param>
/// <returns></returns>
public bool CDOMessageSend(string toEmail,int sendusing) {
lock (lockHelper) {
CDO.Message objMail
= new CDO.Message();
try {
objMail.To
= toEmail;
objMail.From
= _FromEmail;
objMail.Subject
= _Subject;
if (_Format.Equals(System.Web.Mail.MailFormat.Html)) objMail.HTMLBody = _Body; else objMail.TextBody = _Body;
if (!_SmtpPort.Equals("25")) objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"].Value = _SmtpPort; //设置端口
objMail.Configuration.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = _SmtpServer;
objMail.Configuration.Fields[
"http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = sendusing;
objMail.Configuration.Fields[
"http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = _FromEmail;
objMail.Configuration.Fields[
"http://schemas.microsoft.com/cdo/configuration/smtpuserreplyemailaddress"].Value = _FromEmail;
objMail.Configuration.Fields[
"http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].Value = _SmtpUserName;
objMail.Configuration.Fields[
"http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = _SmtpUserName;
objMail.Configuration.Fields[
"http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = _SmtpPassword;
objMail.Configuration.Fields[
"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value=1;

objMail.Configuration.Fields.Update();
objMail.Send();
return true;
}
catch { } finally{

}
System.Runtime.InteropServices.Marshal.ReleaseComObject(objMail);
objMail
= null;
}
return false;
}
/// <summary>
/// SmtpClientSend
/// </summary>
/// <param name="toEmail"></param>
/// <returns></returns>
public bool SmtpClientSend(string toEmail) {
lock (lockHelper) {
System.Net.Mail.MailMessage message
= new MailMessage(_FromEmail, toEmail, _Subject, _Body);
message.SubjectEncoding
= _Encoding;
message.BodyEncoding
= _Encoding;
message.IsBodyHtml
= true;
message.Priority
= MailPriority.High;

SmtpClient client
= new SmtpClient(_SmtpServer);
client.UseDefaultCredentials
= false;
client.Credentials
= new NetworkCredential(_SmtpUserName, _SmtpPassword);
client.DeliveryMethod
= SmtpDeliveryMethod.Network;
client.Port
= Str.ToInt(_SmtpPort, 587);
client.EnableSsl
= true;
try {
client.Send(message);
}
catch {
return false;
}
return true;
}
}

#endregion
}
}

 

多线程服务调用:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Collections;
using System.Threading;
using System.Xml;
using System.IO;
using System.Net.Mail;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using Pub.Class;
using System.Diagnostics;

namespace MailService {

[RunInstaller(
true)]
public partial class MService : ServiceBase {
public static bool isRun = false;
public Queue emailQueue = new Queue();
private Thread readEmailThread;
private Thread[] sendEmailThread;
private string[] strList = new string[] { "MailService 启动成功!", "MailService 停止!", "{2} {1} - [{0}] - 发送失败!", "{2} {1} - [{0}] - 发送成功!", "LiveRemotingService 已启动,服务端口6669。", "LiveRemotingService 停止!" };

private struct Config {
public string Conn;
public string LogFile;
public string SmtpServer;
public string UserName;
public string Password;
public string FromAddress;
public int AmountThread;
public int RecordCount;
public int TimeInterval;
}
private Config config = new Config();

public MService() {
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls
= false;
InitializeComponent();

if (!System.Diagnostics.EventLog.SourceExists("MailSource")) System.Diagnostics.EventLog.CreateEventSource("MailSource", "MailServiceLog");
this.eventLog1.Source = "MailSource";
this.eventLog1.Log = "MailServiceLog";
this.eventLog2.Source = "LiveRemotingSource";
this.eventLog2.Log = "MailServiceLog";
}

protected override void OnStart(string[] args) {
try {
InitConfig();
this.eventLog1.WriteEntry(strList[0], System.Diagnostics.EventLogEntryType.SuccessAudit);

this.timer1.Interval = config.TimeInterval * 1000;
this.timer1.Enabled = true;
sendEmailThread
= new Thread[config.AmountThread];
}
catch (Exception e) {
this.eventLog1.WriteEntry(e.ToString(), System.Diagnostics.EventLogEntryType.Error);
}
}

protected override void OnStop() {
this.eventLog1.WriteEntry(strList[1], System.Diagnostics.EventLogEntryType.SuccessAudit);
GC.Collect();
this.timer1.Enabled = false;
}

private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
if (isRun) return;

timer1.Enabled
= false;
readEmailThread
= new Thread(new ThreadStart(ReadEmailQuque));
readEmailThread.IsBackground
= true;
readEmailThread.Start();
}

private void InitConfig(){
config.Conn
= Pub.Class.WebConfig.GetApp("ConnString");
config.LogFile
= Pub.Class.WebConfig.GetApp("logFile");
config.SmtpServer
= Pub.Class.WebConfig.GetApp("SmtpServer");
config.UserName
= Pub.Class.WebConfig.GetApp("UserName");
config.Password
= Pub.Class.WebConfig.GetApp("Password");
config.FromAddress
= Pub.Class.WebConfig.GetApp("FromAddress");
string amountThread = Pub.Class.WebConfig.GetApp("AmountThread");
config.AmountThread
= amountThread.Equals("") ? 1 : Convert.ToInt32(amountThread);
config.AmountThread
= config.AmountThread < 1 ? 1 : config.AmountThread;
string recordCount = Pub.Class.WebConfig.GetApp("RecordCount");
config.RecordCount
= recordCount.Equals("") ? 1000 : Convert.ToInt32(recordCount);
config.RecordCount
= config.RecordCount < 1000 ? 1000 : config.RecordCount;
string timeInterval = Pub.Class.WebConfig.GetApp("TimeInterval");
config.TimeInterval
= timeInterval.Equals("") ? 1000 : Convert.ToInt32(timeInterval);
config.TimeInterval
= config.TimeInterval < 2 ? 2 : config.TimeInterval;
}

private void ReadEmailQuque(){
timer1.Enabled
= true;
IList
<EC_EmailList> list = EC_EmailListFactory.Instance().SelectListByTop(config.RecordCount);
if (list.Count == 0) return;

isRun
= true;
for (int i = 0; i < list.Count; i++) {
emailQueue.Enqueue(list[i]);
}

for (int i = 0; i < config.AmountThread; i++) {
sendEmailThread[i]
= new Thread(new ThreadStart(DoSendEmail));
sendEmailThread[i].Name
= "Thread" + (i+1).ToString();
sendEmailThread[i].Start();
}
list
= null;
}

private void DoSendEmail(){
while (true) {
EC_EmailList objMail;
lock(this){
if (emailQueue.Count>0) {
objMail
= (EC_EmailList)emailQueue.Dequeue();
}
else {
isRun
= false;
return;
}
}

int mailID = (int)objMail.EmailID;
string strTo = objMail.To;
string strSubject = objMail.Subject;
string strBody = objMail.Body;
string strFrom = objMail.From;
string smtpServer = objMail.SmtpServer;
string userName = objMail.UserName;
string password = objMail.Password;

bool isTrue = SendMail(strTo, strSubject, strBody, strFrom, smtpServer, userName, password, "");

EC_EmailListFactory.Instance().DeleteByID(mailID);

}
}

public bool SendMail(string strTo, string strSubject, string strBody,
string strFrom, string smtpServer, string userName,
string password, string attachments) {
Email email
= new Email();
string strSmtpServer = smtpServer.Length > 0 ? smtpServer : config.SmtpServer.Trim();
email.SmtpServer
= strSmtpServer;
email.SmtpUserName
= userName.Length > 0 ? userName : config.UserName.Trim();
email.SmtpPassword
= password.Length > 0 ? password : config.Password.Trim();
email.SmtpPort
= strSmtpServer.ToLower().Contains("gmail") ? "587" : "25";
email.EnableSsl
= strSmtpServer.ToLower().Contains("gmail") ? true : false;
email.FromEmail
= strFrom.Length > 0 ? strFrom : config.FromAddress.Trim();
email.Subject
= strSubject;
email.Body
= strBody;
email.Encoding
= System.Text.Encoding.UTF8;
bool isSuccess = email.SmtpClientSend(strTo);
return isSuccess;
}
public void ErrorLog(string strMessage) {
lock(this){
StreamWriter sw
= new StreamWriter(config.LogFile + "MailLog.txt", true);
sw.WriteLine(strMessage);
sw.Flush();
sw.Close();
}
}
}
}

 

 

曾经运行在MSN的MCLUB的服务器上跑发EMAIL的服务。应该是安全无死锁调用。

posted @ 2010-08-26 12:44  熊哥  阅读(15398)  评论(15编辑  收藏  举报