Sending E-Mails In The Code Behind With ASP.NET Using C#

I was recently asked, several times by varying different people, how to send emails in ASP.NET. When I explained to them how to do so they were amazed at how simple it was. I thought I would share with you this little nugget of wisdom as it is a very common feature of nearly all websites out in the wild.

In this article we will be creating a new website but if you are just looking to add the email feature to an existing site then please skip the first step.

The steps:

  • Create a new ASP.NET empty website. Name it and save it. I have called mine ‘sendemail’ but you can name yours whatever you like.

  • Next we need to add a web form. So go over to the solution explorer and right click on the website, a menu will appear, click ‘Add’ then ‘Add New Item’ (or ctrl + Shift + A). Select webform from the list, name it, then click ‘Add’.

  • Now we have our webform we need to add some mark up to the page. Nothing complicated just some text inputs, labels and a button, like so:
    1. <asp:Label ID="lblError" runat="server"></asp:Label> <br />  
    2.   
    3. <asp:Label ID="lblFirstName" runat="server" Text="Contact Name" AssociatedControlID="txtFirstName"></asp:Label>  
    4. <asp:TextBox ID="txtFirstName" runat="server" TextMode="SingleLine"></asp:TextBox>  
    5. <br />  
    6.   
    7.   
    8. <asp:Label ID="lblCompanyName" runat="server" Text="Company Name" AssociatedControlID="txtCompanyName"></asp:Label>  
    9. <asp:TextBox ID="txtCompanyName" runat="server" TextMode="SingleLine"></asp:TextBox>  
    10.   
    11. <br />  
    12.   
    13. <asp:Label ID="lblEmail" runat="server" Text="Email Address" AssociatedControlID="txtEmail"></asp:Label>  
    14. <asp:TextBox ID="txtEmail" runat="server" TextMode="SingleLine"></asp:TextBox>  
    15. <br />  
    16.   
    17.   
    18. <asp:Label ID="lblSubject" runat="server" Text="Subject" AssociatedControlID="txtSubject"></asp:Label>  
    19. <asp:TextBox ID="txtSubject" runat="server" TextMode="SingleLine"></asp:TextBox>  
    20.   
    21. <br />  
    22.   
    23. <asp:Label ID="lblPhone" runat="server" Text="Phone Number" AssociatedControlID="txtPhone"></asp:Label>  
    24. <asp:TextBox ID="txtPhone" runat="server" TextMode="SingleLine"></asp:TextBox>  
    25.   
    26. <br />  
    27.   
    28. <asp:Label ID="lblMessage" runat="server" Text="Message" AssociatedControlID="txtMessage"></asp:Label>  
    29. <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine" Rows="6"></asp:TextBox>  
    30.   
    31. <br />  
    32. <asp:Button ID="btnSend" Text="Submit message" ValidationGroup="contactVal" runat="server" OnClick="btnSend_Click" />  

Add the following using statements in your code behind:

  1. using System.Net;  
  2. using System.Net.Mail;  
  3. using System.Text.RegularExpressions;  
Next add the following code to the click event of the button:
  1. protected void btnSend_Click(object sender, EventArgs e) {  
  2.     // create variables and assign values  
  3.     string Name = txtFirstName.Text;  
  4.     string CompanyName = txtCompanyName.Text;  
  5.     string PhoneNumber = txtPhone.Text;  
  6.     string EmailAddress = txtEmail.Text;  
  7.     string SendAddress = @ "<Email Address of sender Goes Here>";  
  8.     string Subject = txtSubject.Text;  
  9.   
  10.     // preserve new lines in the body of the message  
  11.     string Message = Regex.Replace(txtMessage.Text, @ "\r\n?|\n""<br />");  
  12.     // create new message  
  13.     MailMessage msg = new MailMessage();  
  14.     msg.To.Add(new MailAddress(@ "<send to email address goes here>"));  
  15.     msg.Subject = Subject;  
  16.     msg.From = new MailAddress(SendAddress);  
  17.     msg.IsBodyHtml = true;  
  18.     msg.Body = "<p><strong>Contact Name:</strong> " + Name + "<br />";  
  19.     msg.Body += "<strong>Company Name:</strong> " + CompanyName + "<br />";  
  20.     msg.Body += "<strong>Phone Number:</strong> " + PhoneNumber + "<br />";  
  21.     msg.Body += "<strong>Email Address:</strong> " + EmailAddress + "<br />";  
  22.     msg.Body += "<strong>Message:</strong><br />" + Message + "</p>";  
  23.     // set the reply to address to the address entered in the form  
  24.     msg.ReplyToList.Add(new MailAddress(EmailAddress));  
  25.     // set up smtp client and credentials  
  26.     SmtpClient smtpClnt = new SmtpClient(smtp.your - isp.com)  
  27.     smtpClnt.Credentials = new NetworkCredential(EmailAddress and password goes here); // send the message  
  28.     smtpClnt.Send(msg);  
  29.     // inform user that message has sent   
  30.     lblError.Text = "Message sent!";  
  31. }  
What this code does is it collects the information entered, by the user, into the form and places it in variable.

For Example:
  1. string CompanyName = txtCompanyName.Text;  
I have also added in a little RegEx which preserves the new lines entered by the user otherwise the text all ends up squashed into one paragraph. It replaces the new lines with Html <br /> elements. It does so in this line:
  1. string Message = Regex.Replace(txtMessage.Text, @"\r\n?|\n""<br />");  
You could do some other transformations on the text from the multiline text box but for the sake of brevity I have chosen to just preserve the new lines.

Next we have created a new message. We have set the recipient of the message, the subject, the sending address, set isBodyHtml to true and we built the message itself. Again for the sake of brevity there is nothing fancy here, just some basic formatting performed but the possibilities are endless.

We have also set the replyTo address the email address entered by the user on the form. We have done this so that when you check your recipient email account you can reply to the user rather than your own sender address.

Next we set up an SmtpClient. I removed my own for reasons of security but it should look something like this, which is for Gmail: smtp.gmail.com.

Next came the network credentials, which is just the email address and password for the sender address. Then we sent the message. I also added a notification that the message was sent but you could do anything, i.e. reset all form fields, redirect the user to another page, etc.

Now run your application and test it out. If you have any comments or question then please leave me a comment below, or if preferred you can head over to the contact page on my website and fill in the form.

I hope this helps somebody and thank you for taking the time to read. Please share it around as much as you can. Any and all shares/tweets/etc. are very much appreciated.

Up Next
    Ebook Download
    View all
    Learn
    View all