?
Solved

Issue with Send Email Asynchronously with ASP.NET

Posted on 2009-02-12
3
Medium Priority
?
410 Views
Last Modified: 2012-05-06
Hello!

I am trying to add a page for sending email asynchronously to our web site.

My problem is the email does not send? You click the send button and the page just flickers and stays the same. No error, no nothing.

Any ideas?

Here is the code for the web.config:
<system.net>
    <mailSettings>
      <smtp>
        <network host="mailserver.com" port="587" userName="name@test.com" password="password" />
      </smtp>
    </mailSettings>
  </system.net>

New Page code:
<%@ Page Language="C#" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Net.Mail" %>
 
 <script language="C#" runat="server">
    
         protected void Page_Load(object sender, EventArgs e)
         {
 
         }
         protected void btnSend_Click(object sender, EventArgs e)
         {
             SendMail();
         }
 
         /// &lt;summary&gt;
         /// Sends email asynchronously.
         /// &lt;/summary&gt;
         private void SendMail()
         {
             System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
 
             mailMessage.From = new MailAddress("applicant@test.com");
             mailMessage.To.Add(new MailAddress("employer@test.com"));
 
             mailMessage.Subject = txtSubject.Text.Trim();
             mailMessage.Body = txtBody.Text.Trim();
 
             SmtpClient smtpClient = new SmtpClient();
             Object userState = mailMessage;
 
             //Attach event handler for async callback
             smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
 
             try
             {
                 //Send the email asynchronously
                 smtpClient.SendAsync(mailMessage, userState);
             }
             catch (SmtpException smtpEx)
             {
                 //Error handling here
             }
             catch (Exception ex)
             {
                 //Error handling here
             }
         }
 
         /// &lt;summary&gt;
         /// Event handler for processing completion information after asynchronous email sent.
         /// &lt;/summary&gt;
         void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
         {
 
             //Get UserState as MailMessage instance from SendMail()
             MailMessage mailMessage = e.UserState as MailMessage;
 
             if (e.Cancelled)
             {
                 labMessage.Text = "Sending of email message was cancelled. Address=" + mailMessage.To[0].Address;
             }
 
             if (e.Error != null)
             {
                 labMessage.Text = "Error occured, info=" + e.Error.Message;
             }
             else
             {
                 labMessage.Text = "Mail sent successfully";
             }
 
         }    
    
</script>
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
    <div>
     <p>
      <asp:TextBox ID="txtSubject" runat="server" Columns="50" />
    </p>
    <p>
      <asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Rows="5" Columns="60" />
    </p>
    <p>
      <asp:Button ID="btnSend" runat="server" Text="Send Email" 
        onclick="btnSend_Click" /></p>
    <p>
      <asp:Label ID="labMessage" runat="server" /></p>
    </div>
    </form>
</body>
</html> 
Open in New Window Select All

Open in new window

0
Comment
Question by:Cyberzones
3 Comments
 
LVL 4

Accepted Solution

by:
brrrdog earned 1500 total points
ID: 23626492
Send it synchronously first to make sure you don't have an issue with your email configuration.  You can also try <smtp deliveryMethod="PickupDirectoryFromIis"> to use your local IIS's smtp server - either the email file will be waiting in the inetpub\mailroot\queue or pickup folder, or you'll at least get some additional diagnostics with the smtp log.

The reason why it just flickers is because you're doing this asynchronously - the problem is that the response is completed before your smtpClient_SendCompleted event is ever fired.  If you're really looking to give feedback for your send event you'll either need to send it synchronously or do some sort of blocking in one of the page events like prerender.
0
 
LVL 2

Expert Comment

by:patrickriva
ID: 23626744
Have you tryed put some code in the catch blocks and setting breakpoints on those lines?
if you have an exception there its catched and ignored!

try
             {
                 //Send the email asynchronously
                 smtpClient.SendAsync(mailMessage, userState);
             }
             catch (SmtpException smtpEx)
             {
                 string s = smtpEx.ToString();
             }
             catch (Exception ex)
             {
                 string s = exToString();
             }
0
 
LVL 26

Expert Comment

by:Anurag Thakur
ID: 23633578
can you try after changing the user name to domainname\username in web config
<network host="mailserver.com" port="587" userName="domainName\UserName" password="password" />
0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
Suggested Courses

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question