Using email in ASP.Net applications

I know that this topic is also well documented in the web. But I decided to have a go, after so many people ask me the same question

"How can I send emails from asp.net web applications?"

I know we live in the era of Microsoft Messenger,Skype,Twitter,facebook and RSS. All these platforms-technologies are proven alternatives but nothing has eclipsed

the classic email protocols and the use of email as the primary means of direct communication over the web.

I will use a step by step example with screenshots as usual.

You can use any of the versions of Visual studio (VS 2005,VS2008,VS2010 - express editions work fine as well).

I will use VS 2010 Ultimate edition and C# as the .Net language of choice.

The main methods we are going to use reside in the System.Net.Mail class. Have a look here for an excellent resource on System.Net.Mail.

1) Create a new website with the VS version that you have and name it as you want.

2)  Now, before we begin to send any email we need to configure the smtp settings to indicate which mail server you will be talking to.Some people argue that you can set these settings programmatically.

My humble opinion is to set the settings for email sending declaratively in the web.config and more specifically in the mailSettings element.

So in the web.config type the following - obviously in your case you fill in your specific settings

<system.net>

<mailSettings>

<smtp from="nikos.kantzelis@mycompany.com">
<network host="smtp.mycompany.com" port="25" userName="fofo" password="liverpool13" defaultCredentials="false"/>
</smtp>
</mailSettings>	
</system.net>

 

3) I have added a new web form in my website. I have named it "SendMail.aspx". Set it as the start page. Add a reference to the System.Net.Mail namespace.

The main classes we are going to use are MailMessage and SmtpClient. Now let's see how to send a plain-text email from an asp.net page.

4) In the Page_Load event handling routine of the SendMail.aspx page,  type ( obviously in your case you fill in your specific settings where applicable)

 

MailMessage m = new MailMessage();

m.From = new MailAddress("nkantzelis@q-training.gr");
m.To.Add("nikolaosk@hotmail.com");
m.Subject = "Liverpool trip";
m.Body = "Are we going to Anfield this year?";

SmtpClient sc = new SmtpClient();
sc.Send(m);

 

5) Run your application and if everything is configured correctly the email will be sent.

6) Most people that receive emails, probably your clients, would want their email to be sent as HTML formatted.

You might think that the easiest way to send an HTML-formatted email is just to write some markup into the body of your email.

The problem with this approach is that not all email clients are able to display HTML.

Users of some clients won’t be able to read your message easily because they’ll have to "go" through raw HTML to find it.

So the best way is to suit all clients. So the HTML version of the message is going to be as an alternative view.

 In the Page_Load event handling routine comment out all the lines of code and type

 

 MailMessage m = new MailMessage();
 m.From = new MailAddress("nkantzelis@q-training.gr");
 m.To.Add("nikolaosk@hotmail.com");
 m.Subject = "Liverpool trip";
 m.Body = "Are we going to Anfield this year?";
 AlternateView html = AlternateView.CreateAlternateViewFromString(
 "Are we going to <b>Anfield</b> this year?"null,
 "text/html");
 m.AlternateViews.Add(html);

 SmtpClient sc = new SmtpClient();
 sc.Send(m);

You can read more about the alternative view class here.

 Run your application and if everything is configured correctly the email will be sent.

7) When you want to send content such as a Microsoft Word file, or a PDF file, you’ll need to send that file as an attachment to a mail message.

Comment out all the code you have typed so far. In the Page_Load event handling routine type

  MailMessage mail = new MailMessage();
  mail.From = new MailAddress("nkantzelis@q-training.gr");
  mail.To.Add("nikolaosk@hotmail.com");
  mail.Subject = "Liverpool History";
  mail.Body = "Liverpool has won so far 18 championships";

  string path = Server.MapPath("~/test.doc");
  mail.Attachments.Add(new Attachment(path));

  SmtpClient client = new SmtpClient();
  client.Send(mail);

 

The code above sends an attachment a file named test.doc that exists in the root of the web application.

Notice that we attach the file by creating an Attachmentobject and adding the object to the mail’s Attachments collection

Run your application and if everything is configured correctly the email with the attachment will be sent.

8) But what if the remote SMTP server is down or not responding?

What if the SMTP server is responding extremely slowly?

Your page won’t finish loading or displaying until the email is sent, or until an error is returned from the SMTP server.

Imagine the dissapointment-frustration on the user's end. They will brand your application obsolete and unresponsive.

So in our final part of this post we will discuss on how to send emails from an asp.net page asynchronously.

The first thing to notice is to enable the boolean Async directive in the Page element.

So the Page directive becomes

<%@ Page Language="C#" AutoEventWireup="true" 
CodeFile="SendMail.aspx.cs" Inherits="SendMail"  Async="true" %>

 In the top of the SendMail.aspx.cs add a reference to these namespaces.

using System.ComponentModel;
using System.Diagnostics;

Sending email asynchronously is as easy as setting up a delegate and calling the SendAsync method.

In the Page_Load event handling routine comment out all the lines of code and type

 MailMessage m = new MailMessage
("nkantzelis@q-training.gr""nikolaosk@hotmail.com""Liverpool""You will never walk alone.");

 SmtpClient sc = new SmtpClient();
 sc.SendCompleted += new SendCompletedEventHandler(MailSendCompleted);
 sc.SendAsync(m, m);

Just after the end of the Page_Load event handling routine type the code

 public static void MailSendCompleted(
                     object sender, AsyncCompletedEventArgs e)
    {
        MailMessage mail = e.UserState as MailMessage;
        if (e.Cancelled)
        {
            Debug.Write("Email to " + mail.To + " was cancelled.");
        }
        if (e.Error != null)
        {
            Debug.Write("Email to " + mail.To + " failed.");
            Debug.Write(e.Error.ToString());
        }
        else
            Debug.Write("Message has been sent.");
    }

 

Within the handler, we need to check the Cancelled and Error properties of the AsyncCompletedEventArgs object to ensure that nothing went wrong.

Run your application and if everything is configured correctly the email will be sent.

Leave a comment if you would like me to email you the code.

Hope it helps!!

2 Comments

Comments have been disabled for this content.