Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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?
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.
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:
MailMessage
MailAddress
Attachment
SmtpClient
AlternateView
LinkedResource
2.1 MailMessage Class
The 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
Gets the attachment collection used to store data attached to this e-
Attachments
mail message.
Gets the address collection that contains the blind carbon copy
Bcc
(BCC) recipients for this e-mail message.
Body Gets or sets the message body.
Gets the address collection that contains the carbon copy (CC)
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.
Gets the address collection that contains the recipients of this e-mail
To
message.
Below you will find an example of using the MailMessage class
[ C# ]
static void PlainText()
{
//create the mail message
MailMessage mail = new MailMessage();
[ VB.NET ]
Sub PlainText()
'create the mail message
Dim mail As New MailMessage()
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.
//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 times
mail.To.Add("you@yourcompany.com");
mail.To.Add("you2@yourcompany.com");
mail.CC.Add("cc1@yourcompany.com");
mail.CC.Add("cc2@yourcompany.com");
mail.Bcc.Add("blindcc1@yourcompany.com");
mail.Bcc.Add("blindcc2@yourcompany.com");
'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 times
mail.To.Add("you@yourcompany.com")
mail.To.Add("you2@yourcompany.com")
mail.CC.Add("cc1@yourcompany.com")
mail.CC.Add("cc2@yourcompany.com")
mail.Bcc.Add("blindcc1@yourcompany.com")
mail.Bcc.Add("blindcc2@yourcompany.com")
[ C# ]
static void AttachmentFromFile()
{
//create the mail message
MailMessage mail = new MailMessage();
[ VB.NET ]
Sub AttachmentFromFile()
'create the mail message
Dim mail As New MailMessage()
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.
//to authenticate we set the username and password properites on the SmtpClient
smtp.Credentials = new NetworkCredential("username", "secret");
smtp.Send(mail);
}
[ VB.NET ]
Sub Authenticate()
'create the mail message
Dim mail As New MailMessage()
'to authenticate we set the username and password properites on the SmtpClient
smtp.Credentials = New NetworkCredential("username", "secret")
smtp.Send(mail)
End Sub 'Authenticate
2.5 AlternateView Class
Name Description
BaseUri Gets or sets the Base URI to use for resolving
relative URIs in the AlternateView
LinkedResources Gets the set of embedded resources referred to by
this attachment.
CreateAlternateViewFromString (static Overloaded. Creates an AlternateView to view
method) an email message using the specified format..
Below is an example demonstrating the AlternateView class.
[ C# ]
static void MultiPartMime()
{
//create the mail message
MailMessage mail = new MailMessage();
[ VB.NET ]
Sub EmbedImages()
'create the mail message
Dim mail As New MailMessage()
[ C# ]
//create the mail message
MailMessage mail = new MailMessage();
[ VB.NET ]
'create the mail message
Dim mail As New MailMessage()
[ C# ]
//create the mail message
MailMessage mail = new MailMessage();
[ VB.NET ]
'create the mail message
Dim mail As New MailMessage()
[ C# ]
static void MultiPartMime()
{
//create the mail message
MailMessage mail = new MailMessage();
[ VB.NET ]
Sub MultiPartMime()
'create the mail message
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("me@mycompany.com")
mail.To.Add("you@yourcompany.com")
[ VB.NET ]
Sub FriendlyFromName()
'create the mail message
Dim mail As New MailMessage()
//since the To,Cc, and Bcc accept addresses, we can use the same technique as the From
address
mail.To.Add( new MailAddress( "you@yourcompany.com", "Beth Jones") );
mail.CC.Add(new MailAddress("donna@yourcompany.com", "Donna Summers"));
mail.Bcc.Add(new MailAddress("bob@yourcompany.com", "Bob Smith"));
[ VB.NET ]
Sub FriendlyToName()
'create the mail message
Dim mail As New MailMessage()
'since the To,Cc, and Bcc accept addresses, we can use the same technique as the From
address
mail.To.Add(New MailAddress("you@yourcompany.com", "Beth Jones"))
mail.CC.Add(New MailAddress("donna@yourcompany.com", "Donna Summers"))
mail.Bcc.Add(New MailAddress("bob@yourcompany.com", "Bob Smith"))
'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."
//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 times
mail.To.Add("you@yourcompany.com");
mail.To.Add("you2@yourcompany.com");
mail.CC.Add("cc1@yourcompany.com");
mail.CC.Add("cc2@yourcompany.com");
mail.Bcc.Add("blindcc1@yourcompany.com");
mail.Bcc.Add("blindcc2@yourcompany.com");
[ VB.NET ]
Sub MultipleRecipients()
'create the mail message
Dim mail As New MailMessage()
[ VB.NET ]
Sub FriendlyNonAsciiName()
'create the mail message
Dim mail As New MailMessage()
[ VB.NET ]
Sub SetPriority()
'create the mail message
Dim mail As New MailMessage()
[ VB.NET ]
Sub SetTheReplyToHeader()
'create the mail message
Dim mail As New MailMessage()
//To request a read receipt, we need add a custom header named 'Disposition-
Notification-To'
//in this example, read receipts will go back to 'someaddress@mydomain.com'
//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", "<someaddress@mydomain.com>");
[ VB.NET ]
Sub ReadReceipts()
'create the mail message
Dim mail As New MailMessage()
'set the addresses
mail.From = New MailAddress("me@mycompany.com")
mail.To.Add("you@yourcompany.com")
'To request a read receipt, we need add a custom header named 'Disposition-Notification-
To'
'in this example, read receipts will go back to 'someaddress@mydomain.com'
'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", "<someaddress@mydomain.com>")
//to add custom headers, we use the Headers.Add(...) method to add headers to the
//.Headers collection
mail.Headers.Add("X-Company", "My Company");
mail.Headers.Add("X-Location", "Hong Kong");
[ VB.NET ]
Sub CustomHeaders()
'create the mail message
Dim mail As New MailMessage()
'to add custom headers, we use the Headers.Add(...) method to add headers to the
'.Headers collection
mail.Headers.Add("X-Company", "My Company")
mail.Headers.Add("X-Location", "Hong Kong")
[ C# ]
static void AttachmentFromFile()
{
//create the mail message
MailMessage mail = new MailMessage();
[ VB.NET ]
Sub AttachmentFromFile()
'create the mail message
Dim mail As New MailMessage()
[ VB.NET ]
Sub AttachmentFromStream()
'create the attachment from a stream. Be sure to name the data with a file and
'media type that is respective of the data
mail.Attachments.Add(New Attachment(ms, "example.txt", "text/plain"))
System.Net.Configuration.MailSettingsSectionGroup mMailSettings;
[ VB.NET ]
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="me@mycompany.com">
--
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="admin@example.com">
<network defaultCredentials="true" host="smtp.example.com" port="25"
userName="admin@example.com" password="password"/>
</smtp>
</mailSettings>
</system.net>
</location>
<location path="SomeDirectory/Page2.aspx">
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sales@example.com">
<network defaultCredentials="true" host="smtp.example.com" port="25"
userName="sales@example.com" password="password"/>
</smtp>
</mailSettings>
</system.net>
</location>
<location path="SomeDirectory/Page3.aspx">
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="info@example.com">
<network defaultCredentials="true" host="smtp.example.com" port="25"
userName="info@example.com" password="password"/>
</smtp>
</mailSettings>
</system.net>
</location>
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.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#5689696
System.Net Verbose: 0 : [0992] Exiting SmtpClient::.ctor() -> SmtpClient#47606018
System.Net Verbose: 0 : [0992] SmtpClient#47606018::Send(MailMessage#5138334)
System.Net Information: 0 : [0992]
SmtpClient#47606018::Send(DeliveryMethod=Network)
System.Net Information: 0 : [0992] Associating SmtpClient#47606018 with
MailMessage#5138334
System.Net Information: 0 : [0992] Associating SmtpTransport#5689696 with
SmtpConnection#31950948
System.Net Information: 0 : [0992] Associating SmtpConnection#31950948 with
ServicePoint#34920472
System.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#48167163
System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Receive()
System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::Receive
System.Net.Sockets Verbose: 0 : [0992] 00000000 : 32 32 30 20 77 32 6B 20-4D 69 63
72 6F 73 6F 66 : 220 w2k Microsof
System.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 Ser
System.Net.Sockets Verbose: 0 : [0992] 00000020 : 76 69 63 65 2C 20 56 65-72 73 69
6F 6E 3A 20 35 : vice, Version: 5
System.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 rea
System.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 D
System.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:14
System.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#105
System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Send()
System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::Send
System.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#10
System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Receive()
System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::Receive
System.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 [1
System.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-A
System.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=
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-S
System.Net.Sockets Verbose: 0 : [0992] 00000060 : 49 5A 45 20 32 30 39 37-31 35 32
0D 0A 32 35 30 : IZE 2097152..250
System.Net.Sockets Verbose: 0 : [0992] 00000070 : 2D 45 54 52 4E 0D 0A 32-35 30 2D
50 49 50 45 4C : -ETRN..250-PIPEL
System.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-ENHANCEDSTAT
System.Net.Sockets Verbose: 0 : [0992] 000000A0 : 55 53 43 4F 44 45 53 0D-0A 32 35
30 2D 38 62 69 : USCODES..250-8bi
System.Net.Sockets Verbose: 0 : [0992] 000000B0 : 74 6D 69 6D 65 0D 0A 32-35 30 2D
42 49 4E 41 52 : tmime..250-BINAR
System.Net.Sockets Verbose: 0 : [0992] 000000C0 : 59 4D 49 4D 45 0D 0A 32-35 30 2D
43 48 55 4E 4B : YMIME..250-CHUNK
System.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..2
System.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#231
System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Send()
System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::Send
System.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#30
System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Receive()
System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::Receive
System.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 me@myc
System.Net.Sockets Verbose: 0 : [0992] 00000010 : 6F 6D 70 61 6E 79 2E 63-6F 6D 2E
2E 2E 2E 53 65 : ompany.com....Se
System.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#41
System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Send()
System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::Send
System.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
System.Net.Sockets Verbose: 0 : [0992] Socket#22453229::Receive()
System.Net.Sockets Verbose: 0 : [0992] Data from Socket#22453229::Receive
System.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 Unable
System.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 hi
System.Net.Sockets Verbose: 0 : [0992] 00000020 : 6D 40 68 69 73 63 6F 6D-70 61 6E
79 2E 63 6F 6D : m@hiscompany.com
System.Net.Sockets Verbose: 0 : [0992] 00000030 : 0D 0A : ..
System.Net.Sockets Verbose: 0 : [0992] Exiting Socket#22453229::Receive() ->
50#50
System.Net Error: 0 : [0992] Exception in the SmtpClient#47606018::Send - Mailbox
unavailable. The server response was: 5.7.1 Unable to relay for him@hiscompany.com
System.Net 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.
4.11 How do I encrypt messages using s/mime or pgp?
You can't. System.Net.Mail does not support encrypted messages.
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 message
MailMessage mail = new MailMessage();
//to authenticate we set the username and password properites on the SmtpClient
smtp.Credentials = new NetworkCredential("username", "secret");
smtp.Send(mail);
[ VB.NET ]
Sub Authenticate()
'create the mail message
Dim mail As New MailMessage()
//to change the port (default is 25), we set the port property
smtp.Port = 587;
smtp.Send(mail);
}
[ VB.NET ]
Sub ChangePort()
'create the mail message
Dim mail As New MailMessage()
'to change the port (default is 25), we set the port property
smtp.Port = 587
smtp.Send(mail)
End Sub 'ChangePort
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 message
MailMessage mail = new MailMessage();
[ VB.NET ]
Sub EmbedImages()
'create the mail message
Dim mail As New MailMessage()
[ VB.NET ]
Sub SSL()
'create the mail message
Dim mail As New MailMessage()
if (e.Cancelled)
{
Console.WriteLine("Send canceled for mail with subject [{0}].", subject);
}
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()
smtp.SendAsync(mail, userState)
End Sub 'SendAsync
//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()
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();
}
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()
[ C# ]
public static void NonAsciiMail()
{
//create the mail message
MailMessage mail = new MailMessage();
//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");
[ VB.NET ]
Public Sub NonAsciiMail()
'create the mail message
Dim mail As New MailMessage()
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();
[ VB.NET ]
Public Shared Sub InnerExceptions()
'create the mail message
Dim mail As New MailMessage()
Console.WriteLine(errorMessage)
End Try
End Sub 'InnerExceptions
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.
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.
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.
Explicit SSL
System.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 data
If the SMTP server expects SSL/TLS connection right from the start then this will not
work.
Implicit SSL
There 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.
6 Additional Help
The following list of links are places to find additional information on System.Net.Mail
System.Net.Mail Forums
You 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 Microsoft .NET Newsgroups (using google) for various System.Net.Mail
keywords.
MailMessage
http://groups.google.as/groups?q=group
%3Amicrosoft.public.dotnet.*+MailMessage&start=0&scoring=d&hl=en&lr=&safe=off
&num=10&
SmtpClient
http://groups.google.as/groups?q=group
%3Amicrosoft.public.dotnet.*+SmtpClient&start=0&scoring=d&hl=en&lr=&safe=off&
num=10&
AlternateView
http://groups.google.as/groups?q=group
%3Amicrosoft.public.dotnet.*+AlternateView&start=0&scoring=d&hl=en&lr=&safe=of
f&num=10&
Attachment
http://msdn2.microsoft.com/en-us/library/e02kz1ak(en-US,VS.80).aspx
LinkedResource
http://msdn2.microsoft.com/en-us/library/ms144655(en-US,VS.80).aspx
MailMessage
http://msdn2.microsoft.com/en-us/library/8t22a8ww(en-US,VS.80).aspx
SmtpClient
http://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx
Another function to send simple mail
Imports System.Net.Mail