Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Sending Emails Easily Using ASP.NET Helpers

0.00/5 (No votes)
10 Aug 2014 1  
This article explains how you can send emails using ASP.NET Web Helpers without having to work with connections.

Introduction

This article is an explanatory to the email sending feature built in ASP.NET using the .NET Web Helpers. This article explains how you can implement those classes inside your ASP.NET website and send the email to your clients using less code.

Background

In today's world, email sending is the base of almost everything. People like to send emails to their friends about the new stuff they just found on the web. They want to send emails to the Web Admins, Friends, etc. to tell what and how they're feeling.

This was handled using C# MailMessage class back then, but now ASP.NET has taken over the Internet related features and it is better to send the emails using ASP.NET's built-in WebMail class feature.

Many users are asking questions related to this problem. So that is why I want to write an article explaining this class and how you can use it and implement it in your own website to allow the users have this email feature.

Environment Requirements

Before you continue to send the emails, there are some things you need to take care of. This article was written using ASP.NET website which was developed using Microsoft WebMatrix. You can get your own copy of WebMatrix from the Microsoft's website for Web.

Once you download this software, you will get all the required softwares that are needed to run your website on your own computer for testing purposes. This software installs the Web Platform Installer, which does all the remaining job for you.

Once done, continue to the next steps.

What is ASP.NET WebMail

ASP.NET WebMail is a class, that works with the email stuff on your website. This class is a helper class, which as MSDN says, "is a component that simplifies web programming in ASP.NET Web Pages". It is a part of .NET Framework's Web Helpers class. You can access this class in many ways, if you're having a .cshtml page (the C# embedded HTML page) where all the classes and namespaces required are compiled within or you can also use this class using its direct class name and access it inside any .cs (C# Class) file.

System.Web.Helpers.WebMail;

This would enable this WebMail feature in your website. After this, you can easily access its properties and methods in your code and send the WebMail (email) from your website or your program software.

Like all other classes, WebMail also has some methods and properties that you can use and customize your service. The built-in members (properites) of the WebMail class are as follows:

  1. EnableSsl (bool)
    This property sets Secure Socket Layer to the email. Most of the SMTP servers ask for it. Today, while I was preparing for this article, I figured out gmail server requires it. Otherwise, it cancels the connection. Once you set it, you can work with it.
  2. From (string)
    This property sets the from field of the webmail. This is also the part of the email where the sender's email is shown.
  3. Password (string)
    This is the password for your user account from where you will be sending the email.
  4. SmtpPort (int)
    This is the port from where you will be connecting and then sending the email to your client on the server. Remember, mostly 25 can be used as its value. But you can also check for the documentation provided by the service provider to know about their port. Gmail accepts 25 server port too. I have always used it.
  5. SmtpServer (string)
    SmtpServer tells the WebMail about the server to connect to. You specify the service provided in this field.
  6. UserName
    The username you're having at the email service provider.

One thing I want to make clear here. There is a difference between From and UserName field. The difference is, UserName is used to connect to the server, where as From field is just passed as a String to the server to tell the From field only. UserName and Password are used to login to the server, they're the same that were provided to you while signing up. For example, my Gmail account is: justinxxxxx@gmail.com password ******, I would pass this to the UserName and Password fields and the From field can be my brother's email too or my company email, etc.

Do keep the above stated paragraph in mind!

Now let's talk about the methods provided by the WebMail class, as we know this is an email related class so there is only one method provided by it. It is:

public static void Send(
    string to,
    string subject,
    string body,
    string from,
    string cc,
    IEnumerable<string> filesToAttach,
    bool isBodyHtml,
    IEnumerable<string> additionalHeaders,
    string bcc,
    string contentEncoding,
    string headerEncoding,
    string priority,
    string replyTo
)

The only method this class provides is the Send method which is used to send the email. You don't need to configure this class or the instance you create like you did in the MailMessage you just pass the parameters and WebMail handles it all.

The only required parameters would be discussed here, remaining are just optional. Whether you provide them or not, WebMail doesn't care about it. One more thing, and it is the most interesting is that you don't need to keep the sequence in mind. You can pass them in any order, just remember to pass the first three parameters in order. Since they're required.

  1. to (string)
    This is the email address of the receiver.
  2. subject (string)
    The subject for the email being sent. A short message to describe the email.
  3. body (string)
    This is the parameter that has all of the email body content. You pass the entire HTML that would form the email body of the web mail in this parameter. You can attach images to the document you can stylize the HTML content using the HTML codes for bold, italic, etc.
  4. isBodyHtml (bool)
    Used to indicate that the HTML inside the body parameter should be rendered as an HTML markup instead of plain string.

The remaining parameters are not as much required and the email would be sent using just these parameters. Even though the isBodyHtml parameter was also not required one, but I thought it was worth mentioning.

Using the Code

You can download the attachment that has been attached to this article. It includes all the code required for you to test this article code and understand the process.

First of all, I have changed the location of the website to run the email page by default when the user tries to go to the main page. To code for it is as:

Response.Redirect("~/SendEmail");

Remove this if you want to build your project from the template I provided you with.

Moving on to the next step is the usage of a simple HTML form element to accept the data from the user and pass it to the server for processing purposes. For that, I have had a simple SendEmail.cshtml page inside the root folder and I have had written the very basic form as:

@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Send email";
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <h2>Send basic Email - ASP.NET WebMail helper</h2>
  <form method="post" action="ProcessFile.cshtml">
    <div>
        Your name:<br />
        <input type="text" name="customerName" />
    </div>

    <div>
        Your email address: <br />
        <input type="text" name="customerEmail" />
    </div>

    <div>
        Subject line: <br />
        <input type="text" size= 30 name="subjectLine" />
    </div>
      <div>
          Message: <br />
          <textarea name="message" style="width: 300px;"></textarea>
      </div>
    <div>
        File to attach: <br />
        <input type="text" name="fileAttachment" />
    </div>

    <div>
        <input type="submit" value="Submit" />
    </div>
  </form>
</body>
</html>

You can see that the HTML is pretty simple and understandable, you can add the details to the form like your name, your email address your message and then if you want to attach you can attach the file to the WebMail. As I have already mentioned in the above block, you don't need to be passing any parameter if there is no attachment at all. All you need to pass is the very required object like to, subject, body only. You can pass or not pass the remaining items.

The action attribute for this form is ProcessFile.cshtml which is the new file where you will be redirected as this is the job of the action attribute to pass the form data to the next page where you will handle the server-side coding. You can ignore this attribute if you're posting the code on the very page. Because it is the current page location.

The HTML codes for this are as:

@{
    Layout = "~/_SiteLayout.cshtml";

    var customerName = Request["customerName"];
    var customerEmail = Request["customerEmail"]; 
    var customerRequest = Request["customerRequest"];
    var subjectLine = Request["subjectLine"];
    var message = Request["message"];
    var fileAttachment = Request["fileAttachment"];
    var with = "with";
    var errorMessage = "";

    // use a try catch block and send the email
    try {
        // Initialize WebMail helper
        WebMail.SmtpServer = "your-smtp-server";
        WebMail.SmtpPort = 25;
        WebMail.UserName = "your-username";
        WebMail.Password = "password";
        WebMail.From = "your-email-address";
        WebMail.EnableSsl = true;

        // Create array containing file name
        var filesList = new string [] { fileAttachment };

        // Attach file and send email
        // if there is no link to file then send email
        // without any attachment
        if(fileAttachment == null || fileAttachment.IsEmpty()) {
            WebMail.Send(to: customerEmail,
            subject: subjectLine,
            body: "From: " + customerName + "\n\nHis message: " + message);
            with = "without";
        } else {
            // otherwise, send email with file attached
            WebMail.Send(to: customerEmail,
            subject: subjectLine,
            body: "From: " + customerName + "\n\nHis message: " + message,
            filesToAttach: filesList);
        }
    }
    catch (Exception ex ) {
        // errorMessage is the message provided by the exception.
        errorMessage = ex.Message;
    }
}
<!DOCTYPE html>
<html>
<head>
    <title>Request for Assistance</title>
</head>
<body>
  <p>Sorry to hear that you are having trouble, <b>@customerName</b>.</p>
    @if(errorMessage == "")
    {
        <p><b>@customerName</b>, thank you for your interest.</p>
        <p>An email message has been sent to our customer service
           department <b>@with</b> the <b>@fileAttachment</b> file attached.</p>
    }
    else
    {
        <p><b>The email was <em>not</em> sent.</b></p>
        <p>Please check that the code in the ProcessRequest page has 
           correct settings for the SMTP server name, a user name, 
           a password, and a "from" address.
        </p>
        <p>The following error was reported:</p>
        <p><em>@errorMessage</em></p>
    }
</body>
</html>

This page just accepts the data from the Form, and then after that code block, it initializes the WebMail class. This class is static so there is no need to create a new instance of this class as:

WebMail webMail = new WebMail();

..like you did with the MailMessage class. This feature makes it really very easy to work with. You are required to edit the WebMail properties in order for the code to work and the server to accept the request of yours to send the email. Before you move any further, I would like to ask you to edit the code to avoid further errors and head scratching.

Then you pass your credentials, and the parameters to it and it sends the email to the client or to whomever the email must be sent.

The HTML on this page is rendered according to the situation of the email. If the email is sent the HTML says, Ok wait, we'll get back to you we've got your email and if the email is not sent, it says, Sorry, there was an error and we're not able to receive the email.

You will notice a try catch block in my code. That is because, when working with the emails you must use it. When you connect to a new server, you get an exception if it is not connectable. You get an error if there is any certificate error. You get an error if parameter is missing. You get an error for almost everything that is why I have used the email sending thing inside the Try Catch block this way if any error occurs, instead of showing an IIS generated error page I would see a message denoting email not sent and another paragraph telling me what the error was.

That is why, using try catch where an exception might get raised at many stages is a good practice since a broken UI is a bad UX.

Screenshots for the test of this article are as follows:

Email form

This is the main page, the form of the email sending application. You can see it includes all the basic fields required and an additional field for the File Name. I will explain it later in the last image. Next step it to work with the errors.

Error sending email

If there is any error in the email sending process, the catch block would execute and you'll be informed of the error. First of all, you should think about the WebMail properties settings and if everything is OK, then have a look at the error that you have just made. It would tell you that the email wasn't sent, please check the codes.

Email sent without attachment

This is the HTML shown if the email was sent normally. Great job!

But you should see that there was no file attached. It is because you didn't care to attach any file (left the File Name field empty). It is recorded using...

if(fileAttachment == null || fileAttachment.IsEmpty()) {

block and executes only the email (text-only) part and no attachment.

Email sent with attachment

Now, this time you will notice there is an extra HTML text inside the page. This is because when you sent the email, you also attached the File (by filling in the entire location of the file in the File System). You cannot just write the name of the file "HelloWorld.txt", you need to provide the entire link of the file on file system, such as "C:\Users\<username>\Documents\HelloWorld.txt" and ASP.NET would attach this file to the email.

Adding friendly From field

Most of the companies use their own name in the From field with a little grey field for their email address. Showing the Name of the company seems more user friendly since the user would get idea of the email sender by reading the name faster as compared to when reading the email address of the company.

To add this functionality, just edit the .From field of the WebMail class. And make it:

WebMail.From = "\"Afzaal Ahmad Zeeshan\" <hello@example.com>";

This will now show Afzaal Ahmad Zeeshan to the user instead of the email address, hello@example.com. This is a more user friendly way of sending the email.

Points of Interest

I learned how to attach the file attachments to the WebMail class until today I didn't know this. Today, when I started writing this article, I went back to WebMatrix and created a new project and after that, I just tried passing a simple String link to the file, and the file was sent. :) So, maybe the elders were true while saying "Teaching others is a way to increase your own knowledge".

http://msdn.microsoft.com/en-us/library/system.web.helpers.webmail(v=vs.111).aspx (WebMail class MSDN)

History

  • Second version: Added the support to allow friendly From field, instead of email address
  • First version of the post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here