定义抽象接口以封装所有实现:
using System; using System.Web.Mail;
namespace YywMail { public abstract class MySmtpMail { Fields#region Fields
private string _defaultCharset = "GB2312"; private int _defaultSmtpPort = 25;
#endregion Properties#region Properties
protected string DefaultCharset { get { return this._defaultCharset; } }
protected int DefaultSmtpPort { get { return this._defaultSmtpPort;} }
#endregion
Methods#region Methods
/** <summary> /// 获取默认实例 /// </summary> /// <returns></returns> public static MySmtpMail GetDefaultInstance() { // 此处可通过外部配置文件定义具体实现类型,再 // 通过 Activator.CreateInstance() 获取类型实例 }
/** <summary> /// 做一些初始化的工作 /// </summary> public abstract void Open();
/** <summary> /// 销毁对象 /// </summary> public abstract void Close();
/** <summary> /// 发送邮件 /// </summary> /// <param name="message"></param> /// <param name="smtpServer"></param> /// <param name="serverUsername"></param> /// <param name="serverPassword"></param> /// <returns></returns> public bool Send(MailMessage message, string smtpServer, string serverUsername, string serverPassword) { return Send(message, smtpServer, serverUsername, serverPassword, this._defaultSmtpPort); }
public abstract bool Send(MailMessage message, string smtpServer, string serverUsername, string serverPassword, int smtpPort);
public static string[] GetTo(MailMessage message) { if (message == null) throw new ArgumentNullException("message");
if (Globals.IsNullorEmpty(message.To)) return null;
return message.To.Split(;); }
public static string[] GetCc(MailMessage message) { if (message == null) throw new ArgumentNullException("message");
if (Globals.IsNullorEmpty(message.Cc)) return null;
return message.Cc.Split(;); }
public static string[] GetBcc(MailMessage message) { if (message == null) throw new ArgumentNullException("message");
if (Globals.IsNullorEmpty(message.Bcc)) return null;
return message.Bcc.Split(;); }
#endregion } }
注: 按照常理,使用前先 Open() 一下,使用后也别忘了 Close()
实现方案一(Jmail 组件):
在 .NET 中使用 Jmail 需要如下设置: 1、安装jmail; 2、找到jmail.dll; 3、注册该组件Jmail.dll,作法是将jmail.dll文件拷贝到system32目录下,再运行命令“regsvr32 jmail.dll”(不包括引号),卸载可运行“regsvr32 /u jmail.dll”; 4、执行Program Files/Microsoft Visual Studio .NET/FrameworkSDK/Bin/ildasm.exe(可使用Visual Studio .Net 2003 命令提示), 格式如下:tlbimp c:/Program Files/Dimac/w3JMail4/jmail.dll /out:MyJmail.dll /namespace:MyJmail 生成MyJmail.dll后,将它引用至项目中。
下载组件
接下来就是实现类的编写了:
using System; using System.Web.Mail;
namespace YywMail { public class JMailSmtpMail : MySmtpMail { Fields#region Fields
MyJmail.Message jmail = null;
#endregion
Methods#region Methods
public override void Open() { jmail = new MyJmail.Message(); }
public override bool Send(MailMessage message, string smtpServer, string serverUsername, string serverPassword, int smtpPort) { if (jmail == null) throw new Exception("smtp is Closed!"); if (message == null) throw new ArgumentNullException("message");
DateTime t = DateTime.Now;
//Silent属性:如果设置为true,JMail不会抛出例外错误. JMail. Send( () 会根据操作结果返回true或false jmail.Silent = false;
//jmail创建的日志,前提loging属性设置为true jmail.Logging = true;
//字符集,缺省为"US-ASCII" jmail.Charset = base.DefaultCharset;
//信件的contentype. 缺省是"text/plain") : 字符串如果你以HTML格式发送邮件, 改为"text/html"即可。 if (message.BodyFormat == MailFormat.Html) jmail.ContentType = "text/html";
jmail.Priority = GetJmailPriority(message.Priority);
//添加收件人 string[] toArray = MySmtpMail.GetTo(message); if (toArray != null && toArray.Length > 0) { bool isAddedRecipient = false;
for (int i = 0; i < toArray.Length; i++) { if (Globals.IsNullorEmpty(toArray[i])) continue;
if (!isAddedRecipient) { jmail.AddRecipient(toArray[i], String.Empty, String.Empty); isAddedRecipient = true; } else { jmail.AddRecipientCC(toArray[i], String.Empty, String.Empty); } } }
string[] ccArray = MySmtpMail.GetCc(message); if (ccArray != null) { foreach (string cc in ccArray) { if (!Globals.IsNullorEmpty(cc)) jmail.AddRecipientCC(cc, String.Empty, String.Empty); } }
string[] bccArray = MySmtpMail.GetBcc(message); if (ccArray != null) { foreach (string bcc in bccArray) { if (!Globals.IsNullorEmpty(bcc)) jmail.AddRecipientBCC(bcc, String.Empty); } }
jmail.From = message.From;
//发件人邮件用户名 jmail.MailServerUserName = serverUsername; //发件人邮件密码 jmail.MailServerPassWord = serverPassword; //设置邮件标题 jmail.Subject = message.Subject; //邮件添加附件,(多附件的话,可以再加一条jmail.AddAttachment( "c://test.jpg",true,null);)就可以搞定了。[注]:加了附件,讲把上面的jmail.ContentType="text/html";删掉。否则会在邮件里出现乱码。 //jmail.AddAttachment("c://test.jpg", true, null); //邮件内容 jmail.Body = message.Body;
if (message.BodyFormat == MailFormat.Html) jmail.Body += "<br><br>"; else jmail.Body += "/r/n/r/n";
jmail.Body += DateTime.Now.ToString();
smtpServer = String.Format("{0}:{1}", smtpServer, smtpPort);
//jmail发送的方法 bool result = jmail.Send(smtpServer, false);
return result; }
public override void Close() { jmail.Close(); }
private static byte GetJmailPriority( System.Web.Mail.MailPriority priority) { // 邮件等级,1为加急,3为普通,5为低级
if (priority == System.Web.Mail.MailPriority.High) return 1;
if (priority == System.Web.Mail.MailPriority.Low) return 5;
return 3; }
#endregion } }
实现方案二(OpenSmtp.Net 组件):
对于还没有接触过 OpenSmtp.Net 的朋友可以先 Google 下,这里不再做概念介绍,同时它还有一个孪生兄弟 OpenPop.Net,至于 OpenSmtp.Net 我们可以在 http://sourceforge.net/projects/opensmtp-net/ 下载到,目前最新版本是 1.11。
接下来开始进入主题:
using System; using System.Web.Mail; using OpenSmtp.Mail;
namespace YywMail { public class OpenSmtpMail : MySmtpMail { Files#region Files
OpenSmtp.Mail.MailMessage msg = null; Smtp smtp = null;
#endregion
Methods#region Methods
public override void Open() { msg = new OpenSmtp.Mail.MailMessage(); smtp = new Smtp(); }
public override bool Send(System.Web.Mail.MailMessage message, string smtpServer, string serverUsername, string serverPassword, int smtpPort) { if (msg == null || smtp == null) throw new Exception("smtp is Closed!");
if (message == null) throw new ArgumentNullException("message");
SmtpConfig.VerifyAddresses = false; EmailAddress from = new EmailAddress(message.From, message.From); msg.Charset = base.DefaultCharset;
msg.From = from; msg.Priority = GetOpenSmtpPriority(message.Priority);
//添加收件人 string[] toArray = MySmtpMail.GetTo(message); if (toArray != null) { foreach (string to in toArray) { if (!Globals.IsNullorEmpty(to)) msg.AddRecipient(to, AddressType.To); } }
string[] ccArray = MySmtpMail.GetCc(message); if (ccArray != null) { foreach (string cc in ccArray) { if (!Globals.IsNullorEmpty(cc)) msg.AddRecipient(cc, AddressType.Cc); } }
string[] bccArray = MySmtpMail.GetBcc(message); if (ccArray != null) { foreach (string bcc in bccArray) { if (!Globals.IsNullorEmpty(bcc)) msg.AddRecipient(bcc, AddressType.Bcc); } }
msg.Subject = message.Subject;
if (message.BodyFormat == System.Web.Mail.MailFormat.Html) { msg.HtmlBody = message.Body + "<br><br>" + DateTime.Now.ToString(); } else { msg.Body = message.Body + "/r/n/r/n" + DateTime.Now.ToString();; }
string str1 = msg.HtmlBody; string str2 = msg.Body; smtp.Host = smtpServer; smtp.Username = serverUsername; smtp.Password = serverPassword; smtp.Port = smtpPort;
smtp.SendMail(msg);
return true; } public override void Close() { msg = null; smtp = null; }
private static string GetOpenSmtpPriority( System.Web.Mail.MailPriority priority) { // 邮件等级,1为加急,3为普通,5为低级
if (priority == System.Web.Mail.MailPriority.High) return OpenSmtp.Mail.MailPriority.High;
if (priority == System.Web.Mail.MailPriority.Low) return OpenSmtp.Mail.MailPriority.Low;
return OpenSmtp.Mail.MailPriority.Normal; }
#endregion } }