1. September 2011 07:02
I recently had a request on how to create a progress bar for sending an email with aspNetEmail. (thanks John!).
To do this, you need to tie into the EmailMessage BeforeSocketSend event. This event is raised just before aspNetEmail sends the byte array of data to the underlying TCP/IP socket.
Because the email message contents are sent during the DATA command of the SMTP session, we want to wait until that section of the SMTP session takes place. Once we are in the DATA command, we can start our progress indicator. In the below example, we simply write out the current status of sending the email to a Console application.
private bool inDataEnd = false;
private double totalLength= 0.0;
private double totalSent = 0.0;
EmailMessage msg = new EmailMessage( "127.0.0.1");
msg.From = "email@example.com";
msg.To = "firstname.lastname@example.org";
msg.Subject = "large email";
msg.Body = "this email will have a large attachment.";
//load a large file
FileStream fs = File.OpenRead( "c:\\temp\\largefile.jpg");
Attachment a= new Attachment(fs, "largefile.jpg");
//(Not required, but set for this example)
//Set a socket buffer length.
//this will lower the memory footprint, but increase cpu usage
msg.SocketBufferLength = 2048;
//wire up the BeforeSmtpSend envent
msg.BeforeSmtpSend += new BeforeSmtpSendEventHandler ( OnBeforeSmtpSend );
//wire up the BeforeSocketSend event
msg.BeforeSocketSend += new BeforeSocketSendEventHandler( OnBeforeSocketSend );
totalLength = (double)msg.ToString().Length;
void OnBeforeSmtpSend( object sender, BeforeSmtpSendEventArgs e )
if( e.SmtpState == SmtpState.DataEnd )
inDataEnd = true;
inDataEnd = false;
void OnBeforeSocketSend( object sender, BeforeSocketSendEventArgs e )
if( inDataEnd )
totalSent += (double)e.Size;
double pctDone = totalSent/totalLength;
Console.WriteLine( pctDone.ToString("0.00% Done"));
As always, if anyone has any questions or feature requests, please feel free to contact us using the Contact Us form.