Mail Classes

Sending E-Mail with the System.Net.Mail Classes

One extremely useful and often-required feature in commercial and hobbyist Web sites is the ability to send e-mail automatically. The System.Net.Mail namespace contains all the classes you need for this, although MailMessage, Attachment, and SmtpClient are the ones you will use most often. The technique is to create an instance of the MailMessage class, set all the properties you require on this class, add any attachments you want to send, and then call the Send method of the SmtpClient class to generate the message and pass it to your mail server.

Sending Text and HTML E-Mail Messages

To send a text message, you use code like that shown in Listing 15.27. The "to" and "from" addresses are String values in this case, as are the Subject and Body. There are several overloads of the constructor for the MailMessage class, and you can set the To and From properties instead of providing them in the constructor. Other properties of the MailMessage class include Cc, Bcc, ReplyTo, Priority, and DeliveryNotificationOptions. If you use HTML for the body of the message, set the IsBodyHtml property to true to indicate this, ensuring that the recipient receives it as HTML.

Sending a Simple Text E-Mail Message

// create the email message
MailMessage msg = new MailMessage(emailFromAddr, emailToAddr);
msg.Subject = "Auto-generated by ASP.NET!";
// use the String passed to this routine as the message body
msg.Body = sourceString;
// specify the sender that will deliver the message using the
// local SMTP service. Alternatively can set up defaults in the
// <mailSettings> section of machine.config or web.config
SmtpClient sender = new SmtpClient(serverName);
// add default credentials for accessing SMTP server
sender.Credentials = CredentialCache.DefaultNetworkCredentials;
// send the message

For information on sending e-mail through a remote mail server that requires specific logon credentials, see the earlier section, Using a Remote SMTP Server.

You can also provide the e-mail addresses as instances of the MailAddress class instead of as a String. This class exposes the DisplayName, Host, and User properties as well as the Address (the e-mail address) property. Alternatively, you can use the standard format for a String e-mail address that contains a display name:

"Display name" [email protected]

To use multiple e-mail addresses for a property, separate them with a semicolon.

Validating E-Mail Addresses

It is a good idea to validate any String e-mail addresses you use when sending messages automatically. An easy way is to use the Regex (regular expression) class from the System.Text.RegularExpressions namespace. Like all the other tasks you have met in this chapter, .NET makes it easy to use regular expressionsthe hardest part is in understanding the actual expression. Listing 15.28 shows how the example application validates e-mail addresses you enter in the page, or the e-mail address you specify as the sender when you configure the application.

Validating E-Mail Addresses Using a Regular Expression

// validate the email addresses using a regular expression
Regex rx = new Regex(@"([a-zA-Z0-9_\-\.]+)@(([a-zA-Z0-9\-]+\.)+)"
                    + "([a-zA-Z0-9]{2,4})");
// test against the two email addresses
if (! rx.IsMatch(emailToAddr))
  throw new Exception("Email 'To' address is not valid.");
if (!rx.IsMatch(emailFromAddr))
  throw new Exception("Email 'From' address is not valid.");

Figure shows the example page where the selected input is a collection of values (which, as you saw earlier, returns a small text string) and the option to e-mail the file to the specified recipient is enabled.

13. Sending a collection of values as an e-mail message as well as to a disk file

Figure shows the e-mail after receipt. You can see the text string in the body and the subject that wasas it saysauto-generated by ASP.NET.

14. A text e-mail sent from the example application

Sending E-Mail Messages with Text Attachments

Sending e-mails that have an attachment is more complex than sending simple text-only or HTML e-mails, but it is not difficult. The Attachments property of the MailMessage class can hold a collection of Attachment instances, each defining an attachment for the e-mail. The Attachment class has properties that define the name, encoding, and content type of the attachment. You can declare these values when you create an Attachment using one of the many constructors, or afterwards by setting the properties.

If the attachment is a file on disk, you simply specify the path and name file in the Attachment constructor, and optionally a ContentType (MIME type) value. If the attachment is a String value, you can use the static CreateAttachmentFromString method of the Attachment class to generate the attachment.

You can also create attachments from a stream, which provides the flexibility required to generate binary attachments. In this case, you use one of the overloads of the Attachment class that accepts a stream. You can optionally provide the name of the file that the attachment represents and the MIME type.

Listing 15.29 summarizes the code used in the example to send text attachments. The MediaTypeNames class allows you to specify a whole range of MIME types, including Text.Html ("text/html"), Text.Plain ("text/text"), Text.Xml ("text/xml"), Image.Gif ("image/gif"), Image.Jpeg ("image/jpeg"), a whole range of Application types such as "application/zip," and more. After creating the attachment, the code uses the Add method of the AttachmentCollection class (exposed by the Attachments property of the MailMessage class) to add the attachmentbefore sending the message.

Note that the ContentType and the MediaTypeNames classes are in the System.Net.Mime namespace, which you must import in order to use these classes.

Creating an E-Mail with a Text Attachment from a String

// specify the content type and file name
ContentType cType = new ContentType();
cType.MediaType = MediaTypeNames.Text.Plain;
cType.Name = fileName;
// create an attachment from the source String
attach = Attachment.CreateAttachmentFromString(sourceString, cType);
// create the email message
MailMessage msg = new MailMessage(emailFromAddr, emailToAddr);
msg.Subject = "Auto-generated by ASP.NET!";
// add the attachment to the message
msg.Body = "Please find the attached file " + fileName;
SmtpClient sender = new SmtpClient(serverName);
sender.Credentials = CredentialCache.DefaultNetworkCredentials;

Sending E-Mail Messages with Binary Attachments

When sending a binary attachment that is not stored as a disk file, you must provide the content as a stream. The code in the example page, summarized in Listing 15.30, creates a MemoryStream over the array of Bytes that contains the data to send. After setting the current position pointer to the start of the file, the code creates a new Attachment using the MemoryStream and the proposed file name. The remainder of the code, as in Listing 15.29, adds the Attachment to the MailMessage, specifies the other details of the message, and sends it.

Creating an E-Mail with a Binary Attachment from a Byte Array

// get a stream over the array of bytes
MemoryStream outStream = new MemoryStream(sourceBytes);
outStream.Position = 0;
// create the attachment, specifying the file name to be
// used as part of the ContentType to identify the file
attach = new Attachment(outStream, fileName);
// create the email message
MailMessage msg = new MailMessage(emailFromAddr, emailToAddr);
msg.Subject = "Auto-generated by ASP.NET!";
// add the attachment to the message
msg.Body = "Please find the attached file " + fileName;
SmtpClient sender = new SmtpClient(serverName);
sender.Credentials = CredentialCache.DefaultNetworkCredentials;

To see the whole process in action, Figure shows selection of an existing file to be e-mailed to the specified address and output within the page using a StringBuilder.

15. Selecting the options to send an existing file by e-mail

Selecting the Use an existing file option in the page automatically displays a list of drives, and you can navigate to an existing file and select it. In Figure, a file containing the Web page retrieved earlier in this chapter is chosen.

16. Selecting an existing file from disk

Figure shows the e-mail that the example generates. The existing file, a saved Web page, is attached to the message with the correct filename. Outlook also displays the filename using the appropriate icon. Double-clicking the file causes it to open in the browser just as you would expect.

17. The resulting e-mail with the Web page attached

You can select a different source type in the main application page, for example, the Graphic image option (see Figure), so that the source is a dynamically generated array of bytes rather than an existing file.

18. Specifying a graphic as the source of the e-mail attachment

Then send it as an e-mail attachment, open the e-mail in your e-mail client, and you will see the attached graphic file. Double-clicking this time opens the application designated for handling GIF filesin Figure, you can see that this is PaintShop Pro.

19. Viewing a graphic delivered in an e-mail message

The latest version of PaintShop Pro is available for trial or purchase from the Corel® Corporation Web site at

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows