11.14 Send E-Mail Through SMTP


Problem

You need to send e-mail to an e-mail address using a Simple Mail Transfer Protocol (SMTP) server.

Solution

Use the SmtpMail and MailMessage classes in the System.Web.Mail namespace.

Discussion

The classes in the System.Web.Mail namespace provide a bare-bones wrapper for the Collaboration Data Objects for Windows 2000 (CDOSYS) component. They allow you to compose and send formatted e-mail messages using SMTP.

Using these types is easy. You simply create a MailMessage object, specify the sender and recipient e-mail address, and place the message content in the Body property.

 MailMessage myMessage = new MailMessage(); myMessage.To = "someone@somewhere.com"; myMessage.From = "me@somewhere.com"; myMessage.Subject = "Hello"; myMessage.Priority = MailPriority.High; myMessage.Body = "This is the message!"; 

If you want, you can send an HTML message by changing the message format and using HTML tags.

 myMessage.BodyFormat = MailFormat.Html; myMessage.Body = @"<HTML><HEAD></HEAD>" +    @"<BODY>This is the message!</BODY></HTML>"; 

You can even add file attachments using the MailMessage.Attachments collection and the MailAttachment class.

 MailAttachment myAttachment = new MailAttachment("c:\mypic.gif"); myMessage.Attachments.Add(myAttachment); 

To send the message, you simply specify the SMTP server name and call the SmptMail.Send method.

 SmtpMail.SmtpServer = "test.mailserver.com"; SmtpMail.Send(myMessage); 

However, there is a significant catch to using the SmtpMail class to send an e-mail message. This class requires a local SMTP server or relay server on your network. In addition, the SmtpMail class doesn't support authentication, so if your SMTP server requires a username and password, you won't be able to send any mail. To overcome these problems, you can use the CDOSYS component directly through COM interop ( assuming you have a server version of Windows or Microsoft Exchange).

Note  

Remember that the SMTP protocol can't be used to retrieve e-mail. For this task, you need the POP3 or IMAP protocol, neither of which is exposed natively in the .NET Framework.

For more information about using and configuring your own SMTP server, consult a dedicated book on IIS.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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