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?