1

I am a new ASP.NET developer and I am working on a project in which the admin/system can send an email to the user. As I don't want the admin to wait until the system sends the email, I plan to use SendAsync method.

However, I am getting a very weird error which is

"SmtpExecption was caught: Failure sending mail."

that I could not resolve it.

For your information, I am using .NET Framework 4.

protected void btnSend_Click(object sender, EventArgs e)
    {
    try
            {
                Mailer mail = new Mailer();
                string senderE = ConfigurationManager.AppSettings["EmailID"].ToString();
                string senderName = "Test User"
                string recipientName = "TestSender";
                string subject = txtSubject.Text;
                string body = txtMessage.Text;
                mail.SendAsync(senderE, senderName, recipient, recipientName, subject, body);

                lblInfo.Text = "sent successfully :)";
                Response.Redirect("Test.aspx");
            }
            catch
            {
                lblInfo.Text = "Error!!!";
            }}

Here's the code of SendAsync Method from my custom Mailer class:

    public void SendAsync(string sender, string senderName, string recipient, string recipientName, string subject, string body)
        {
            var message = new MailMessage()
            {
                From = new MailAddress(sender, senderName),
                Subject = subject,
                Body = body,
                IsBodyHtml = true
            };
            message.To.Add(new MailAddress(recipient, recipientName));

            try
            {
                var client = new SmtpClient();
                client.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
                string userState = "Test";
                client.SendAsync(message, userState);
            }
            catch (Exception ex)
            {
                //handle exeption
                throw ex;
            }
            finally
            {
                //clean up.
                message.Dispose();
            }
        }

public static void MailDeliveryComplete(object sender, AsyncCompletedEventArgs e)
    {
        string message = "";
        // Get the unique identifier for this asynchronous operation.
        MailMessage mail = e.UserState as MailMessage;

        if (e.Error != null)
        {
            //handle error
            message = "Error " + e.Error.ToString() + " occurred";
        }
        else if (e.Cancelled)
        {
            //handle cancelled
            message = "Send canceled for mail with subject " + mail.ToString();
        }
        else
        {
            //handle sent email
            message = "Mail sent successfully";
        }

    }

So how can I fix it?

UPDATE #1:

By the way, I am saving all the SMTP configurations in the Web.Config file. Here are the settings:

<system.net>
    <mailSettings>
      <smtp from="My Gmail Account" deliveryMethod="Network">
        <network enableSsl="true" host="smtp.gmail.com" port="587" userName="Username" password="Password" defaultCredentials="false"/>
      </smtp>
    </mailSettings>
  </system.net>

UPDATE #2: After trying different suggestions, I added Async=True to the Page Directive and I got a new error message says:

An asynchronous module or handler completed while an asynchronous operation was still pending.

I debugged the code and this time the debugger went inside MailDeliveryMethod and it throws this error from the following block:

if (e.Error != null)
        {
            //handle error
            message = "Error " + e.Error.ToString() + " occurred";
        }

Any idea about why I am getting this kind of error?

Technology Lover
  • 259
  • 1
  • 7
  • 19
  • 1
    What line does it get thrown on? Is there an innerex? – P.Brian.Mackey Nov 04 '13 at 19:59
  • 6
    FYI: **NEVER** use `throw ex;`. This ruins your stack trace (the source of the exception will be indicated as `throw ex` and *not* where it was actually thrown)! Just use `throw;` to properly re-throw – tnw Nov 04 '13 at 19:59
  • Did you set your localhost as your SMTP server? By the way, SMTP servers use port 25 as default which is blocked as defaul by the most of ISPs – curiousBoy Nov 04 '13 at 20:00
  • DId you try sync-ed with the same values? Simplify code step by step. You might have forgotten to set EnableSSL or something else. – LINQ2Vodka Nov 04 '13 at 20:01
  • ps: How about client credentials? – LINQ2Vodka Nov 04 '13 at 20:05
  • Thanks guys for trying to help me. Please see my updated question. And by the way, I tried to send an email synchronously and it was working fine. However, trying to send an email asynchronously did not work and I don't know why. – Technology Lover Nov 04 '13 at 20:28
  • Please answer the question above: "What line does it get thrown on?". Also, AsyncCompletedEventArgs has Error property containing an exception. Is its text what you wrote in above? – LINQ2Vodka Nov 04 '13 at 20:41
  • @jim, it gave an error in the following: `catch (Exception ex) { //handle exeption throw ex; }` – Technology Lover Nov 04 '13 at 20:54
  • 1. Try to set breakpoint inside your MailDeliveryComplete and see what the Error is. 2. I'm not sure but how your web.config mailing settings are attached to your smtp client created in code? – LINQ2Vodka Nov 04 '13 at 21:00
  • @jim, I set three breakpoints inside MailDeliveryComplete method, however, the debugger did not reach it (or it did not go inside the MailDeliveryComplete). It is really weird error. – Technology Lover Nov 04 '13 at 21:16
  • what about option #2? – LINQ2Vodka Nov 04 '13 at 21:23
  • I think by default, it will get the settings from the Web.Config file. As I told you, I tried sending a normal email instead of using SendAsync and it was working fine with the same settings. – Technology Lover Nov 04 '13 at 21:38

0 Answers0