A DNS user in the forum asked about how to quickly respond to users while sending bulk email in the background. This got me to write a test function to see how it works to send emails asynchronously, which resulted the following code (modified from some existing code from somewhere).
Web Form Directive (Please note that to use asynchronous mode, set Async="true") :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendemailAsync.aspx.cs" Inherits="_Default" Async="true"%>
Send Email Code:
public void Send(string from, string
[] to, string subject, string messageBody,
bool isBodyHtml, bool Async,
string[] attachments)
{
SmtpClient emailClient;
try
{
emailClient = new SmtpClient();
emailClient.Host = //”Your host”;
emailClient.UseDefaultCredentials = true;
emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
emailClient.Port = 25;
//prepare the MailMessage contents
MailMessage message = new MailMessage ();
message.From = new MailAddress (from);
message.Subject = subject;
message.Body = messageBody;
// message.Sender = new MailAddress(from);
//set the receiver' address
foreach (string address in to)
message.To.Add(new MailAddress (address));
//set to indicate whether to use html format
message.IsBodyHtml = isBodyHtml;
message.BodyEncoding = System.Text.Encoding.UTF8;
Attachment a = new Attachment(@"D:\backup\index.html");
if (attachments.Length != null)
{
for (int i = 0; i < attachments.Length; i++)
message.Attachments.Add(new Attachment (attachments
));}
if (Async == true)
{
//wire up the event for when the Async send is completed
//smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted);
// emailClient.SendCompleted +=
emailClient.SendAsync(message, null);
// sendDelegate(emailClient, message);
}
else
emailClient.Send(message);
message.Dispose();
}
catch (Exceptionex)
{
Response.Write(ex.Message);
}
}
Note:
I have done some mini-scale test, there is no significant performance advantage of async over sync. However, if sending thousands of emails would be a differnt matter.
...
Blogging is a buiness that needs a lot of discipline, which I sorely lack, as a result, my blog has a whole month of gapping hole. Too bad. I hope I can do better from now on.