Send emails with System.Web.mail in .NET applications
Author: Mark Strawmyer
Date: February 9, 2004
Welcome to the .NET NUTS & BOLTS column. In this column, we will explore how to send emails in your application. This will use the class in the System.Web.mail name space. Collaboration Data Objects Windows 2000 Collaboration Data Object (CDOSYS) is a message component that Microsoft is used to create and send standard email information. It is an alternative to collaboration data objects (cdonts) with Windows NT. Although CDONTS is included in Windows 2000 due to backward compatibility, Windows XP, Windows Server 2003, and a CDONTS component are not included. So any application that uses CDONTS sends a message must be migrated to use CDOSYS. It provides the same function and is easy to use. In addition to the alternative, CDOSYS has introduced some functions in CDONTS, such as:
The ability to send messages to the newsgroup to control the MIME structure of the message and transfer the event accepting the pool to respond to the event to respond to the system.Web.mail namespace containing the CDOSYS component interaction to create and send information. Using Internet Information Services (IIS) and SMTP services In order to send emails from the application, you must confirm that SMTP services have been installed in the IIS service list. In Windows 2000 / XP, you can set it by control panel -> Add / Remove Programs -> Add / Remove Windows Components options. The task of the STMP service is based on configuring and sending messages. This service can be delivered directly, or you can use the proxy server to send a message. When the proxy server is configured, all messages will forward it to it for transmission. You must ensure that IIS and SMTP services are properly installed and configured. The SMTP service uses a directory structure to save the message before delivery. The default directory is c: / inetpub / mailroot. This folder contains some subdirectories, such as: Queue, Drop, Badmail. If you can't configure the SMTP service instance to send, you will be able to find a message in the * .eml file in the directory C: / INETPUB / MAILROOT / QUEUE. This trick will be useful when you enter an email offline. Send a message As mentioned earlier, sending an email will be a relatively simple matter. Class System.Web.mail.mailMASSAGE CLASS represents messages to be sent. E-mail messages will be created by the instance of this class. This class contains properties such as recipients, senders, and topics to let you control the message you want to send. You can also create an attachment using an instance of class system.Web.mail.maiLattachment, then add it to the MailMessage ATTACHMENTS (attachment) collection. The message will then be sent from class system.web.mail.smtpmail. Send Mail Sample Code The following C # sample code will contain a Windows console program that demonstrates how to send simple email. The local machine will be configured for its default when there is no SMTPMAIL's SMTPServer property. You must make sure you add a reference to System.Web.dll because it is a console application instead of an ASP.NET application. Using system;
Using system.web.mail;
Namespace codeGuru.sendmail
{
///
/// Test Console Application To Demonstrate Sending E-Mail.
/// summary> Class Testmail
{
///
/// The main entry point for the application.
/// summary>
[Stathread]
Static void main (string [] args)
{
Testmail.send ("Testuser@codeguru.com",
"mstrawmyer@crowechizek.com",
"Test Message Using CDOSYS",
"Hello World! This Is A Simple Message Sent
Using cdosys. ");
}
///
/// send a message using the .net wrapper for collaborative data
/// Objects (cdo). This method be used by me sending to a
/// Single Recipient Only; Otherwise, The List of Recipients
/// Will Be Known.
/// summary>
/// Message Originator param>
/// Message receiver param>
/// Message Subject param>
/// Message Body param>
Public Static Void Send (String MessageFrom,
String MessageTo,
String MessageSubject,
String messagebody)
{
MailMessage Message = New MailMessage ();
Message.from = messagefrom;
Message.to = message.
Message.subject = messagesubject;
Message.BodyFormat = mailformat.text;
Message.body = messagebody;
Try
{
System.console.writeline ("Sending Outgoing Message);
SMTPMAIL.SEND (Message);
}
Catch (System.Web.httpexception Exhttp)
{
System.console.writeline ("Exception Occurred:"
Exhttp.Message);
}
}
}
}
Sending an attachment's Mail Sample Code The following C # sample code will contain a Windows console program that demonstrates how to send an accessory-added email. This will be done by an instance of creating class MessageAtTachment, and then add it to the Attachments collection. Using system;
Using system.web.mail;
Namespace codeGuru.sendmail
{
///
/// Console Application To DemonStrate Sending E-mail with an an
/// attachment.
/// summary>
Class testmail
{
///
/// The main entry point for the application.
/// summary>
[Stathread]
Static void main (string [] args)
{
Testmail.sendattachment ("Testuser@codeguru.com",
"mstrawmyer@crowechizek.com",
"Test Message Using CDOSYS",
"Hello World! This Is A Simple
Message Sent Using CDOSYS. ",
"c: //myattachment.txt");
}
///
/// send a message using the .net wrapper for collaborative data
/// Objects (cdo). This method be used when desending to
/// A Single Recipient Only; OtherWise, The List of Recipients
/// Will Be Known.
/// summary>
/// Message Originator param>
/// Message receiver param>
/// Message Subject param>
/// Message Body param>
/// Path to attachment
/// param>
Public static void sendattachment (String MessageFrom,
String MessageTo,
String MessageSubject,
String MessageBody,
String MessageAttachmentPath)
{
// Create and setup the message
MailMessage Message = New MailMessage ();
Message.from = messagefrom;
Message.to = message.
Message.subject = messagesubject;
Message.BodyFormat = mailformat.text;
Message.body = messagebody;
// Create and add the attachment
MaiLattachment attachment = new
MaiLattachment (MessageAttachmentPath); message.attachments.add (attachment);
Try
{
// Deliver the Message
System.console.writeline ("Sending Outgoing Message);
SMTPMAIL.SEND (Message);
}
Catch (System.Web.httpexception Exhttp)
{
System.console.writeline ("Exception Occurred:"
Exhttp.Message);
}
}
}
}
Possible improvements We have demonstrated how to send emails from different channels. Now I am thinking about how to apply this feature in your application. Here are some ideas and you sharing together:
E-mail Warning - When a fatal or unable to recover an application error, your application can send an email to a specified address to make it quickly known. Create a web-based contact message - You can use users to send user feedback by filling out the web form, then write the relevant program to send the message to the appropriate contact. Subscribe Services - When you send an email through the CDOSYS component, you will need to send multiple emails instead of a single mail to all recipients. When a message has a large number of recipients, processing all the recipients will dramatically reduce the processing speed. At this time, you should then break the list of recipients into multiple lists and send a message several times. Send a message using BCC - When you send an email through the CDOSYS component, you may want to use BCC instead of To to fill in the recipient address. This makes all recipients unable to know the list of receiver. Sending an HTML format message-message body format can be HTML. It allows the message body to be sent in HTML format instead of normal text. -------------------------------------------------- --------- Original:
Sending e-mail with system.web.mail
Mark StrawMyer (View Profile) February 9, 2004Rating: Not yet rated
Welcome to the next installment of the .NET Nuts & Bolts column. In this column, we'll explore sending e-mail from within applications. This will involve utilizing classes contained in the System.Web.Mail namespace. Collaboration Data Objects Collaboration Data Objects for Windows 2000 (CDOSYS) is a Microsoft messaging component that allows for standards-based e-mail messages to be constructed and sent. It is a replacement of the Collaboration Data Objects for NTS (CDONTS), which, as you can probably guess by the name, was for Windows NT. CDONTS is included with Windows 2000 for backwards compatibility, but Windows XP, Windows Server 2003, and beyond do not include or support the use of CDONTS. Thus, any applications that send messages using CDONTS must be migrated to use CDOSYS. It provides the same functionality and is just as easy to use. in addition to serving as a replacement, CDOSYS introduces some new functionality that was not previously available in CDONTS. some of the functio NaLity Includes: Ability To Post Messages To NewsGroups Control of Mime Body Structure for Messages Reply And Forward Functionality Transport Event Sink To Allow Responding to Events
The System.Web.Mail namespace contains classes that interact with CDOSYS to construct and send the message (s). Using IIS and SMTP Service In order for CDOSYS to send e-mail or other messages from your application, you need to enlist the services Of Iis with The SMTP Service Installed. Both Are Available in Windows 2000 / XP THROUGH THE Control Panel -> Add / Remove Programs ->
Add / Remove Windows Components option. The job of the STMP Service is to accept and deliver the messages, based on the configuration. The service can attempt to deliver the messages directly, or it can utilize a smart host to deliver the message instead. When a smart host is enlisted, all messages are forwarded to it for delivery You need to have IIS and the SMTP service installed and configured The SMTP Service uses a directory structure to contain messages prior to delivery The default directory is C:... / Inetpub .. / mailroot This folder contains a number of subdirectories such as Queue, Drop, and Badmail If you are unable to configure your instance of the SMTP Service for delivery, you can find the message in a * .EML file in the C:
/ Inetpub / mailroot / Queue directory. This technique can be useful when creating messages offline. Sending a Message As previously mentioned, sending an e-mail is a relatively simple thing to do. The System.Web.Mail.MailMessage class represents the message to be sent. E-mail messages are constructed by using instances of this class. This class contains properties such as to, From, and Subject that allow you to control the message being sent. Attachments can be created through instances of the System.Web .Mail.MailAttachment and then added to the MailMessage through the Attachments collection of the MailMessage. The message is then delivered through the System.Web.Mail.SmtpMail class. Sending a Message Sample code The following sample code contains a C # -based Windows Console application that shows how to send an e-mail message. by not specifying that the SmtpMail.SmtpServer property is not set, the localhost is used by default. You need to make sure to add a reference to the System.Web.dll Because this is a console application and not an asp.net application.using system; using system.web.mail;
Namespace codeGuru.sendmail
{
///
/// Test Console Application To Demonstrate Sending E-Mail.
/// summary>
Class testmail
{
///
/// The main entry point for the application.
/// summary>
[Stathread]
Static void main (string [] args)
{
Testmail.send ("Testuser@codeguru.com",
"mstrawmyer@crowechizek.com",
"Test Message Using CDOSYS",
"Hello World! This Is A Simple Message Sent
Using cdosys. ");
}
///
/// send a message using the .net wrapper for collaborative data
/// Objects (cdo). This method be used when desnding to a // single recipient only; OtherWise, The List of Recipients
/// Will Be Known.
/// summary>
/// Message Originator param>
/// Message receiver param>
/// Message Subject param>
/// Message Body param>
Public Static Void Send (String MessageFrom,
String MessageTo,
String MessageSubject,
String messagebody)
{
MailMessage Message = New MailMessage ();
Message.from = messagefrom;
Message.to = message.
Message.subject = messagesubject;
Message.BodyFormat = mailformat.text;
Message.body = messagebody;
Try
{
System.console.writeline ("Sending Outgoing Message);
SMTPMAIL.SEND (Message);
}
Catch (System.Web.httpexception Exhttp)
{
System.console.writeline ("Exception Occurred:"
Exhttp.Message);
}
}
}
}
Sending a Message with an Attachment Sample Code The following sample code contains a C # -based Windows Console application that shows how to send an e-mail message that includes an attachment. This is done by creating instances of the MessageAttachment class and then adding them to The Message THROUGH The attachments collection.using system;
Using system.web.mail;
Namespace codeGuru.sendmail
{
///
/// Console Application To DemonStrate Sending E-mail with an an
/// attachment.
/// summary>
Class testmail
{
///
/// The main entry point for the application.
/// summary>
[Stathread]
Static void main (string [] args) {
Testmail.sendattachment ("Testuser@codeguru.com",
"mstrawmyer@crowechizek.com",
"Test Message Using CDOSYS",
"Hello World! This Is A Simple
Message Sent Using CDOSYS. ",
"c: //myattachment.txt");
}
///
/// send a message using the .net wrapper for collaborative data
/// Objects (cdo). This method be used when desending to
/// A Single Recipient Only; OtherWise, The List of Recipients
/// Will Be Known.
/// summary>
/// Message Originator param>
/// Message receiver param>
/// Message Subject param>
/// Message Body param>
/// Path to attachment
/// param>
Public static void sendattachment (String MessageFrom,
String MessageTo,
String MessageSubject,
String MessageBody,
String MessageAttachmentPath)
{
// Create and setup the message
MailMessage Message = New MailMessage ();
Message.from = messagefrom;
Message.to = message.
Message.subject = messagesubject;
Message.BodyFormat = mailformat.text;
Message.body = messagebody;
// Create and add the attachment
MaiLattachment attachment = new
MaiLattachment (MessageAtTachmentPath);
Message.attachments.add (attachment);
Try
{
// Deliver the Message
System.console.writeline ("Sending Outgoing Message);
SMTPMAIL.SEND (Message);
}
Catch (System.Web.httpexception Exhttp)
{
System.Console.writeline ("Exception Occurred:" Excetp.Message);
}
}
}
}
Possible Enhancements We have demonstrated how to send e-mail messages in a couple of ways It is now up to you to think about ways in which you can utilize this functionality within your applications Here are some ideas to consider on your own..:
E-mail alerts-when a fatal or unrecoverable application error occurs, your application could e-mail information to a designated location so that it is immediately known. Build a Web-based contact form-you can allow users to send customer feedback by filling out a Web form and then programmatically e-mailing it to the appropriate contact (s). Subscription service-when sending mail by using CDOSYS for a subscription-type service, you may want to send multiple messages instead of a single message with all of the recipients. When a message has too many recipients, it can drastically slow processing as all of the recipients are processed. It is often better to break the list of recipients into multiple lists and send multiple messages. Send messages using Bcc-when sending mail using by CDOSYS for a subscription-type service, you may want to address messages using the Bcc instead of to. This will keep the list of recipients unknown to all of those that receive it. Send HTML-formatted mail -The Message Body Format Can Be set to html. This article introduces the email in how to send emails in how .NET programs Configure IIS and SMTP services, how to send simple messages and some ideas for use in applications. For developers, it is not a good article to send emails. In the development of the .NET online bookstore, we can also use the send email to feed back book information to the customer, and provide custom single services for customers.