Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Sending Emails from ASP.NET



A common task that most ASP.NET applications share is sending notification emails to registered users for application specific events and to the site administrator when something goes wrong. But how would send emails from within an ASP.NET application? The task is not different for the ASP.NET platform and requires the same classes and techniques you would use from within, say, a desktop application. All the machinery is in the System.Net.Mail namespace.

The first thing you do is preparing a mail message. The class that represents a mail message is MailMessage. The constructor takes up to four parameters: the sender's address, the receiver's address, the subject line of the message, and the body. There are four different constructors available and you can choose to specify these arguments (at the very minimum you indicate sender and receiver) as plain strings or through instances of a container class such as MailAddress.


MailAddress toAddress = new MailAddress(to);
MailAddress fromAddress = new MailAddress(from);

A MailMessage class can be further configured to specify encoding, alternate views of the message such as HTML, attachments and blind carbon copies. Is it possible to specify multiple receivers? You bet.

The MailMessage class provides properties like To, CC, and Bcc. These properties are implemented as instances of the MailMessageCollection class and let you add as many addresses as you need.


MailMessage msg = new MailMessage(fromAddress, toAddress);
msg.To.Add(address1);
msg.CC.Add(address2);

To set the subject and the body of the message you use ad hoc properties at any time. You can also set these properties through one of the constructors.


msg.Subject = theSubject;
msg.Body = theBody;

You can populate the Body property with any text you like. To send an attachment, instead, you need to resort to the Attachments collection. First, you define an Attachment object and make it point to a local file, a string or a stream.


Attachment data = new Attachment(file,
                     MediaTypeNames.Application.Octet);

You specify the content of an attachment by using the content type property on the constructor. The content type parameter indicates the MIME type header of the attachment. In addition, you can add time stamp information for the file. You do this via the ContentDisposition property on the Attachment class.


ContentDisposition disp = data.ContentDisposition;
disp.CreationDate = GetCreationTime(file);

Finally, to add the file to the message, you use the Addmethod and the Attachments collection.

	
msg.Attachments.Add(data);

The final step consists in the physical submission of the message to an SMTP server. The SmtpClient class receives the address of the SMTP server through the constructor and sends the message via its method Send.


SmtpClient mail = new SmtpClient("your-smtp-server");
mail.Send(msg);

The SmtpClient class also supports credentials to be used when the server requires the client to authenticate before accepting email on the client's behalf.


mail.Credentials = CredentialCache.DefaultNetworkCredentials;

Credentials can also be specified using the web.config file. In particular, you use the <mailSettings>element. Note that any information stored in the configuration file gets overridden once you use the Credentials property programmatically.

The Send method works synchronously, but an asynchronous version also exists. The method SendAsync sends the message and returns. The SendCompleted event is raised when the asynchronous operation completes. In an ASP.NET scenario, though, the asynchronous method is arguably an ideal solution. In ASP.NET page you might want to send all messages synchronously and return an updated user interface when you're done. The classes in the System.Net.Mail namespace offer a simple and effective programming model for sending emails programmatically.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.