Asp.net smtp mail message holding page up

hi Experts,

I'm using a click event to do 3 things (run a sql query, send an email, display a label) it works but the addition of the email slows the page right down, I presumed this was just happening if the mail request hit the exchange server at a busy time but I've noticed the lag seems to be after I receive the mail.
So as a rule the mail takes maybe 1-2seconds to pop up on my screen, but the web page will appear to freeze for maybe another 8-10 seconds before finally refreshing and displaying the label text - without the email this process is instant.

Question is how to remove the lag so the user is not sat waiting for the process to finish?
forstersAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Najam UddinCommented:
try sending async

smtpClient.SendAsync(mail, state);

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
forstersAuthor Commented:
hi thanks for your comment, I tried to get this working before but the mail just didn't send and I got an error. I think from what I read that there is a conflict with the SendAsync command and Asp.net?
The example on msdn is for a c# console app and I've not found a working example for an asp.net page...

Below is the code I have tried, which errors on the mail send but otherwise works:
protected void Button2_Click(object sender, EventArgs e)
    {
        SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        SqlCommand cmd2 = new SqlCommand("Update AccDets set ClientName=@ClientName, AccNumber=@AccNumber, SortCode=@SortCode, LastAmendedBy=@username where AccID=@AccID", con2);
        cmd2.Parameters.AddWithValue("@AccNumber", TxtNewAcc.Text);
        cmd2.Parameters.Add("@SortCode ", SqlDbType.Char);
        cmd2.Parameters["@SortCode "].Value = TxtNewSort1.Text + TxtNewSort2.Text + TxtNewSort3.Text;
        cmd2.Parameters.AddWithValue("@ClientName", TxtNewName.Text);
        cmd2.Parameters.AddWithValue("@AccID", Session["accID"]);
        cmd2.Parameters.AddWithValue("@username", Session["username"]);

        con2.Open();

        cmd2.ExecuteNonQuery();
        // SEND EMAIL TO COMPLIANCE
        MailAddress fromAddress = new System.Net.Mail.MailAddress("sender@mailaddress.co.uk");  
        MailAddress toAddress = new System.Net.Mail.MailAddress("recipient@mailaddress.co.uk"); 
        try
        {
            MailMessage message = new MailMessage();
            message.From = fromAddress;
            message.Subject = "Test";
            message.To.Add(toAddress);

            message.IsBodyHtml = true;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<p style=\"color:#000099; font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold;\">Text</p>");
            sb.Append("<p style=\"color:#000099; font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold;\">Text</p>");
            sb.Append("<p style=\"color:#000099; font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold;\">Text </p>");
            sb.Append("<p style=\"color:#000099; font-family:Arial, Helvetica, sans-serif; font-size:14px; font-weight:bold;\">Text</p>");

                     message.Body = sb.ToString();

            SmtpClient smtpClient = new SmtpClient("Servername");
            Object state = message;

                     
                smtpClient.SendAsync(message, state);
                message.Dispose(); 
        }
            
            catch (Exception ex)
            {
                namePanel.Visible = true;
                buttonPanel.Visible = true;
                editPanel.Visible = false;
                LblAction.Text = "";
                LblActionError.Text += "There has been an error (" + ex.Message.ToString() + ").";
            }

           
            con2.Close();

            namePanel.Visible = true;
            buttonPanel.Visible = true;
            editPanel.Visible = false;
            LblAction.Text = "Update Successful";
        }

Open in new window

0
Najam UddinCommented:
can you share error?
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

forstersAuthor Commented:
it just says 'Failure sending mail'
0
Najam UddinCommented:
in place of ex.Message try ex.ToString(), this will give more detailed error. And check if you have marked your page async

<%@ Page Language="C#" AutoEventWireup="true" ....... Async="true" %>

Open in new window

0
forstersAuthor Commented:
new error below - I set the async to true and the error isn't thrown but its been a couple of minutes already and still no mail...

There has been an error (System.Net.Mail.SmtpException: Failure sending mail. ---> System.InvalidOperationException: Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event. at System.Web.LegacyAspNetSynchronizationContext.OperationStarted() at System.ComponentModel.AsyncOperation.CreateOperation(Object userSuppliedState, SynchronizationContext syncContext) at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken) --- End of inner exception stack trace --- at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken) at Admin_ClientAccountManager_EditAccount_EditClientAccount.Button2_Click(Object sender, EventArgs e) in ...\EditClientAccount.aspx.cs:line 130).
0
Najam UddinCommented:
With Async true there should not be error. Now there are delivery and send are 2 different things. Delivery of email is not dependent on Web Site, your exchange server might delay it. Page should not freeze now.

In short, let me know if following is happening
1. Page does not freeze
2. You get your email (may be with some delay in delivery)

If both answer are yes, you should be good to go..
0
forstersAuthor Commented:
indeed - well there is no error, the page refreshes, I am still awaiting the email now sent 9 minutes ago.. bit too long wouldn't you think?
0
Najam UddinCommented:
Lets try something more before sendAsync call put

smtpClient.SendCompleted +=    new SendCompletedEventHandler(MailSendCompleted);

Open in new window


public static void MailSendCompleted(object sender, AsyncCompletedEventArgs e)
{
  MailMessage m = e.UserState as MailMessage;  
  if (e.Error != null)
  {
    //log here e.Error.ToString();
  }
  else
    // log "sent";
}

Open in new window

0
forstersAuthor Commented:
Ah ok thank you for this, getting somewhere - I get the following:

There has been an error (System.Net.Mail.SmtpException: Failure sending mail. ---> System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Net.Mail.MailMessage'. at System.Net.Mail.MailMessage.get_AlternateViews() at System.Net.Mail.MailMessage.SetContent(Boolean allowUnicode) at System.Net.Mail.SmtpClient.SendMailCallback(IAsyncResult result) --- End of inner exception stack trace
0
Najam UddinCommented:
move
message.Dispose();

inside complete event
0
forstersAuthor Commented:
Awesome! Thank you so much, that's now working perfectly. Thank you.
0
forstersAuthor Commented:
Ah one snag (sorry) on the webpage there is a second button to clear the form / refresh the page, if I click this after the mail has sent and the page initially refreshed it then hangs again for ages is there a way to avoid this?
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.