Using the ASP.NET Login Controls with Mail Servers that Require SSL

Some of the Login controls that ship with ASP.NET, such as CreateUserWizard, ChangePassword and PasswordRecovery enable you to send e-mail to your users without writing a lot of code. You just drag and drop a control, assign a mail body template and you're pretty much done. However, as soon as your mail server requires you to use SSL (as, for example, GMail does), things become a little trickier. In this short article I'll show the code and configuration needed to send mail to servers that require SSL.

Introduction

You typically don't have to write a lot of code when you want to send an e-mail from one of the Login controls if your mail server doesn't require SSL or authentication. For example, for the CreateUserWizard to send an e-mail with an account confirmation message, you need to do three things:

  1. Configure the MailDefinition element of the CreateUserWizard
  2. Create a message body for the e-mail
  3. Set up a mail server in the web.config file

Here's the definition for the CreateUserWizard control:

<asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
  <MailDefinition BodyFileName="~/App_Data/CreateUserWizard.txt" 
         Subject="Your new account">
  </MailDefinition>
  <WizardSteps>
    <asp:CreateUserWizardStep runat="server" />
    <asp:CompleteWizardStep runat="server" />
  </WizardSteps>
</asp:CreateUserWizard>

The CreateUserWizard.txt file can contain text welcoming the user and can optionally contain the user's user name and password:

Dear <%UserName%>,

Thank you for signing up for an account at our web site. For your reference, please 
find your login details below:

User name: <%UserName%>
Password: <%Password%>	    

The final step is configuring the mail server in the web.config file. If you can use your ISP's mail server or you have a mail server on your local network, you typically don't need more than this:

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="You@YourProvider.com">
      <network host="smtp.YourProvider.com"/>
    </smtp>
  </mailSettings>
</system.net>

Now, whenever a user signs up for an account using the CreateUserWizard control, an e-mail that contains the user's user name and password is sent using the mail server defined in the config file. This all works fine if your mail server doesn't require SSL. When it does, for example because you are using GMail's SMTP server, you need to write a bit more code.

Using Mail Servers that Require SSL

When sending an e-mail message with your own code to a mail server that requires SSL, you need to set the EnableSsl property of the SmtpClient class you're using to true. However, when using the Login controls, you don't create an instance of SmtpClient yourself so you can't easily enable SSL. Internally, the CreateUserWizard (and other controls) create an SmtpClient with this setting to false, resulting in errors when trying to send the e-mail. To work around this, follow these steps:

  1. Configure the web.config file and set up a mail server with a specified port number, user name and password.
  2. Handle the SendingMail event that the Login controls fire and execute the following steps:
    1. Create your own instance of the SmtpClient
    2. Set EnableSsl to true
    3. Send the message (which you can access using e.Message) with your own SmtpClient
    4. Cancel the original message.

For the first step, you need to add something like this to your web.config file:

<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="YourAccount@gmail.com">
      <network
        port="587"
        userName="YourAccount@gmail.com"
        password="YourPassword"
        host="smtp.gmail.com"
      />
    </smtp>
  </mailSettings>
</system.net> 

You need to fill in your GMail's user name and password in the respective attributes.

The next step is to handle the SendingMail event which is fired by the following three Login controls:

  • ChangePassword
  • CreateUserWizard
  • PasswordRecovery

You can handle the SendingMail event that these controls fire with the following code:

protected void CreateUserWizard1_SendingMail(object sender, MailMessageEventArgs e)
{
  SmtpClient mySmtpClient = new SmtpClient();
  mySmtpClient.EnableSsl = true;
  mySmtpClient.Send(e.Message);
  e.Cancel = true;
}

This code first creates a new SmtpClient. When this client needs to send out an e-mail, it will use the details provided in the web.config file, including the user name, password and configured mail server.

Next, it enables SSL by setting the EnableSsl property to true. It then accesses the message that is being sent by the Login controls using e.Message which is then passed to the client's Send method. Finally, to stop the control from still sending its own message using the configured mail server without enabling SSL, the code calls e.Cancel = true. Since this code is the same for all three controls, you could create a helper method with this code so you only need to write it once.

This solution is not as convenient as an EnableSsl attribute on the network element in web.config would be, but it doesn't require a whole lot of code to make it work. In the code download that comes with this article, you find a sample page for each of the three Login controls that support sending mail.

Download Files

Source Code for this Article

Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .


Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Thursday, January 27, 2011 4:59:13 PM David said:
This is working with VS 2010. But it's not working with published site. What should I check? Error message from published site is:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
On Friday, January 28, 2011 9:48:39 AM Imar Spaanjaars said:
Hi David,

Sounds like your site can't find the configured database. Check out the connection string in your web.config and work with your database administrator to find the right setup details. Take a look at www.connectionstrings.com for examples of connection strings.

Cheers,

Imar
On Monday, March 28, 2011 4:41:38 PM Nazeem Bahadoor said:
Hi ,
I have tried with my gmail account, it got an error message :

No connection could be made because the target machine actively refused it 74.125.157.109:587
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 74.125.157.109:587 .   Any help will be glad.
On Tuesday, March 29, 2011 12:52:27 AM Imar Spaanjaars said:
Hi Nazeem,

Are you using the *exact*same code as I am showing here? If so, the code is fine and the problem may be in the network.

Otherwise, try posting your complete code and config information on a forum such as this one: http://p2p.wrox.com/index.php?referrerid=385

Cheers,

Imar
On Monday, May 16, 2011 7:44:24 AM John Simmons said:
I am using visual web developer express 2010.
I bought and used your book Beginning ASP.NET 4.
I constructed a web site using the ASP.NET 4web site instead of using your ASP.NET empty web site to begin my new web site.
I followed all your recommended instructions to build my site.
Everything works great except that when I attempted to set the properties on the create user wizard to allow a confirmed email to the newly created user no email was received.  I even tried your suggestion of using the event technique to no avail.
I constructed a new web site based on the ASP.NET 4 empty website and set up the basic log in controls and create user wizard.  The new basic site worked as you said it would and the proper confirm emails indeed were sent out.
I wonder if the problem might be that the ASP.NET 4 web site template places the login system inside the pre-constructed master page header and not in the root director?
I wonder if the problem is that the auto create user wizard is not placed in a web form, but instead placed in a master page content holder.  I tried to add a forms  tag around the create user wizard, but VWDE would not allow it.

Could you give me a clue as to why my using an ASP.NET 4 web site template renders the create user wizard incapable of sending confirmation emails to the newly logged in users that are created?

You have a great book and is a very good guide to learn the system.

Thank you very much for your book and any help you may provide me.

John Simmons
On Monday, May 16, 2011 7:52:58 AM Imar Spaanjaars said:
Hi John,

No, I don't know why that wouldn't work. I just tested it and it works fine for me. Have you tried specifying a local drop folder and see of that works? Maybe the control works fine but mail sending doesn't?

Take a look here for the local drop folder: http://imar.spaanjaars.com/496/using-a-local-pickup-folder-for-email-delivery

>> I wonder if the problem is that the auto create user wizard is not placed in a web form, but instead placed in a master page content holder.  I tried to add a forms  tag around the create user wizard, but VWDE would not allow it.

Nope, that shouldn't have anything to do with it. The Master Page that's used defines these form tags so you shouldn't add your own.

Cheers,

Imar
On Wednesday, September 12, 2012 2:55:05 AM Christopher said:
Hi Imar,
I am indeed very pleased with your book.  It has helped me immensely. Thank you so much.

I am having a little hitch in sending confirmation email. I have tried all your suggestion but it did not work, don't know where the problem is. It keeps showing this error "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. vz8sm4534880pbc.63"

As for the password recovery, it worked perfectly. Please advice me on what to do. I am awaiting your earliest response. Thanks.

On Thursday, September 13, 2012 3:18:40 PM Imar Spaanjaars said:
Hi Christopher,

Can you post your code in the General ASP.NET category of the Wrox forum (at http://p2p.wrox.com/asp-net-4-general-discussion-561/)?

Then I'll take a look and see if I can find anything wrong with your code.

Cheers,

Imar
On Thursday, November 27, 2014 7:55:44 PM Edwin said:
please i need some materials on C# programming language that will be of great assistance to me in order to enable me undertake a project  which is the design and implementation of bank fraud detection system.
On Thursday, November 27, 2014 9:30:54 PM Imar Spaanjaars said:
Hi there,

How is this related to the article's topic of using the ASP.NET Login Controls with mail servers that require SSL?

I would start in the Amazon C# books section, or try a Google search.

Cheers,

Imar

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.