Recently, I need to maintain the ASP.NET 1.1 program due to work. I used to use the C# 2.0 System.Net.Mail namespace to send emails very well, but there are many problems with System.Web.Mail in ASP.NET 1.1, so I chose another one. The strategy encapsulates the interface for sending emails, and then implements email sending in other ways, so there are the following words.
Define an abstract interface to encapsulate all implementations:
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>
/// Get the default instance
/// </summary>
/// <returns></returns>
public static MySmtpMail GetDefaultInstance()
{
// Here you can define the specific implementation type through an external configuration file, and then
// Get the type instance through Activator.CreateInstance()
}
/**//// <summary>
/// Do some initialization work
/// </summary>
public abstract void Open();
/**//// <summary>
/// Destroy the object
/// </summary>
public abstract void Close();
/**//// <summary>
/// Send email
/// </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
}
}
Note: According to common sense, Open() before use, and don’t forget to Close() after use.
Implementation plan one (Jmail component):
Using Jmail in .NET requires the following settings:
1. Install jmail;
2. Find jmail.dll;
3. To register the component Jmail.dll, copy the jmail.dll file to the system32 directory, and then run the command "regsvr32 jmail.dll" (excluding quotation marks). To uninstall, run "regsvr32 /u jmail.dll";
4. Execute Program FilesMicrosoft Visual Studio .NETFrameworkSDKBinildasm.exe (you can use the Visual Studio .Net 2003 command prompt),
The format is as follows: tlbimp c:Program FilesDimacw3JMail4jmail.dll /out:MyJmail.dll /namespace:MyJmail
After generating MyJmail.dll, reference it into the project.
downloading the component,
the next step is to write the implementation class:
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 attribute: If set to true, JMail will not throw an exception error. JMail.Send( () will return true or false according to the operation result
jmail.Silent = false;
//Log created by jmail, provided that the logging attribute is set to true
jmail.Logging = true;
//Character set, the default is "US-ASCII"
jmail.Charset = base.DefaultCharset;
//The content type of the letter. The default is "text/plain"): String If you send the email in HTML format, change it to "text/html".
if (message.BodyFormat == MailFormat.Html)
jmail.ContentType = "text/html";
jmail.Priority = GetJmailPriority(message.Priority);
//Add recipient
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;
//Sender's email user name
jmail.MailServerUserName = serverUsername;
//Sender's email password
jmail.MailServerPassWord = serverPassword;
//Set email title
jmail.Subject = message.Subject;
//Add attachments to the email (if there are multiple attachments, you can add jmail.AddAttachment("c:\test.jpg",true,null);) and it will be done. [Note]: After adding an attachment, please delete the jmail.ContentType="text/html"; above. Otherwise, garbled characters will appear in the email.
//jmail.AddAttachment("c:\test.jpg", true, null);
//Email content
jmail.Body = message.Body;
if (message.BodyFormat == MailFormat.Html)
jmail.Body += "<br><br>";
else
jmail.Body += "rnrn";
jmail.Body += DateTime.Now.ToString();
smtpServer = String.Format("{0}:{1}", smtpServer, smtpPort);
//Jmail sending method
bool result = jmail.Send(smtpServer, false);
return result;
}
public override void Close()
{
jmail.Close();
}
private static byte GetJmailPriority(System.Web.Mail.MailPriority priority)
{
// Mail level, 1 is urgent, 3 is normal, 5 is low-level
if (priority == System.Web.Mail.MailPriority.High)
return 1;
if (priority == System.Web.Mail.MailPriority.Low)
return 5;
return 3;
}
#endregion
}
}
Implementation plan two (OpenSmtp.Net component):
For those who have not come into contact with OpenSmtp.Net, you can Google it first. I will not introduce the concept here. At the same time, it also has a twin brother OpenPop.Net. As for OpenSmtp.Net, we can Download it from http://sourceforge.net/projects/opensmtp-net/ . The latest version is 1.11.
Next, let’s get into the topic:
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);
//Add recipient
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 + "rnrn" + 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)
{
// Mail level, 1 is urgent, 3 is normal, 5 is low-level
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
}
}
Implementation plan three:
(The above two implementation plans are sufficient to meet the current needs, and can be expanded if necessary)