+ All Categories

SMTP

Date post: 22-Nov-2014
Category:
Upload: rajeshkutiwari
View: 131 times
Download: 0 times
Share this document with a friend
Popular Tags:
93
System.Net.Mail FAQ Complete FAQ Listing 1 Introduction 1.1 What is System.Net.Mail? 1.2 What is the .NET Framework ? 1.3 What do I need to send email in .NET? 1.4 What is a relay server? 1.5 What is the IIS SMTP Service? 1.6 Can System.Net.Mail read email?
Transcript
Page 1: SMTP

System.Net.Mail FAQComplete FAQ Listing1 Introduction 1.1 What is System.Net.Mail? 1.2 What is the .NET Framework ? 1.3 What do I need to send email in .NET? 1.4 What is a relay server? 1.5 What is the IIS SMTP Service?1.6 Can System.Net.Mail read email?

Page 2: SMTP

1.1 What is System.Net.Mail?

System.Net.Mail is the namespace used to send email if you are using the 2.0 (or higher) .NET Framework. Unlike System.Web.Mail, which was introduced in the 1.0 Framework, it is not built upon the CDO/CDOSYS libraries. Instead it is written from the ground up without any interop. Thus, it is not dependant upon other COM libraries. System.Net.Mail introduces brand new classes for creating and sending email. Although some functionality has been removed, the new System.Net.Mail namespace is much more versatile than the older CDO dependant System.Web.Mail.

1.2 What is the .NET Framework? The answer to this question is way beyond the scope of this faq. Basically the .NET Framework is a engine that programmers use to create applications. Programmers code against the .NET Framework to create applications. The System.Web.Mail Namespace is part of the .NET framework. You can read more about the .NET Framework on MSDN at http://msdn.microsoft.com/netframework/

1.3 What do I need to send email in .NET? First, and foremost, you need the .NET Framework installed. Then you need a reference to the System.dll (automatically included in ASP.NET applications). Then you need to use the System.Net.Mail namespace to create and send email messages. Once you have programmatically set up your application, you will need a relay server to send email through. A relay server is a mail server, or a SMTP server/service, that can handle sending email. System.Net.Mail simply sends the mail to a relay server, and the relay server is responsible for delivering it to the final destination.

1.4 What is a relay server? A relay is a service that allows you to send email. It is usually a full fledged mail server, or can be a specialized SMTP Service. Some examples of a mail server include Microsoft Exchange, IMail by IPSwitch, or Mail Enable by Mail Enable. An example of a SMTP service is the SMTP Service installed that can be installed with IIS. SNM sends email to a relay server, and the relay server is responsible for delivering the email to the final destination. When sending email to a relay server, you must have protocol permissions to use that server. Because of SPAM problems, relay servers are normally locked down, either by IPAddress or by some type of username/password authentication. Relaying errors are the most common problems when programmatically sending emails. If you ever see an exception that reads something like "550 Permission Denied", this is usually a relay error, and you need to talk to your mail server administrator about proper permissions.

1.5 What is the IIS SMTP Service? The IIS SMTP service is a SMTP service used for sending email. It handles all of the MX Record (Mail server location) lookups, SMTP connections to remote mail servers, retries, and failures. More information about configuring the SMTP Service can be found here:

Page 3: SMTP

Manage Your Company's E-mail with the Windows 2000 SMTP Service http://www.microsoft.com/mind/1299/smtp2000/smtp2000.asp

1.6 Can System.Net.Mail read email? No. System.Net.Mail can only send email. To read email you either need a Mime parsing component such as aspNetMime or a POP3 component such as aspNetPOP3.

Page 4: SMTP

2 Exploring System.Net.Mail Classes2.1 MailMessage Class2.2 MailAddress Class2.3 Attachment Class2.4 SmtpClient Class2.5 AlternateView Class2.6 Linked Resource

2 Exploring System.Net.Mail Classes

This FAQ section will explore the main classes of the System.Net.Mail name space. This is not a complete listing of all the classes, but rather the ones that are most commonly used. They include: MailMessageMailAddressAttachmentSmtpClientAlternateViewLinkedResource

Page 5: SMTP

2.1 MailMessage ClassThe MailMessage class can be considered the foundation class of the System.Net.Mail namespace. It deals with creating and managing the email message. All other classes will somehow interact with this class. The MailMessage class exposes such properties as the Property Description

Attachments Gets the attachment collection used to store data attached to this e-mail message.

Bcc Gets the address collection that contains the blind carbon copy (BCC) recipients for this e-mail message.

Body Gets or sets the message body.

CC Gets the address collection that contains the carbon copy (CC) recipients for this e-mail message.

From Gets or sets the from address for this e-mail message.Subject Gets or sets the subject line for this e-mail message.

To Gets the address collection that contains the recipients of this e-mail message.

Below you will find an example of using the MailMessage class[ C# ] static void PlainText(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);}

[ VB.NET ] Sub PlainText()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")

Page 6: SMTP

mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'PlainText

Page 7: SMTP

2.2 MailAddress Class

Click here for MSDN docs. The MailAddress class is used for creating email addresses. This class is used for setting the MailMessage.From, MailMessage.To, MailMessage.CC and MailMessage.BCC properties. Of these properties the .From class is actually a MailAddress, while the To, CC and BCC properties are actually collections of MailAddresses. The two most common properties of the MailAddress class are the DisplayName and the Address properties. They are described below.

Name Description Address Gets the e-mail address specified when this instance was created.DisplayName Gets the display name composed from the display name and address

information specified when this instance was created.  Below is an example demonstrating the MailAddress class.[ C# ] static void MultipleRecipients(){//create the mail messageMailMessage mail = new MailMessage();

//set the addresses//to specify a friendly 'from' name, we use a different ctormail.From = new MailAddress("[email protected]", "Steve James");

//since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address//since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple timesmail.To.Add("[email protected]");mail.To.Add("[email protected]");mail.CC.Add("[email protected]");mail.CC.Add("[email protected]");mail.Bcc.Add("[email protected]");mail.Bcc.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);}

Page 8: SMTP

[ VB.NET ] Sub MultipleRecipients()'create the mail messageDim mail As New MailMessage()

'set the addresses'to specify a friendly 'from' name, we use a different ctormail.From = New MailAddress("[email protected]", "Steve James")

'since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address'since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple timesmail.To.Add("[email protected]")mail.To.Add("[email protected]")mail.CC.Add("[email protected]")mail.CC.Add("[email protected]")mail.Bcc.Add("[email protected]")mail.Bcc.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'MultipleRecipients

Page 9: SMTP

2.3 Attachment Class Printer Friendly

Click here for MSDN docs. The Attachment class is used for creating and managing individual attachments of the MailMessage object. Attachments can be created from streams or file paths. The stream or file path must be set in the ctor of the Attachment.Below is an example demonstrating the Attachment class [ C# ] static void AttachmentFromFile(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this content is in the body";

//add an attachment from the filesystemmail.Attachments.Add(new Attachment("c:\\temp\\example.txt"));

//to add additional attachments, simply call .Add(...) againmail.Attachments.Add(new Attachment("c:\\temp\\example2.txt"));mail.Attachments.Add(new Attachment("c:\\temp\\example3.txt"));

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);

}

[ VB.NET ] Sub AttachmentFromFile()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

Page 10: SMTP

'set the contentmail.Subject = "This is an email"mail.Body = "this content is in the body"

'add an attachment from the filesystemmail.Attachments.Add(New Attachment("c:\temp\example.txt"))

'to add additional attachments, simply call .Add(...) againmail.Attachments.Add(New Attachment("c:\temp\example2.txt"))mail.Attachments.Add(New Attachment("c:\temp\example3.txt"))

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'AttachmentFromFile

Page 11: SMTP

2.4 SmtpClient Class

Click here for MSDN docs. The SmtpClient class is responsible for sending or transporting the email. The SmtpClient can transport the email content over the network, or it can actually write them to the filesystem in the MS IIS Smtp Service Pickup Directory format, which resembles a RFC821 formatted message. Emails can be sent either synchronously or asynchronously. The SmtpClient also supports sending email via SSL for security purposes. The following list of properties are the most common used on the SmtpClient class.

Name Description Credentials Gets or sets the credentials used to authenticate the

sender.DeliveryMethod Specifies how outgoing email messages will be

handled.EnableSsl Specify whether the SmtpClient uses Secure Sockets

Layer (SSL) to encrypt the connection.Host Gets or sets the name or IP address of the host used for

SMTP transactions.Port Gets or sets the port used for SMTP transactions.  Below is an example demonstrating the SmtpClient class.[ C# ] static void Authenticate(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");

//to authenticate we set the username and password properites on the SmtpClientsmtp.Credentials = new NetworkCredential("username", "secret"); smtp.Send(mail);

}

Page 12: SMTP

[ VB.NET ] Sub Authenticate()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'send the messageDim smtp As New SmtpClient("127.0.0.1")

'to authenticate we set the username and password properites on the SmtpClientsmtp.Credentials = New NetworkCredential("username", "secret")smtp.Send(mail)End Sub 'Authenticate

Page 13: SMTP

2.5 AlternateView Class

Click here for MSDN docs. The AlternateView class is used for providing alternate bodies and creating Multi-Part mime emails. If you want to create an email that will be rendered properly in both Html capable and Plain Text only mail clients, then you will create alternate views of the message. There are a few main properties and methods you will use with the AlternateView class. They are:

Name Description BaseUri Gets or sets the Base URI to use for resolving

relative URIs in the AlternateViewLinkedResources Gets the set of embedded resources referred to by

this attachment.CreateAlternateViewFromString (static method)

Overloaded. Creates an AlternateView to view an email message using the specified format..

Below is an example demonstrating the AlternateView class. [ C# ] static void MultiPartMime(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";

//first we create the Plain Text partAlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");//then we create the Html partAlternateView htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");mail.AlternateViews.Add(plainView);mail.AlternateViews.Add(htmlView);

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1"); //specify the mail server addresssmtp.Send(mail);}

Page 14: SMTP

[ VB.NET ] Sub MultiPartMime()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"

'first we create the Plain Text partDim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", Nothing, "text/plain")'then we create the Html partDim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", Nothing, "text/html")mail.AlternateViews.Add(plainView)mail.AlternateViews.Add(htmlView)

'send the messageDim smtp As New SmtpClient("127.0.0.1") 'specify the mail server addresssmtp.Send(mail)End Sub 'MultiPartMime

Page 15: SMTP

2.6 Linked Resource

Click here for MSDN docs. The LinkedResource class is the last, and least used main class. It is mainly used for creating embedded images. To create an embedded image you will need to first create a Html formatted AlternateView. Within that alternate view you create an tag, that points to the ContentId (CID) of the LinkedResource. You then create a LinkedResource object and add it to the AlternateView's LinkedResources collection.Below is an example using the LinkedResource class.[ C# ] static void EmbedImages(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";

//first we create the Plain Text partAlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");

//then we create the Html part//to embed images, we need to use the prefix 'cid' in the img src value//the cid value will map to the Content-Id of a Linked resource.//thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo'AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.<img src=cid:companylogo>", null, "text/html");

//create the LinkedResource (embedded image)LinkedResource logo = new LinkedResource( "c:\\temp\\logo.gif" );logo.ContentId = "companylogo";//add the LinkedResource to the appropriate viewhtmlView.LinkedResources.Add(logo);

//add the viewsmail.AlternateViews.Add(plainView);mail.AlternateViews.Add(htmlView);

//send the message

Page 16: SMTP

SmtpClient smtp = new SmtpClient("127.0.0.1"); //specify the mail server addresssmtp.Send(mail);}

[ VB.NET ] Sub EmbedImages()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"

'first we create the Plain Text partDim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", Nothing, "text/plain")

'then we create the Html part'to embed images, we need to use the prefix 'cid' in the img src value'the cid value will map to the Content-Id of a Linked resource.'thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo'Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.<img src=cid:companylogo>", Nothing, "text/html")

'create the LinkedResource (embedded image)Dim logo As New LinkedResource("c:\temp\logo.gif")logo.ContentId = "companylogo"'add the LinkedResource to the appropriate viewhtmlView.LinkedResources.Add(logo)

'add the viewsmail.AlternateViews.Add(plainView)mail.AlternateViews.Add(htmlView)

'send the messageDim smtp As New SmtpClient("127.0.0.1") 'specify the mail server addresssmtp.Send(mail)End Sub 'EmbedImages

Page 17: SMTP

3 Quickstart Programming Samples 3.1 Working with the Body3.1.1 How do I send a plain text email? 3.1.2 How do I send a simple Html email? 3.1.3 How do I create a Multi-Part mime message?3.2 Working with Addresses3.2.1 How do I change the FROM address to a friendly name? 3.2.2 How do I change the TO address to a friendly name? 3.2.3 How do I specify multiple recipients? 3.2.4 How do I create a friendly non-ascii display name?3.3 Working with Headers3.3.1 How do I change the email priority?3.3.2 How do I add the Reply-To header to the MailMessage?3.3.3 How do I request a read receipt?3.3.4 How do I add custom headers to the MailMessage? 3.4 Working with Attachments3.4.1 How do I send an email with attachments? 3.4.2 How do I create an attachment from a stream?3.5 Accessing Config File Mail Settings Programmatically

Page 18: SMTP

3 Quickstart Programming Samples This System.Web.Mail QuickStart is a series of samples and supporting commentary designed to quickly acquaint developers with the syntax of sending email in .NET. The QuickStart samples are designed to be short, easy-to-understand illustrations of System.Net.Mail.

Important: When testing these samples, always be sure to: 1. Have a reference set to the System.dll. 2. If you are using C#, be sure the "using System.Net.Mail;" statement is found at the top of your code. Or, if you are using VB.NET, be sure the "Imports System.Net.Mail" statement if found at the top of your code. 3. Set the correct FROM and TO addresses. 4. Set the SmtpMail.SmtpServer to a valid server that allows relaying for your FROM email address or the IP address you are sending email from.

3.1 Working with the Body This section of the FAQ will deal with creating different types of email bodies. From Plain Text formatted emails, to Html formatted emails, to creating Multi-Part Mime emails.

Page 19: SMTP

3.1.1 How do I send a plain text email? The following example demonstrates sending a simple plain text email.   [ C# ] //create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is a sample body";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);

[ VB.NET ] 'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is a sample body"

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)

Page 20: SMTP

3.1.2 How do I send a simple Html email? By default, email sent with System.Net.Mail is formatted as plain text. To format as Html, set the MailMessage.IsBodyHtml property to true.   [ C# ] //create the mail message MailMessage mail = new MailMessage();

//set the addresses mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]");

//set the content mail.Subject = "This is an email"; mail.Body = "this is a sample body with html in it. <b>This is bold</b> <font color=#336699>This is blue</font>"; mail.IsBodyHtml = true;

//send the message SmtpClient smtp = new SmtpClient("127.0.0.1"); smtp.Send(mail);

[ VB.NET ] 'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email" mail.Body = "this is a sample body with html in it. <b>This is bold</b> <font color=#336699>This is blue</font>"mail.IsBodyHtml = True

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)

Page 21: SMTP

3.1.3 How do I create a Multi-Part mime message? This example will demonstrate creating a Multi-Part mime message. Multi-Part messages are messages that contain alternate body parts. Alternate body parts are used for displaying different content to different mail clients. Because it is impossible to sniff or determine an end users' mail client application, it is left up to the email developer to cover all formats. You simply create different, alternate body parts. Then, it is up to the mail client to display the richest body part it can render. The following example creates the most common Multi-Part mime email, a Plain Text and a Html Text email (2 alternate body parts).

[ C# ] static void MultiPartMime(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";

//first we create the Plain Text partAlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");//then we create the Html partAlternateView htmlView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", null, "text/html");mail.AlternateViews.Add(plainView);mail.AlternateViews.Add(htmlView);

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1"); //specify the mail server addresssmtp.Send(mail);}

[ VB.NET ] Sub MultiPartMime()'create the mail messageDim mail As New MailMessage()

Page 22: SMTP

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"

'first we create the Plain Text partDim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", Nothing, "text/plain")'then we create the Html partDim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("<b>this is bold text, and viewable by those mail clients that support html</b>", Nothing, "text/html")mail.AlternateViews.Add(plainView)mail.AlternateViews.Add(htmlView)

'send the messageDim smtp As New SmtpClient("127.0.0.1") 'specify the mail server addresssmtp.Send(mail)End Sub 'MultiPartMime

Page 23: SMTP

3.2 Working with Addresses This section of the faq will demonstrate working with the From, To, CC, and Bcc addresses.

3.2.1 How do I change the FROM address to a friendly name? Because the MailMessage.From property is a MailAddress, we simply need to use a different ctor to create a MailAddress. The ctor we will use will accept a friendly display name. [ C# ] static void FriendlyFromName(){ //create the mail messageMailMessage mail = new MailMessage();

//set the addresses//to specify a friendly 'from' name, we use a different ctormail.From = new MailAddress("[email protected]", "Steve James" );mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);

}

[ VB.NET ] Sub FriendlyFromName()'create the mail messageDim mail As New MailMessage()

'set the addresses'to specify a friendly 'from' name, we use a different ctormail.From = New MailAddress("[email protected]", "Steve James")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)

Page 24: SMTP

End Sub 'FriendlyFromName

Page 25: SMTP

3.2.2 How do I change the TO address to a friendly name? Chainging the To, CC, and Bcc addresses to use a Friendly display name, is just like we did for the .From property. We simply need to use a different MailAddress ctor to achieve this functionality. Below is a sample that demonstrates this.[ C# ] static void FriendlyToName(){//create the mail messageMailMessage mail = new MailMessage();

//set the addresses//to specify a friendly 'from' name, we use a different ctormail.From = new MailAddress("[email protected]", "Steve James");

//since the To,Cc, and Bcc accept addresses, we can use the same technique as the From addressmail.To.Add( new MailAddress( "[email protected]", "Beth Jones") );mail.CC.Add(new MailAddress("[email protected]", "Donna Summers"));mail.Bcc.Add(new MailAddress("[email protected]", "Bob Smith"));

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);}

[ VB.NET ] Sub FriendlyToName()'create the mail messageDim mail As New MailMessage()

'set the addresses'to specify a friendly 'from' name, we use a different ctormail.From = New MailAddress("[email protected]", "Steve James")

'since the To,Cc, and Bcc accept addresses, we can use the same technique as the From addressmail.To.Add(New MailAddress("[email protected]", "Beth Jones"))mail.CC.Add(New MailAddress("[email protected]", "Donna Summers"))mail.Bcc.Add(New MailAddress("[email protected]", "Bob Smith"))

Page 26: SMTP

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'FriendlyToName

 

Page 27: SMTP

3.2.3 How do I specify multiple recipients? Because the To, CC, and Bcc properties are MailAddress collections, to add additional recipients, all we need to do is call .Add(...) on the respective properties. Below is an example that demonstrates adding multiple To, CC, and Bcc addresses.[ C# ] static void MultipleRecipients(){//create the mail messageMailMessage mail = new MailMessage();

//set the addresses//to specify a friendly 'from' name, we use a different ctormail.From = new MailAddress("[email protected]", "Steve James");

//since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address//since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple timesmail.To.Add("[email protected]");mail.To.Add("[email protected]");mail.CC.Add("[email protected]");mail.CC.Add("[email protected]");mail.Bcc.Add("[email protected]");mail.Bcc.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);}

[ VB.NET ] Sub MultipleRecipients()'create the mail messageDim mail As New MailMessage()

'set the addresses'to specify a friendly 'from' name, we use a different ctormail.From = New MailAddress("[email protected]", "Steve James")

Page 28: SMTP

'since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address'since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple timesmail.To.Add("[email protected]")mail.To.Add("[email protected]")mail.CC.Add("[email protected]")mail.CC.Add("[email protected]")mail.Bcc.Add("[email protected]")mail.Bcc.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'MultipleRecipients

Page 29: SMTP

3.2.4 How do I create a friendly non-ascii display name? When we want to use non-ascii display names we have to specify an Encoding that matches the characterset of the name (string). This is something that needs to be known at the time of development. Below is an example of creating a friendly display name that uses ISO-8859-1 characters.[ C# ] static void FriendlyNonAsciiName(){//create the mail messageMailMessage mail = new MailMessage();

//set the addresses//to specify a friendly non ascii name, we use a different ctor. //A ctor that accepts an encoding that matches the text of the namemail.From = new MailAddress("[email protected]", "Steve Øbirk", Encoding.GetEncoding( "iso-8859-1"));mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);

}

[ VB.NET ] Sub FriendlyNonAsciiName()'create the mail messageDim mail As New MailMessage()

'set the addresses'to specify a friendly non ascii name, we use a different ctor. 'A ctor that accepts an encoding that matches the text of the namemail.From = New MailAddress("[email protected]", "Steve Øbirk", Encoding.GetEncoding("iso-8859-1"))mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

Page 30: SMTP

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'FriendlyNonAsciiName

Page 31: SMTP

3.3 Working with Headers This section of the faq will demonstrate working with headers of the MailMessage. From changing the messages' priority, to adding custom headers. We will explore different header names and values.

3.3.1 How do I change the email priority? Although the priority of a message is controlled by headers, in the System.Net.Mail namespace, the Priority of a message is actually exposed as a property of the MailMessage object. A priority can have the following valuesProperty DescriptionHigh The email has high priority. Low The email has low priority. Normal The email has normal priority. The following example demonstrates setting the MailMessage object to a High priority.[ C# ] static void SetPriority(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//specify the priority of the mail messagemail.Priority = MailPriority.High;

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);}

[ VB.NET ] Sub SetPriority()'create the mail messageDim mail As New MailMessage()

'set the addresses

Page 32: SMTP

mail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'specify the priority of the mail messagemail.Priority = MailPriority.High

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'SetPriority

Page 33: SMTP

3.3.2 How do I add the Reply-To header to the MailMessage? Just the Priority property, the Reply-To header is set via a property called ReplyTo on the MailMessage object. Since the ReplyTo property is of type MailAddress, it can be a simple email address, or it can include a friendly display name. The following example demonstrates setting the ReplyTo property.[ C# ] static void SetTheReplyToHeader(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//specify the priority of the mail messagemail.ReplyTo = new MailAddress("[email protected]");

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);}

[ VB.NET ] Sub SetTheReplyToHeader()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'specify the priority of the mail messagemail.ReplyTo = New MailAddress("[email protected]")

'send the message

Page 34: SMTP

Dim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'SetTheReplyToHeader

Page 35: SMTP

3.3.3 How do I request a read receipt? To request a read receipt, we need to specify a Disposition-Notification-To header. This header is recognized my most major mail clients to send a read receipt when the email is first read. It's important to note that just because you request a read receipt, doesn't' mean you will get one.Read receipt requests may not be always honored because1) A mail client may not recognize the special Disposition-Notification-To header.2) A mail client may not implement that functionality.3) The end user may have that functionality turned off.4) The end user may optionally not choose to send one for your particular email.[ C# ] static void ReadReceipts(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//To request a read receipt, we need add a custom header named 'Disposition-Notification-To'//in this example, read receipts will go back to '[email protected]'//it's important to note that read receipts will only be sent by those mail clients that //a) support them//and//b)have them enabled.mail.Headers.Add("Disposition-Notification-To", "<[email protected]>");

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);}

[ VB.NET ] Sub ReadReceipts()'create the mail messageDim mail As New MailMessage()

Page 36: SMTP

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'To request a read receipt, we need add a custom header named 'Disposition-Notification-To''in this example, read receipts will go back to '[email protected]''it's important to note that read receipts will only be sent by those mail clients that 'a) support them'and'b)have them enabled.mail.Headers.Add("Disposition-Notification-To", "<[email protected]>")

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'ReadReceipts

Page 37: SMTP

3.3.4 How do I add custom headers to the MailMessage? Custom headers are useful for adding information to a MailMessage that may not be supported on standard properties. By adding custom headers, we can tag email messages with information that may not be visible to the end user, yet still might be important to us. This is especially useful in tracking bounced emails. By using custom headers, we can find our custom header in a bounced email, and perhaps tie it back to a record in the database. Below is an example of adding two "X-" headers to a MailMessage. There isn't anything special about adding the prefix "X-" to a header. In the email world, the "X-" prefix has just come to mean "extra".[ C# ] static void CustomHeaders(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//to add custom headers, we use the Headers.Add(...) method to add headers to the //.Headers collectionmail.Headers.Add("X-Company", "My Company");mail.Headers.Add("X-Location", "Hong Kong");

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);}

[ VB.NET ] Sub CustomHeaders()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the content

Page 38: SMTP

mail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'to add custom headers, we use the Headers.Add(...) method to add headers to the '.Headers collectionmail.Headers.Add("X-Company", "My Company")mail.Headers.Add("X-Location", "Hong Kong")

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'CustomHeaders

Page 39: SMTP

3.4 Working with Attachments This FAQ section will demonstrate creating attachments from the filesystem and from a stream.

3.4.1 How do I send an email with attachments? To send an email with attachments, the ASP.NET process (or the ASP.NET impersonated account) will need permission to read the file, and attach it to the MailMessage class.  If the file is found in the website, we don't need use the explicit file path, we could also call Server.MapPath(...). Below is a simple example of attaching  text files to an outgoing email.

[ C# ] static void AttachmentFromFile(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this content is in the body";

//add an attachment from the filesystemmail.Attachments.Add(new Attachment("c:\\temp\\example.txt"));

//to add additional attachments, simply call .Add(...) againmail.Attachments.Add(new Attachment("c:\\temp\\example2.txt"));mail.Attachments.Add(new Attachment("c:\\temp\\example3.txt"));

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);

}

[ VB.NET ] Sub AttachmentFromFile()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")

Page 40: SMTP

mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this content is in the body"

'add an attachment from the filesystemmail.Attachments.Add(New Attachment("c:\temp\example.txt"))

'to add additional attachments, simply call .Add(...) againmail.Attachments.Add(New Attachment("c:\temp\example2.txt"))mail.Attachments.Add(New Attachment("c:\temp\example3.txt"))

'send the messageDim smtp As New SmtpClient("127.0.0.1")smtp.Send(mail)End Sub 'AttachmentFromFile

3.4.2 How do I create an attachment from a stream? Something that is new in System.Net.Mail, is the capability to create attachments from streams. With this capability we can create an attachment from text, binary data, or from basically anything in memory. We simply need to make sure it is written to a stream. The following example creates an attachment from some simple text, but it could have just as easily have come from Sql Server.[ C# ] static void AttachmentFromStream(){

//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this content is in the body";

//Get some binary databyte[] data = GetData();

//save the data to a memory streamMemoryStream ms = new MemoryStream(data);

Page 41: SMTP

//create the attachment from a stream. Be sure to name the data with a file and //media type that is respective of the datamail.Attachments.Add( new Attachment( ms, "example.txt", "text/plain" ));

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");smtp.Send(mail);}static byte[] GetData(){//this method just returns some binary data.//it could come from anywhere, such as Sql Serverstring s = "this is some text";byte[] data = Encoding.ASCII.GetBytes(s);return data;}

[ VB.NET ] Sub AttachmentFromStream()

'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this content is in the body"

'Get some binary dataDim data As Byte() = GetData()

'save the data to a memory streamDim ms As New MemoryStream(data)

'create the attachment from a stream. Be sure to name the data with a file and 'media type that is respective of the datamail.Attachments.Add(New Attachment(ms, "example.txt", "text/plain"))

'send the messageDim smtp As New SmtpClient("127.0.0.1")

Page 42: SMTP

smtp.Send(mail)End Sub 'AttachmentFromStream

Function GetData() As Byte()'this method just returns some binary data.'it could come from anywhere, such as Sql ServerDim s As String = "this is some text"Dim data As Byte() = Encoding.ASCII.GetBytes(s)Return dataEnd Function 'GetData

Page 43: SMTP

3.5 Accessing Config File Mail Settings Programmatically Some people may not know that .NET 2.0 provides APIs for accessing everything in a configuration file. The most common question I see relates to accessing the mail settings in the system.net node programmatically. Special thanks to Ryan Olshan for this one. [ C# ]

System.Net.Configuration.MailSettingsSectionGroup mMailSettings;

int mPort = mMailSettings.Smtp.Network.Port;string mHost = mMailSettings.Smtp.Network.Host;string mPassword = mMailSettings.Smtp.Network.Password;string mUsername = mMailSettings.Smtp.Network.Username;

[ VB.NET ]

Dim mMailSettings As System.Net.Configuration.MailSettingsSectionGroup

Dim mPort As Integer = mMailSettings.Smtp.Network.PortDim mHost As String = mMailSettings.Smtp.Network.HostDim mPassword As String = mMailSettings.Smtp.Network.PasswordDim mUsername As String = mMailSettings.Smtp.Network.Username

Page 44: SMTP

4 Advanced Programming Samples * You Are Here * [ Scroll To Answer ] 4.1 How do I read SMTP configuration data?4.10 How do I create a log file of the SMTP session?4.11 How do I encrypt messages using s/mime or pgp?4.2 How do I authenticate to send an email?4.3 How do I change the SMTP port number?4.4 How do I embed images in an email? 4.5 How do I send an email over SSL?4.6 How do I send email asynchronously?4.7 How do I write to the Pickup directory?4.8 How do I send a web page? 4.9 How do I send non US-ASCII emails?

4 Advanced Programming Samples This System.Net.Mail advanced samples is a series of code samples and supporting commentary designed to perform advanced email operations. Some of the topics discussed here cannot be achieved using System.Net.Mail, but are listed for completeness, and because I have seen these questions asked on various newsgroups and lists.

Page 45: SMTP

4 Advanced Programming Samples This System.Net.Mail advanced samples is a series of code samples and supporting commentary designed to perform advanced email operations. Some of the topics discussed here cannot be achieved using System.Net.Mail, but are listed for completeness, and because I have seen these questions asked on various newsgroups and lists.

4.1 How do I read SMTP configuration data? Using special settings in your app's configuration file, System.Net.Mail can configure itself. Using the configuation file, you can set the following default properties:MailMessage.FromSmtpClient.HostSmtpClient.Port The settings will also allow you specify a Username and Password to be used for authentication. It is important to note that if DefaultCredentials are specified to true, the userName and password attributes are igorned.Here is an example of the  node:  <configuration>  <system.net>    <mailSettings>      <smtp from ="[email protected] ">        --             The node supports the following properties, but we won't use all of them                    -->        <network host="127.0.0.1" />       </< span>smtp>    </< span>mailSettings>   </< span>system.net></< span>configuration> 

If you need more flexibility, you can set individual SMTP settings for each page. For example: <location path="SomeDirectory/Page1.aspx"> <system.net> <mailSettings> <smtp deliveryMethod="Network" from="[email protected]"> <network defaultCredentials="true" host="smtp.example.com" port="25" userName="[email protected]" password="password"/> </smtp> </mailSettings> </system.net>

Page 46: SMTP

</location> <location path="SomeDirectory/Page2.aspx"> <system.net> <mailSettings> <smtp deliveryMethod="Network" from="[email protected]"> <network defaultCredentials="true" host="smtp.example.com" port="25" userName="[email protected]" password="password"/> </smtp> </mailSettings> </system.net> </location> <location path="SomeDirectory/Page3.aspx"> <system.net> <mailSettings> <smtp deliveryMethod="Network" from="[email protected]"> <network defaultCredentials="true" host="smtp.example.com" port="25" userName="[email protected]" password="password"/> </smtp> </mailSettings> </system.net> </location>

Page 47: SMTP

4.10 How do I create a log file of the SMTP session? The System.Net namespace allows you to log the contents of the SMTP session to a file.  This is done through a combination of trace switches in your app's configuration file. The following example of trace switches will cause the SMTP session to be logged to a file named "System.Net.trace.log".  <configuration>  <system.diagnostics>    <trace autoflush="true" />

    <sources>

      <source name="System.Net" >        <listeners>          <add name="MyTraceFile"/>        </listeners>      </source>

      <source name="System.Net.Sockets">        <listeners>          <add name="MyTraceFile"/>        </listeners>      </source>

    </sources>     <sharedListeners>      <add        name="MyTraceFile"        type="System.Diagnostics.TextWriterTraceListener"        initializeData="System.Net.trace.log"                />    </sharedListeners>    <switches>      <add name="System.Net" value="Verbose" />      <add name="System.Net.Sockets" value="Verbose" />    </switches> </configuration>Here is what the log file might look like:System.Net Verbose: 0 : [0992] SmtpClient::.ctor(host=127.0.0.1)System.Net Information: 0 : [0992] Associating SmtpClient#47606018 with SmtpTransport#5689696System.Net Verbose: 0 : [0992] Exiting SmtpClient::.ctor() -> SmtpClient#47606018System.Net Verbose: 0 : [0992] SmtpClient#47606018::Send(MailMessage#5138334)System.Net Information: 0 : [0992] SmtpClient#47606018::Send(DeliveryMethod=Network)

Page 48: SMTP

System.Net Information: 0 : [0992] Associating SmtpClient#47606018 with MailMessage#5138334System.Net Information: 0 : [0992] Associating SmtpTransport#5689696 with SmtpConnection#31950948System.Net Information: 0 : [0992] Associating SmtpConnection#31950948 with ServicePoint#34920472System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Socket(InterNetwork#2)System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Socket() System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Connect(1:25#16777318)System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Connect() System.Net Information: 0 : [0992] Associating SmtpConnection#31950948 with SmtpPooledStream#48167163System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Receive()System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::ReceiveSystem.Net.Sockets Verbose: 0 : [0992] 00000000 : 32 32 30 20 77 32 6B 20-4D 69 63 72 6F 73 6F 66 : 220 w2k MicrosofSystem.Net.Sockets Verbose: 0 : [0992] 00000010 : 74 20 45 53 4D 54 50 20-4D 41 49 4C 20 53 65 72 : t ESMTP MAIL SerSystem.Net.Sockets Verbose: 0 : [0992] 00000020 : 76 69 63 65 2C 20 56 65-72 73 69 6F 6E 3A 20 35 : vice, Version: 5System.Net.Sockets Verbose: 0 : [0992] 00000030 : 2E 30 2E 32 31 39 35 2E-36 37 31 33 20 72 65 61 : .0.2195.6713 reaSystem.Net.Sockets Verbose: 0 : [0992] 00000040 : 64 79 20 61 74 20 20 53-61 74 2C 20 33 31 20 44 : dy at Sat, 31 DSystem.Net.Sockets Verbose: 0 : [0992] 00000050 : 65 63 20 32 30 30 35 20-32 32 3A 31 33 3A 31 34 : ec 2005 22:13:14System.Net.Sockets Verbose: 0 : [0992] 00000060 : 20 2D 30 36 30 30 20 0D-0A : -0600 ..System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Receive() -> 105#105System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Send()System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::SendSystem.Net.Sockets Verbose: 0 : [0992] 00000000 : 45 48 4C 4F 20 77 32 6B-0D 0A : EHLO w2k..System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Send() -> 10#10System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Receive()System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::ReceiveSystem.Net.Sockets Verbose: 0 : [0992] 00000000 : 32 35 30 2D 77 32 6B 20-48 65 6C 6C 6F 20 5B 31 : 250-w2k Hello [1System.Net.Sockets Verbose: 0 : [0992] 00000010 : 32 37 2E 30 2E 30 2E 31-5D 0D 0A 32 35 30 2D 41 : 27.0.0.1]..250-ASystem.Net.Sockets Verbose: 0 : [0992] 00000020 : 55 54 48 20 47 53 53 41-50 49 20 4E 54 4C 4D 20 : UTH GSSAPI NTLM System.Net.Sockets Verbose: 0 : [0992] 00000030 : 4C 4F 47 49 4E 0D 0A 32-35 30 2D 41 55 54 48 3D : LOGIN..250-AUTH=

Page 49: SMTP

System.Net.Sockets Verbose: 0 : [0992] 00000040 : 4C 4F 47 49 4E 0D 0A 32-35 30 2D 54 55 52 4E 0D : LOGIN..250-TURN.System.Net.Sockets Verbose: 0 : [0992] 00000050 : 0A 32 35 30 2D 41 54 52-4E 0D 0A 32 35 30 2D 53 : .250-ATRN..250-SSystem.Net.Sockets Verbose: 0 : [0992] 00000060 : 49 5A 45 20 32 30 39 37-31 35 32 0D 0A 32 35 30 : IZE 2097152..250System.Net.Sockets Verbose: 0 : [0992] 00000070 : 2D 45 54 52 4E 0D 0A 32-35 30 2D 50 49 50 45 4C : -ETRN..250-PIPELSystem.Net.Sockets Verbose: 0 : [0992] 00000080 : 49 4E 49 4E 47 0D 0A 32-35 30 2D 44 53 4E 0D 0A : INING..250-DSN..System.Net.Sockets Verbose: 0 : [0992] 00000090 : 32 35 30 2D 45 4E 48 41-4E 43 45 44 53 54 41 54 : 250-ENHANCEDSTATSystem.Net.Sockets Verbose: 0 : [0992] 000000A0 : 55 53 43 4F 44 45 53 0D-0A 32 35 30 2D 38 62 69 : USCODES..250-8biSystem.Net.Sockets Verbose: 0 : [0992] 000000B0 : 74 6D 69 6D 65 0D 0A 32-35 30 2D 42 49 4E 41 52 : tmime..250-BINARSystem.Net.Sockets Verbose: 0 : [0992] 000000C0 : 59 4D 49 4D 45 0D 0A 32-35 30 2D 43 48 55 4E 4B : YMIME..250-CHUNKSystem.Net.Sockets Verbose: 0 : [0992] 000000D0 : 49 4E 47 0D 0A 32 35 30-2D 56 52 46 59 0D 0A 32 : ING..250-VRFY..2System.Net.Sockets Verbose: 0 : [0992] 000000E0 : 35 30 20 4F 4B 0D 0A : 50 OK..System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Receive() -> 231#231System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Send()System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::SendSystem.Net.Sockets Verbose: 0 : [0992] 00000000 : 4D 41 49 4C 20 46 52 4F-4D 3A 3C 6D 65 40 6D 79 : MAIL FROM:..System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Send() -> 30#30System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Receive()System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::ReceiveSystem.Net.Sockets Verbose: 0 : [0992] 00000000 : 32 35 30 20 32 2E 31 2E-30 20 6D 65 40 6D 79 63 : 250 2.1.0 [email protected] Verbose: 0 : [0992] 00000010 : 6F 6D 70 61 6E 79 2E 63-6F 6D 2E 2E 2E 2E 53 65 : ompany.com....SeSystem.Net.Sockets Verbose: 0 : [0992] 00000020 : 6E 64 65 72 20 4F 4B 0D-0A : nder OK..System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Receive() -> 41#41System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Send()System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::SendSystem.Net.Sockets Verbose: 0 : [0992] 00000000 : 52 43 50 54 20 54 4F 3A-3C 68 69 6D 40 68 69 73 : RCPT TO:..System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Send() -> 30#30

Page 50: SMTP

System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Receive()System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::ReceiveSystem.Net.Sockets Verbose: 0 : [0992] 00000000 : 35 35 30 20 35 2E 37 2E-31 20 55 6E 61 62 6C 65 : 550 5.7.1 UnableSystem.Net.Sockets Verbose: 0 : [0992] 00000010 : 20 74 6F 20 72 65 6C 61-79 20 66 6F 72 20 68 69 : to relay for hiSystem.Net.Sockets Verbose: 0 : [0992] 00000020 : 6D 40 68 69 73 63 6F 6D-70 61 6E 79 2E 63 6F 6D : [email protected] Verbose: 0 : [0992] 00000030 : 0D 0A : ..System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Receive() -> 50#50System.Net Error: 0 : [0992] Exception in the SmtpClient#47606018::Send - Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected] Error: 0 : [0992] at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message)System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Dispose()System.Net Verbose: 0 : [0992] Exiting SmtpClient#47606018::Send() In this example, an exception was actually thrown. The exception basically said I don't have permission to relay through the mail server to send email.

Page 51: SMTP

4.11 How do I encrypt messages using s/mime or pgp? You can't. System.Net.Mail does not support encrypted messages.

Page 52: SMTP

4.2 How do I authenticate to send an email? To authenticate with System.Net.Mail is much more intuitive than it was with System.Web.Mail. No longer do you have to set a fields property. Instead, you simply create a NetworkCredential's object, and set the username and password. Below is an example setting the username and password.[ C# ] static void Authenticate(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");

//to authenticate we set the username and password properites on the SmtpClientsmtp.Credentials = new NetworkCredential("username", "secret"); smtp.Send(mail);

}

[ VB.NET ] Sub Authenticate()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'send the messageDim smtp As New SmtpClient("127.0.0.1")

Page 53: SMTP

'to authenticate we set the username and password properites on the SmtpClientsmtp.Credentials = New NetworkCredential("username", "secret")smtp.Send(mail)End Sub 'Authenticate

Page 54: SMTP

4.3 How do I change the SMTP port number? Changing the SMTP port (the port email will be sent to), is also much easier than it was in System.Web.Mail. In System.Net.Mail, you simply set the .Port property on the SmtpClient object. Below is an example that changes the SMTP port to the lesser used port number 587.[ C# ] static void ChangePort(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1");

//to change the port (default is 25), we set the port propertysmtp.Port = 587;smtp.Send(mail);}

[ VB.NET ] Sub ChangePort()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'send the messageDim smtp As New SmtpClient("127.0.0.1")

'to change the port (default is 25), we set the port property

Page 55: SMTP

smtp.Port = 587smtp.Send(mail)End Sub 'ChangePort

Page 56: SMTP

4.4 How do I embed images in an email? Embedding images is something that is new with System.Net.Mail. To embed an image you will need to Create a LinkedResource object. The LinkedResource will actually contain the binary data of the Image. This binary data is encoded as part of the email, and sent along as part of the MailMessage. Give the LinkedResource a unique name, also known as a Content-Id. Create a HTML AlternateView. Inside that HTML text, you need to use the standard <img> tag. For the "src" value, you need to point it at the Content-Id of the LinkedResource image. This is done by using the syntax <img src="cid:whatever"> The "src=cid:" part is required for the email client to recognize the <img> tag as an embedded image, while the "whatever" part is the actual Content-Id of the LinkedResource image.  This will instruct the mail client to find an embedded image named "whatever" and display the contents *without* making a http:// request. That's all there is to create a linked image. Below is a short but complete example that demonstrates creating an embedded image. [ C# ] static void EmbedImages(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";

//first we create the Plain Text partAlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");

//then we create the Html part//to embed images, we need to use the prefix 'cid' in the img src value//the cid value will map to the Content-Id of a Linked resource.//thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo'AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.<img src=cid:companylogo>", null, "text/html");

//create the LinkedResource (embedded image)LinkedResource logo = new LinkedResource( "c:\\temp\\logo.gif" );logo.ContentId = "companylogo";//add the LinkedResource to the appropriate view

Page 57: SMTP

htmlView.LinkedResources.Add(logo);

//add the viewsmail.AlternateViews.Add(plainView);mail.AlternateViews.Add(htmlView);

//send the messageSmtpClient smtp = new SmtpClient("127.0.0.1"); //specify the mail server addresssmtp.Send(mail);}

[ VB.NET ] Sub EmbedImages()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"

'first we create the Plain Text partDim plainView As AlternateView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", Nothing, "text/plain")

'then we create the Html part'to embed images, we need to use the prefix 'cid' in the img src value'the cid value will map to the Content-Id of a Linked resource.'thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo'Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.<img src=cid:companylogo>", Nothing, "text/html")

'create the LinkedResource (embedded image)Dim logo As New LinkedResource("c:\temp\logo.gif")logo.ContentId = "companylogo"'add the LinkedResource to the appropriate viewhtmlView.LinkedResources.Add(logo)

'add the views

Page 58: SMTP

mail.AlternateViews.Add(plainView)mail.AlternateViews.Add(htmlView)

'send the messageDim smtp As New SmtpClient("127.0.0.1") 'specify the mail server addresssmtp.Send(mail)End Sub 'EmbedImages

Page 59: SMTP

4.5 How do I send an email over SSL? Sending an email over Ssl is really simply with System.Net.Mail. In fact, all you need to do is set the .EnableSsl property on the SmtpClient property to true. Below you will find an example of of SMTP over SSL. Note: Due to what I believe is a bug in System.Net.Mail you *cannot* use SSL and Credentials (username/password) at the same time. I was never able to get that to work. I always got an exception from the remote mail server. I believe it has to do with the steps System.Net.Mail takes to initiate the SSL session and SMTP authentication.[ C# ] static void SSL(){//create the mail messageMailMessage mail = new MailMessage();

//set the addressesmail.From = new MailAddress("[email protected]");mail.To.Add("[email protected]");

//set the contentmail.Subject = "This is an email";mail.Body = "this is the body content of the email.";

//Port 587 is another SMTP portSmtpClient smtp = new SmtpClient("127.0.01", 587);smtp.EnableSsl = true;smtp.Send(mail);}

[ VB.NET ] Sub SSL()'create the mail messageDim mail As New MailMessage()

'set the addressesmail.From = New MailAddress("[email protected]")mail.To.Add("[email protected]")

'set the contentmail.Subject = "This is an email"mail.Body = "this is the body content of the email."

'Port 587 is another SMTP portDim smtp As New SmtpClient("127.0.0.1", 587)smtp.EnableSsl = True

Page 60: SMTP

smtp.Send(mail)End Sub

Page 61: SMTP

4.6 How do I send email asynchronously? System.Net.Mail has also added asynchronous support for sending email. To send asynchronously, you need need to Wire up a SendCompleted event Create the SendCompleted event Call SmtpClient.SendAsync These steps are demonstrated in the code below.[ C# ] static void SendAsync() { //create the mail message MailMessage mail = new MailMessage();

//set the addresses mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]");

//set the content mail.Subject = "This is an email"; mail.Body = "this is the body content of the email.";

//send the message SmtpClient smtp = new SmtpClient("127.0.0.1"); //specify the mail server address //the userstate can be any object. The object can be accessed in the callback method //in this example, we will just use the MailMessage object. object userState = mail;

//wire up the event for when the Async send is completed smtp.SendCompleted += new SendCompletedEventHandler(SmtpClient_OnCompleted);

smtp.SendAsync( mail, userState ); } public static void SmtpClient_OnCompleted(object sender, AsyncCompletedEventArgs e) { //Get the Original MailMessage object MailMessage mail= (MailMessage)e.UserState;

//write out the subject string subject = mail.Subject;

if (e.Cancelled) { Console.WriteLine("Send canceled for mail with subject [{0}].", subject);

Page 62: SMTP

} if (e.Error != null) { Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString()); } else { Console.WriteLine("Message [{0}] sent.", subject ); } }

[ VB.NET ] Sub SendAsync() 'create the mail message Dim mail As New MailMessage()

'set the addresses mail.From = New MailAddress("[email protected]") mail.To.Add("[email protected]")

'set the content mail.Subject = "This is an email" mail.Body = "this is the body content of the email."

'send the message Dim smtp As New SmtpClient("127.0.0.1") 'specify the mail server address 'the userstate can be any object. The object can be accessed in the callback method 'in this example, we will just use the MailMessage object. Dim userState As Object = mail

'wire up the event for when the Async send is completed AddHandler smtp.SendCompleted, AddressOf SmtpClient_OnCompleted

smtp.SendAsync(mail, userState) End Sub 'SendAsync

Public Sub SmtpClient_OnCompleted(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs) 'Get the Original MailMessage object Dim mail As MailMessage = CType(e.UserState, MailMessage)

'write out the subject Dim subject As String = mail.Subject

Page 63: SMTP

If e.Cancelled Then Console.WriteLine("Send canceled for mail with subject [{0}].", subject) End If If Not (e.Error Is Nothing) Then Console.WriteLine("Error {1} occurred when sending mail [{0}] ", subject, e.Error.ToString()) Else Console.WriteLine("Message [{0}] sent.", subject) End If End Sub 'SmtpClient_OnCompleted

Page 64: SMTP

4.7 How do I write to the Pickup directory? Writing email to the IIS Server's SMTP service pickup directory is another new feature of System.Net.Mail. The SMTP pickup directory is a special directory used by Microsoft's SMTP service to send email. Any email files found in that directory are processed and delivered over SMTP. If the delivery process fails, the files are stored in a queue directory for delivery at another time. If a fatal error occurs (such as a DNS resolution error), the files are moved to the Badmail directory.By writing to the pickup directory, this speeds up the process because the entire chatting SMTP layer used for relaying is by passed. Below is an example of how to write directly to the Pickup directory.[ C# ] public static void PickupDirectory() { //create the mail message MailMessage mail = new MailMessage();

//set the addresses mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]");

//set the content mail.Subject = "This is an email"; mail.Body = "this is the body content of the email.";

//if we are using the IIS SMTP Service, we can write the message //directly to the PickupDirectory, and bypass the Network layer SmtpClient smtp = new SmtpClient(); smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis; smtp.Send(mail); }

[ VB.NET ] Public Sub PickupDirectory() 'create the mail message Dim mail As New MailMessage()

'set the addresses mail.From = New MailAddress("[email protected]") mail.To.Add("[email protected]")

'set the content mail.Subject = "This is an email" mail.Body = "this is the body content of the email."

Page 65: SMTP

'if we are using the IIS SMTP Service, we can write the message 'directly to the PickupDirectory, and bypass the Network layer Dim smtp As New SmtpClient() smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis smtp.Send(mail) End Sub 'PickupDirectory

Page 66: SMTP

4.8 How do I send a web page? System.Net.Mail does not natively support sending a web page. However, using the WebRequest class, you can screen scrape web pages, and pass the resulting Html string to the MailMessage object. The following example demonstrates this technique.

Note: Be sure to import the System.Net and System.IO namespaces for this code snippet. [ C# ] public static void EmailWebPage() { //create the mail message MailMessage mail = new MailMessage();

//set the addresses mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]");

//set the content mail.Subject = "This is an email";

//screen scrape the html string html = ScreenScrapeHtml("http://localhost/example.htm"); mail.Body = html; mail.IsBodyHtml = true;

//send the message SmtpClient smtp = new SmtpClient("127.0.0.1"); smtp.Send(mail);

} public static string ScreenScrapeHtml(string url) { WebRequest objRequest = System.Net.HttpWebRequest.Create(url); StreamReader sr = new StreamReader(objRequest.GetResponse().GetResponseStream()); string result = sr.ReadToEnd(); sr.Close(); return result; }

[ VB.NET ] Public Sub EmailWebPage() 'create the mail message Dim mail As New MailMessage()

'set the addresses

Page 67: SMTP

mail.From = New MailAddress("[email protected]") mail.To.Add("[email protected]")

'set the content mail.Subject = "This is an email"

'screen scrape the html Dim html As String = ScreenScrapeHtml("http://localhost/example.htm") mail.Body = html mail.IsBodyHtml = True

'send the message Dim smtp As New SmtpClient("127.0.0.1") smtp.Send(mail) End Sub 'EmailWebPage

Public Function ScreenScrapeHtml(ByVal url As String) As String Dim objRequest As WebRequest = System.Net.HttpWebRequest.Create(url) Dim sr As New StreamReader(objRequest.GetResponse().GetResponseStream()) Dim result As String = sr.ReadToEnd() sr.Close() Return result End Function 'ScreenScrapeHtml

Page 68: SMTP

4.9 How do I send non US-ASCII emails? In the beginning, when email was first being used, it was all us-ascii content. To handle different languages and character sets, different encodings must be used. The following example demonstrates sending a non us-ascii email, using the ISO-8859-1 character set as an example. The hardest part of sending non us-ascii email, is to determine the correct character set. For reference, an easy to use character set chart can be found at aspNetEmail's website, here: http://www.aspnetemail.com/charsets.aspx .

The following example demonstrates this technique.

[ C# ] public static void NonAsciiMail() { //create the mail message MailMessage mail = new MailMessage();

//set the addresses mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]");

//set the content mail.Subject = "This is an email";

//to send non-ascii content, we need to set the encoding that matches the //string characterset. //In this example we use the ISO-8859-1 characterset mail.Body = "this text has some ISO-8859-1 characters: âÒÕÇ"; mail.BodyEncoding = Encoding.GetEncoding("iso-8859-1");

//send the message SmtpClient smtp = new SmtpClient("127.0.0.1"); smtp.Send(mail);

}

[ VB.NET ] Public Sub NonAsciiMail() 'create the mail message Dim mail As New MailMessage()

'set the addresses mail.From = New MailAddress("[email protected]") mail.To.Add("[email protected]")

'set the content mail.Subject = "This is an email"

Page 69: SMTP

'to send non-ascii content, we need to set the encoding that matches the 'string characterset. 'In this example we use the ISO-8859-1 characterset mail.Body = "this text has some ISO-8859-1 characters: âÒÕÇ" mail.BodyEncoding = Encoding.GetEncoding("iso-8859-1")

'send the message Dim smtp As New SmtpClient("127.0.0.1") smtp.Send(mail) End Sub 'NonAsciiMail

Page 70: SMTP

5 Troubleshooting System.Net.Mail* You Are Here * [ Scroll To Answer ] 5.1 Bccs are not so blind.5.2 Cannot enable SSL with a username and password.5.3 System.Net.Mail with SSL to authenticate against port 465

5 Troubleshooting System.Net.Mail System.Net.Mail seems like a pretty stable class of email objects. There are a few known issues. I'm sure more will crop up over time. At the time I put this FAQ together, System.Net.Mail has been out of beta for less than 30 days. Check the forums for more ideas and help.If you do get any exceptions, be sure to always check the inner exception for more additional information. Usually the inner exceptions will provide the additional information to solve your problem. Here's a code example for checking inner exceptions in a console application. If you want to use this code in an ASP.NET page, be sure to change Console.WriteLine(...) to Response.Write(...).[ C# ] public static void InnerExceptions() { //create the mail message MailMessage mail = new MailMessage();

//set the addresses mail.From = new MailAddress("[email protected]"); mail.To.Add("[email protected]");

//set the content mail.Subject = "This is an email"; mail.Body = "this is the body content of the email.";

//send the message SmtpClient smtp = new SmtpClient("127.0.0.1"); try { smtp.Send(mail); } catch (Exception ex) { Exception ex2 = ex; string errorMessage = string.Empty; while (ex2 != null) { errorMessage += ex2.ToString(); ex2 = ex2.InnerException; }

Page 71: SMTP

Console.WriteLine(errorMessage); } }

[ VB.NET ] Public Shared Sub InnerExceptions() 'create the mail message Dim mail As New MailMessage() 'set the addresses mail.From = New MailAddress("[email protected]") mail.To.Add("[email protected]") 'set the content mail.Subject = "This is an email" mail.Body = "this is the body content of the email." 'send the message Dim smtp As New SmtpClient("127.0.0.1") Try smtp.Send(mail) Catch ex As Exception Dim ex2 As Exception = ex Dim errorMessage As String = String.Empty While Not (ex2 Is Nothing) errorMessage += ex2.ToString() ex2 = ex2.InnerException End While Console.WriteLine(errorMessage) End TryEnd Sub 'InnerExceptions

Page 72: SMTP

5.1 Bccs are not so blind. Bcc stands for Blind Carbon Copy. You typically BCC someone on an email when you don't want any of the other recipients to know someone else is being copied on the email. Unfortunately there is a bug in System.Net.Mail when you BCC someone. If you look at the raw headers of the sent mail message you will see X-Receiver header for everyone that was sent the message. This includes the To, CC, and BCC addresses. Thus anyone who was BCC'd on the message is recorded in headers.

Page 73: SMTP

5.2 Cannot enable SSL with a username and password. I don't really know if this is a problem or not, but I have not been able to enable SSL and also use a username/password for authentication. I believe this has to do with the order in which System.Net.Mail sends the commands to the SMTP server. For whatever reason I received an "Authentication failed" exception from the remote SMTP server. As soon as I turned SSL off, everything worked. If I didn't set a username/password, the SSL session worked just fine. It was the combination of SSL and a username/password that wouldn't let me email.

Page 74: SMTP

5.3 System.Net.Mail with SSL to authenticate against port 465 This is an excellent blog post from http://blogs.msdn.com/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx

Dan does a good job explaining the implicit SSL limitation of System.Net.Mail.

System.Net.Mail with SSL to authenticate against port 465 Sending mail using System.Net.Mail with SSL will fail:

System.Net.NetworkCredential aCred = new System.Net.NetworkCredential("myacct", "mypassword");SmtpClient smtp = new SmtpClient("smtp.mail.myserver.com", 465); smtp.EnableSsl = true; smtp.UseDefaultCredentials = false; smtp.Credentials = aCred;System.Net.Mail only supports "Explicit SSL".

Explicit SSLSystem.Net.Mail only supports "Explicit SSL". Explicit SSL starts as unencrypted on port 25, then issues a STARTDLS and switches to an Encrypted connection. See RFC 2228.Explicit SLL would go something like: Connect on 25 -> StartTLS (starts to encrypt) -> authenticate -> send dataIf the SMTP server expects SSL/TLS connection right from the start then this will not work.

Implicit SSLThere is no way to use Implicit SSL (SMTPS) with System.Net.Mail. Implicit SSL would have the entire connection is wrapped in an SSL layer. A specific port would be used (port 465 is common). There is no formal RFC covering Implicit SSL.Implicit SLL would go something like: Start SSL (start encryption) -> Connect -> Authenticate -> send data

This is not considered a bug, it’s a feature request. There are two types of SSL authentication for SMTP, and we only support one (by design) – Explicit SSL.  

Page 75: SMTP

6 Additional Help The following list of links are places to find additional information on System.Net.MailSystem.Net.Mail ForumsYou can use the forums found on this site for discussing different System.Net.Mail issues. The forums are found here:http://www.SystemNetMail.com/forums.aspx Yahoo ASP.NET Email Peer-To-Peer support group. We discuss anything .NET and email related here:http://groups.yahoo.com/group/aspnetemail/ Search the internet using Google for System.Net.Mail resources here:http://www.google.com/search?sourceid=navclient&ie=UTF-8&rls=GGLG,GGLG:2005-30,GGLG:en&q=System%2ENet%2EMail Search the Microsoft .NET Newsgroups (using google) for various System.Net.Mail keywords.MailMessagehttp://groups.google.as/groups?q=group%3Amicrosoft.public.dotnet.*+MailMessage&start=0&scoring=d&hl=en&lr=&safe=off&num=10&

SmtpClienthttp://groups.google.as/groups?q=group%3Amicrosoft.public.dotnet.*+SmtpClient&start=0&scoring=d&hl=en&lr=&safe=off&num=10&

AlternateViewhttp://groups.google.as/groups?q=group%3Amicrosoft.public.dotnet.*+AlternateView&start=0&scoring=d&hl=en&lr=&safe=off&num=10&  MSDN Documentation on various System.Net.Mail classes.AlternateViewhttp://msdn2.microsoft.com/en-us/library/ms144582(en-US,VS.80).aspx

Attachmenthttp://msdn2.microsoft.com/en-us/library/e02kz1ak(en-US,VS.80).aspx

LinkedResourcehttp://msdn2.microsoft.com/en-us/library/ms144655(en-US,VS.80).aspx

MailMessagehttp://msdn2.microsoft.com/en-us/library/8t22a8ww(en-US,VS.80).aspx

SmtpClienthttp://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx

Page 76: SMTP
Page 77: SMTP

Another function to send simple mailImports System.Net.Mail

Public Shared Function SendMail(ByVal MailFrom As String, ByVal MailTo As String, ByVal MailSubject As String, ByVal MailBody As String, Optional ByVal MailCC As String = "", Optional ByVal MailBCC As String = "", Optional ByVal MyMailPriority As MailPriority = MailPriority.Normal, Optional ByVal IsBodyHtml As Boolean = False, Optional ByVal Attachment1 As String = "-999", Optional ByVal Attachment2 As String = "-999", Optional ByVal Attachment3 As String = "-999", Optional ByVal MailFromName As String = "-999") As Boolean Try Dim ObjSendMail As New MailMessage(MailFrom, MailTo, MailSubject, MailBody) If MailFromName <> "-999" Then ObjSendMail.From = New MailAddress(MailFrom, MailFromName) End If If Attachment1 <> "-999" Then Try ObjSendMail.Attachments.Add(New Attachment(Attachment1)) Catch ex As Exception End Try End If If Attachment2 <> "-999" Then Try ObjSendMail.Attachments.Add(New Attachment(Attachment2)) Catch ex As Exception End Try End If If Attachment3 <> "-999" Then Try ObjSendMail.Attachments.Add(New Attachment(Attachment3)) Catch ex As Exception End Try End If If IsBodyHtml = True Then ObjSendMail.IsBodyHtml = True Else ObjSendMail.IsBodyHtml = False End If If MailCC > "" Then ObjSendMail.CC.Add(MailCC) End If If MailBCC > "" Then ObjSendMail.Bcc.Add(MailBCC) End If ObjSendMail.Priority = MyMailPriority

Page 78: SMTP

Dim client As New SmtpClient(mysmtpserver) client.Send(ObjSendMail) Return True Catch ex As Exception Return False End Try End Function


Recommended