Link to home
Start Free TrialLog in
Avatar of SweatCoder
SweatCoderFlag for United States of America

asked on

smtp SendAsync always throws error "Failure sending email"

I have an ASP.NET web page that calls a separate class library that attempts to send email async. When I send the email synchronously, it works perfectly:

smtp.Send(mail)

but when I send async:

smtp.SendCompleted += new SendCompletedEventHandler(SendEmailCompletedCallback);
smtp.SendAsync(mail, GetUserIDFromCookie());

private static void SendEmailCompletedCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
            //int token = int.Parse(e.UserState.ToString());

            if (e.Cancelled)
            {
                WriteLog("SendEmailCompletedCallback", "Async email cancelled.");
            }
            if (e.Error != null)
            {
                WriteLog("SendEmailCompletedCallback", "Async email error: " + e.Error.ToString());
            }
            else
            {
                WriteLog("SendEmailCompletedCallback", "Async email sent!");
            }
        }

The callback method is never reached. Exception thrown during SendAsync(..).

Everything else is the same. Credentials the same for both methods. I have Async="true" in my @Page declaration on the calling aspx page.

I have googled on this for awhile and read several articles. I can't find anything I'm missing.
Avatar of dj_alik
dj_alik

You full error is this?
Message: "Failure sending mail."
 
InnerException: {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()
    at System.Net.Mail.MailMessage.BeginSend(BaseWriter writer, Boolean sendEnvelope, AsyncCallback callback, Object state)
    at System.Net.Mail.SmtpClient.SendMailCallback(IAsync¿­Result result)} System.Exception {System.ObjectDisposedException}
 
Are you using statement if yes remove it.
Avatar of SweatCoder

ASKER

What does this mean: "Are you using statement if yes remove it."  ??
ASKER CERTIFIED SOLUTION
Avatar of dj_alik
dj_alik

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes, the smtp.Dispose() was wrecking the object, causing the error. When I commented that out, everything worked great.
Sorry about the delay in coming back to this.