Sending emails with ASP .NET

In this article, you’ll see how sending email with ASP.NET is possible and then we’ll go deeper to see how you can use HTML emails or include attachments.

I can’t imagine a complete website that hasn’t got a function to email someone, either the user when he registers or the administrator when someone contacts him through the website. No doubt, ASP.NET must have a class that can be used to send emails. Actually, there are two: SmtpMail and MailMessage.

In this article, you’ll see how sending email with ASP.NET is possible and then we’ll go deeper to see how you can use HTML emails or include attachments.

But first you’ll need to check if the Microsoft SMTP Service is turned on. To do this either open the Internet Services Manager directly or open Computer Management and Navigate to Internet Information Services -> Default SMTP Virtual Server and checkout if the button with the ‘play’ icon on it is disabled, that means it is already started.

Microsoft SMTP Service is the one we’ll use in this article, but you can as well use something more professional like the Microsoft Exchange Server. The reason why we’re using the first mentioned is because it’s included in Windows XP Professional and Windows 2000.

Testing Microsoft SMTP Service

It’s better to test it before using it in an ASP.NET application so if it doesn’t work, at least you can’t blame it on the web application. It’s incredible how easy it is to test this service.

By default, your folder for IIS files is located somewhere in C:\Inetpub. Also the folders that Microsoft SMTP Service uses are located here, more exactly the folder is called mailroot. The SMTP service uses these folders to store email messages. You can see a total of seven folders, the most important one for sending email is Pickup – open this folder. Now start the best editor possible: Notepad. In it paste the following lines:

To: [email protected]

From: [email protected]

Subject: Hello Andrei
I'm testing the Microsoft SMTP Service, didn't meant to bother.

You recognize the typical fields used to send email, to, from and subject and below the content of the email. In the From field you can enter any email address you want, even if it’s not yours. Now save this file in the Pickup folder using any name you wish, test.txt for example. The next second it should disappear… that’s because it was sent. If you leave the fields unchanged, it will send it to my email address and I’ll know that you’re reading my article right now.

Now that we settled this out, we can start developing. Fire up Microsoft Visual Studio .NET and start a new ASP.NET Web Application.

To the WebForm add four TextBoxes, the last one should have the property TextMode set to MultiLine (makes it a textarea). Also, add a button to the recipe. The entire layout should look like this:

I recommend setting the ID property of each textbox to txtFrom, txtTo, txtSubject and txtContent and for the button btnSend so that we don’t confuse them.

Now we get to my favorite part, coding. Open WebForm1.aspx.cs, the first thing we must do is import the namespace where SmtpMail and MailMessage classes are:

using System.Web.Mail;

Next, create a new instance of the MailMessage class:

protected MailMessage MMsg;

Double click the button on the WebForm to get to the btnSend_Click() event. Inside paste the following code:

MMsg = new MailMessage();

MMsg.From = txtFrom.Text;

MMsg.To = txtTo.Text;

MMsg.Subject = txtSubject.Text;

MMsg.Body = txtContent.Text;

SmtpMail.Send(MMsg);

We create a new instance of MailMessage on the first line and then we set several properties needed to send the message. The last line actually sends the email by using the Send() method of SmtpMail.

Sometimes when you upload your website to a webhost you’ll have to change the SMTP server. This can be done by changing the SmtpServer property:

SmtpMail.SmtpServer = "localhost";

localhost is the name of the SMTP server but you could as well enter an IP.

If your SMTP server requires authentication, before using the Send() method, supply the required information as shown below:

// Username


MMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "andrei");


// Password


MMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "mysecretpassword");


// SMTP Server


MMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserver", "mail.geekpedia.com");


// Port


MMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", 25);


// These don't normally need changing


MMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);


MMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusing", 2);


MMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout", 10);


MMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", false);

As you can see, sending emails is a very simple task in ASP.NET and can be done just by setting a few properties. The application is now fully functional and you can compile it, run it, fill in the fields and press btnSend.

There are some other properties you can set, like CC (Carbon Copy) or BCC (Blind Carbon Copy) which are both well known in email messaging.

Another property you might be interested in is Priority, which can set the message priority to Low, Normal or High.

Here’s an example of how to use it:

MMsg.Priority = MailPriority.High;

We all know that email messages can be either plain text or HTML. By default they are sent as plain text, but you can change this by setting the BodyFormat property to Html:

MMsg.BodyFormat = MailFormat.Html;

However there’s more about HTML email, and that’s covered in the next section.

Sending HTML emails

In most cases plain text may do the job, but sometimes you will want to send HTML email, for sending a newsletter perhaps. We saw earlier how you can change from plain text to HTML email just by setting a property but there’s more than this as you will see here. First let’s send a simple HTML email message by using HTML tags in the body of the email. Be sure the BodyFormat property is set to MailFormat.Html and then set the Body property like in the following example:

MMsg.Body = "<HTML><HEAD><TITLE>Hello Andrei</TITLE></HEAD><BODY><h3>Hello Andrei</h3><p><font face='Verdana' size='2'>Just testing...</font></p></BODY></HTML>";

Here’s how the message looks in Outlook 2003:

As expected, the HTML tags do their job and format the message.

Using HTML you can also include graphics and links just like in a webpage. In regard to the graphics and links I should mention that you should use the complete path and not relative URLs. For example instead of img/SomeIcon.gif you would have to use http://www.somedomain.com/img/SomeIcon.gif.

That doesn’t represent a problem in short messages that have a link or two or a graphic or two, but when you want to format the entire email message to look like a webpage and you have tens of graphics, using complete paths gets annoying. Microsoft thought of that so there’s a solution – the UrlContentLocation property – used like in the following example:

MMsg.UrlContentLocation = @"http://www.somedomain.com/img/";

Now you can simply use SomeIcon.gif as the path of the graphic. The same applies to links to different pages on your website.

Sending emails with attachments

Email attachments are sent just as easy with the help of the MailAttachment class and its two properties.

First, we have to create a new instance of this class:

protected MailAttachment MAtt;

And then in the btnSend_Click() event, just before the SmtpMail.Send() method, paste the following lines:

MAtt = new MailAttachment(@"C:\Document.pdf");

MMsg.Attachments.Add(MAtt);

The path is set when creating the new instance of MailAttachment, and after that the mail attachment object is added to the attachments list of the email message (because you can have multiple attachments simply by using Add() multiple times with different files).

However, normally the visitor will type the path to the file he wants, or even better, he can browse and select the file he want so send as attachment. Open WebForm1.aspx and inside Form1, just above the button that sends the message, add the following line:

<input id="txtFile" type="file" runat="server" size="32">

This control adds a textbox and a button to the webform which you can use to browse to the file you want. Here’s an example of a completed form.

Now don’t forget to change the path to the attachment to reflect the content of the textbox and also before adding the attachment the application should check to see if the user specified any attachment at all, because if the textbox is empty an exception will occur.

if(txtFile.PostedFile != null)

{

   MAtt = new MailAttachment(@txtFile.PostedFile.FileName);

   MMsg.Attachments.Add(MAtt);

}

Even if we get a little bit off-topic, you might be interested in limiting the allowed size of the attachment.

To limit the allowed size of the attached file to 1 MB (1024 bytes) you have to retrieve the size of the file, so here’s the modified if condition that does exactly this:

if(txtFile.PostedFile != null && txtFile.PostedFile.ContentLength <= 1024)

{

   MAtt = new MailAttachment(@txtFile.PostedFile.FileName);

   MMsg.Attachments.Add(MAtt);

}

There’s not much more to say about the SmtpMail and MailMessage class, the methods and properties listed here are the ones you’ll need most of the time.

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top