Sending Web eMail in ASP.NET

Share this article

One of the most common functionalities used in Web development is sending email from a Web page. Before you ask, I’ll give you a couple of reasons why you might want to send email from your Web application:

  • create a “give us your feedback” Web page

  • implement a “forgotten password” script that sends a password to the user’s email account

  • send an automatic welcome email to your new newsletter subscriber

  • send automatic email update notifications

  • send automatic email notifications whenever an error occurs in your Web application

    Of course there are many more situations where it’s appropriate to send email from your Web applications, and it’s up to you to determine exactly how and where you’re going to implement this functionality.

    Enter: .NET

    The .NET framework makes the task of sending email from a Web page unbelievably easy and I’ll show you how to do it in a matter of minutes. This article presumes that you have a basic understanding of how .NET and ASP.NET works.

    1. Import the namespace, and create instances of required classes

    We are going to use the SmtpMail and MailMessage classes, which belong to the System.Web.Mail namespace. In order to use them, we will need to import the System.Web.Mail namespace like this:

    <%@ Import Namespace="System.Web.Mail" %>

    The MailMessage class provides properties and methods for constructing an email message. To build our email message we need to create an instance of this class:

    Dim objMail As New MailMessage()

    2. Set the properties of the object

    Next, we have to set all the properties of the objMail object:

    ' The email address of the sender 
    objMail.From = "yourname@yourdomain.com"

    ' The email address of the recipient
    objMail.To = "recipientname@somedomain.com"

    ' The email address of the Cc recipient
    objMail.Cc = "name1@anotherdomain.com"

    ' The email address of the Bcc recipient
    objMail.Bcc = "name2@anotherdomain.com"

    ' The format of the message - it can be MailFormat.Text
    or MailFormat.Html
    objMail.BodyFormat = MailFormat.Text

    ' The priority of the message  - it can be MailPriority.High,
    MailPriority,Normal or MailPriority.Low
    objMail.Priority = MailPriority.High

    'The subject of the message
    objMail.Subject = "My first ASP.NET email"

    'The message text
    objMail.Body = "This is my first email sent via
    ASP.NET. It was easier than I thought :)"

    After all the properties (some of them are optional) of our new email message are set properly, the only thing that’s left to do is send the message.

    3. Send the Message

    If you have experience sending email from classic ASP script with CDONTS you might think that the MailMessage class has method Send or something similar. Well, the way ASP.NET sends email messages is a little different from ASP.

    We need to use the static method Send of the SmtpMail class, passing in our objMail instance. You might be asking “what’s a ‘static method’?” A static method is one that’s not associated with an instance of a type. An example of an instance of a type is our objMail object. It is illegal to reference a static member of a class through an instance. The proper way to do it is:

    SmtpMail.Send(objMail)

    If you want to specify an SMTP server that’s different than the default, you’ll need to set the SmtpServer property of the SmtpMail class:

    SmtpMail.SmtpServer = "smtp.your-server.com"
    Summary

    In summary, to send an email from your ASP.NET page, you need to:

  • import the System.Web.Mail namespace in your ASP.NET page

  • create an instance of the MailMessage class

  • set all the properties of the MailMessage instance

  • send the message with SmtpMail.Send method

    And finally, to get you started, here’s the complete, functional code for an ASP.NET page that sends the user’s feedback via email to the Webmaster:

    <%@ Page Language="VB" EnableSessionState="False"  
    EnableViewState="False" Trace="False" Debug="False"%>
    <%@ Import Namespace="System.Web.Mail" %>  
    <script language="VB" runat=server>  

    Sub Page_Load(Sender as Object, E as EventArgs)  
       If Page.IsPostBack Then
           lblResponse.Text = "Your email has been sent."
       End If
    End Sub  
       
    Sub btn_Click(sender as Object, e as System.EventArgs)
     If  Request.Form("Email") <> "" Then
       Dim objMail As New MailMessage()
       objMail.From = "your_name@yourdomain.com"
       objMail.To = Request.Form("Email")
       objMail.Subject = Request.Form("Subject")
       objMail.Body = Request.Form("Message")
       objMail.BodyFormat = MailFormat.Text
       SmtpMail.SmtpServer = " smtp.your-server.com"
       SmtpMail.Send(objMail)
     Else
       lblResponse.Text = "Please enter an email address."
     End If
    End Sub

    </script>  
    <html>
    <head>
    <style>
    .main {font-family:Verdana; font-size:12px;}
    .title {font-family:Verdana; font-size:18px; font-weight:bold;}
    </style>
    </head>
    <body>
    <span class="title" align="center">Send email from  
    an ASP.NET page</span>

    <br><br><asp:Label class="main" id="lblResponse"  
    runat="server"/>

    <form method="POST" name="MainForm" runat="server">
    <table>
     <tr>
       <td class="main" align="right">Email:</td>
       <td class="main"><input type="text"  
       class="main" name="Email" value=""></td>
     </tr>
     <tr>
       <td class="main" align="right">
       Subject:</td>
       <td class="main"><input type="text"  
       class="main" name="Subject" value=""></td>
     </tr>
     <tr>
       <td class="main" align="right"  
       valign="top">Message:</td>
       <td class="main"><textarea name="Message"  
       cols="50" rows="8"></textarea></td>
     </tr>


     <tr>
       <td class="main">&nbsp;</td>
       <td class="main"><input type="Submit"  
       id="btnSubmit" OnServerClick="btn_Click" value="Send"  
       runat="server" /></td>
     </tr>
    </table>
    </form>
    </body>
    </html>
  • Frequently Asked Questions (FAQs) about Sending Web Email in ASP.NET

    How can I send an email in ASP.NET using C#?

    Sending an email in ASP.NET using C# is a straightforward process. You need to use the System.Net.Mail namespace, which contains classes for sending emails. The main classes are MailMessage and SmtpClient. MailMessage represents an email message and SmtpClient sends an email message. You can set the properties of the MailMessage object like From, To, Subject, Body, and then call the Send method of the SmtpClient object to send the email.

    How can I send an email with an HTML body in ASP.NET?

    To send an email with an HTML body in ASP.NET, you need to set the IsBodyHtml property of the MailMessage object to true. This will allow you to use HTML tags in the Body property of the MailMessage object. You can then format the body of the email using HTML tags.

    How can I add images to the email body in ASP.NET?

    To add images to the email body in ASP.NET, you can use the LinkedResource class in the System.Net.Mail namespace. You need to create a LinkedResource object for each image, set the ContentId property to a unique identifier, and then add the LinkedResource object to the AlternateViews collection of the MailMessage object. In the HTML body of the email, you can reference the image by its ContentId.

    How can I send an email using ASP.NET Core?

    In ASP.NET Core, you can use the Microsoft.Extensions.DependencyInjection namespace to inject the IEmailSender service into your controller. The IEmailSender service provides a SendEmailAsync method that you can use to send an email. You need to configure the SMTP settings in the appsettings.json file.

    How can I send an email using ASP.NET Web API?

    To send an email using ASP.NET Web API, you can create a controller that inherits from the ApiController class. In the controller, you can create a POST method that accepts an Email model as a parameter. The Email model should contain properties like From, To, Subject, Body. In the POST method, you can use the MailMessage and SmtpClient classes to send the email.

    How can I handle errors when sending an email in ASP.NET?

    When sending an email in ASP.NET, you can use a try-catch block to handle any errors that may occur. The SmtpException class in the System.Net.Mail namespace represents an exception that is thrown when the SmtpClient is unable to send an email. You can catch this exception and handle it appropriately.

    How can I send multiple emails in ASP.NET?

    To send multiple emails in ASP.NET, you can create a list of MailMessage objects and then use a foreach loop to send each email. You can use the same SmtpClient object to send all the emails.

    How can I send an email with attachments in ASP.NET?

    To send an email with attachments in ASP.NET, you can use the Attachment class in the System.Net.Mail namespace. You need to create an Attachment object for each file, and then add the Attachment object to the Attachments collection of the MailMessage object.

    How can I send an email with a high priority in ASP.NET?

    To send an email with a high priority in ASP.NET, you can set the Priority property of the MailMessage object to MailPriority.High. This will mark the email as high priority in the recipient’s email client.

    How can I send an email asynchronously in ASP.NET?

    To send an email asynchronously in ASP.NET, you can use the SendMailAsync method of the SmtpClient object. This method sends an email asynchronously, which means that your application can continue executing other code while the email is being sent.

    Peter TodorovPeter Todorov
    View Author

    Peter runs a Windows hosting company www.ASP-Hosting.ca, which offers affordable ASP and ASP.NET hosting. He started recently www.ASPdev.org featuring ASP and ASP.NET articles and tutorials.

    Share this article
    Read Next
    Get the freshest news and resources for developers, designers and digital creators in your inbox each week
    Loading form