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.

Listing 15.27. 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 sender.Send(msg);

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@domain.com


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.

Listing 15.28. 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 15.13 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.

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


Figure 15.14 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.

Figure 15.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.


Listing 15.29. 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.Attachments.Add(attach); msg.Body = "Please find the attached file " + fileName; SmtpClient sender = new SmtpClient(serverName); sender.Credentials = CredentialCache.DefaultNetworkCredentials; sender.Send(msg);

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.

Listing 15.30. 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.Attachments.Add(attach); msg.Body = "Please find the attached file " + fileName; SmtpClient sender = new SmtpClient(serverName); sender.Credentials = CredentialCache.DefaultNetworkCredentials; sender.Send(msg);

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

Figure 15.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 15.16, a file containing the Web page retrieved earlier in this chapter is chosen.

Figure 15.16. Selecting an existing file from disk


Figure 15.17 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.

Figure 15.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 15.18), so that the source is a dynamically generated array of bytes rather than an existing file.

Figure 15.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 15.19, you can see that this is PaintShop Pro.

Figure 15.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 http://www.corel.com/.




ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net