.

Saturday, June 14, 2008

Sending Email Asynchronously

Sending Email Asynchronously

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 <>

message.Attachments.Add(new Attachment (attachmentsIdea));}

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);

}

}

No comments:

.