.NET Framework Class Library
MailMessage Class

Represents an e-mail message that can be sent using the SmtpClient class.

Namespace:  System.Net.Mail
Assembly:  System (in System.dll)
Syntax

Visual Basic (Declaration)
Public Class MailMessage _
    Implements IDisposable
Visual Basic (Usage)
Dim instance As MailMessage
C#
public class MailMessage : IDisposable
Visual C++
public ref class MailMessage : IDisposable
JScript
public class MailMessage implements IDisposable
Remarks

Instances of the MailMessage class are used to construct e-mail messages that are transmitted to an SMTP server for delivery using the SmtpClient class.

To specify the sender, recipient, and contents of an e-mail message, use the associated properties of the MailMessage class.

Mail part

Property

Sender

From

Recipient

To

Carbon copies (CC)

CC

Blind carbon copies (BCC)

Bcc

Attachments

Attachments

Subject

Subject

Message body

Body

Use the AlternateViews property to specify copies of an e-mail message in different formats. For example, if you send a message in HTML, you might also want to provide a plain text version in case some of the recipients use e-mail readers that cannot display HTML content. For an example that demonstrates creating a message with alternate views, see AlternateViews.

After assembling your e-mail message, you can send it by using the Send or SendAsync methods.

Examples

The following code example demonstrates creating and sending an e-mail message that includes an attachment.

C#
        public static void CreateMessageWithAttachment(string server)
        {
            // Specify the file to be attached and sent.
            // This example assumes that a file named Data.xls exists in the
            // current working directory.
            string file = "data.xls";
            // Create a message and set up the recipients.
            MailMessage message = new MailMessage(
               "jane@contoso.com",
               "ben@contoso.com",
               "Quarterly data report.",
               "See the attached spreadsheet.");

            // Create  the file attachment for this e-mail message.
            Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
            // Add time stamp information for the file.
            ContentDisposition disposition = data.ContentDisposition;
            disposition.CreationDate = System.IO.File.GetCreationTime(file);
            disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
            disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
            // Add the file attachment to this e-mail message.
            message.Attachments.Add(data);

            //Send the message.
            SmtpClient client = new SmtpClient(server);
            // Add credentials if the SMTP server requires them.
            client.Credentials = CredentialCache.DefaultNetworkCredentials;

      try {
              client.Send(message);
            }
            catch (Exception ex) {
              Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", 
                    ex.ToString() );              
            }
            // Display the values in the ContentDisposition for the attachment.
            ContentDisposition cd = data.ContentDisposition;
            Console.WriteLine("Content disposition");
            Console.WriteLine(cd.ToString());
            Console.WriteLine("File {0}", cd.FileName);
            Console.WriteLine("Size {0}", cd.Size);
            Console.WriteLine("Creation {0}", cd.CreationDate);
            Console.WriteLine("Modification {0}", cd.ModificationDate);
            Console.WriteLine("Read {0}", cd.ReadDate);
            Console.WriteLine("Inline {0}", cd.Inline);
            Console.WriteLine("Parameters: {0}", cd.Parameters.Count);
            foreach (DictionaryEntry d in cd.Parameters)
            {
                Console.WriteLine("{0} = {1}", d.Key, d.Value);
            }
            data.Dispose();
        }
Visual C++
static void CreateMessageWithAttachment( String^ server )
{

   // Specify the file to be attached and sent.
   // This example assumes that a file named Data.xls exists in the
   // current working directory.
   String^ file = L"data.xls";

   // Create a message and set up the recipients.
   MailMessage^ message = gcnew MailMessage( L"jane@contoso.com",L"ben@contoso.com",L"Quarterly data report.",L"See the attached spreadsheet." );

   // Create  the file attachment for this e-mail message.
   Attachment^ data = gcnew Attachment(file, MediaTypeNames::Application::Octet);

   // Add time stamp information for the file.
   ContentDisposition^ disposition = data->ContentDisposition;
   disposition->CreationDate = System::IO::File::GetCreationTime( file );
   disposition->ModificationDate = System::IO::File::GetLastWriteTime( file );
   disposition->ReadDate = System::IO::File::GetLastAccessTime( file );

   // Add the file attachment to this e-mail message.
   message->Attachments->Add( data );

   //Send the message.
   SmtpClient^ client = gcnew SmtpClient( server );

   // Add credentials if the SMTP server requires them.
   client->Credentials = CredentialCache::DefaultNetworkCredentials;
   client->Send( message );

   // Display the values in the ContentDisposition for the attachment.
   ContentDisposition^ cd = data->ContentDisposition;
   Console::WriteLine( L"Content disposition" );
   Console::WriteLine( cd );
   Console::WriteLine( L"File {0}", cd->FileName );
   Console::WriteLine( L"Size {0}", cd->Size );
   Console::WriteLine( L"Creation {0}", cd->CreationDate );
   Console::WriteLine( L"Modification {0}", cd->ModificationDate );
   Console::WriteLine( L"Read {0}", cd->ReadDate );
   Console::WriteLine( L"Inline {0}", cd->Inline );
   Console::WriteLine( L"Parameters: {0}", cd->Parameters->Count );
   IEnumerator^ myEnum1 = cd->Parameters->GetEnumerator();
   while ( myEnum1->MoveNext() )
   {
      DictionaryEntry^ d = safe_cast<DictionaryEntry^>(myEnum1->Current);
      Console::WriteLine( L"{0} = {1}", d->Key, d->Value );
   }

   data->~Attachment();
   client->~SmtpClient();
}


CPP_OLD
public:
    static void CreateMessageWithAttachment(String* server)
    {
        // Specify the file to be attached and sent.
        // This example assumes that a file named Data.xls exists in the
        // current working directory.
        String* file = S"data.xls";
         // Create a message and set up the recipients.
         MailMessage* message = new MailMessage(
            S"jane@contoso.com", 
            S"ben@contoso.com",
            S"Quarterly data report.", 
            S"See the attached spreadsheet.");

        // Create  the file attachment for this e-mail message.
        Attachment* data = new Attachment();
        data->SetContentFromFile(file, 0, MediaTypeNames::Application::Octet);
        // Add time stamp information for the file.
        ContentDisposition* disposition = data->ContentDisposition;
        disposition->CreationDate = System::IO::File::GetCreationTime(file);
        disposition->ModificationDate = System::IO::File::GetLastWriteTime(file);
        disposition->ReadDate = System::IO::File::GetLastAccessTime(file);
        // Add the file attachment to this e-mail message.
        message->Attachments->Add(data);
        //Send the message.
        SmtpClient* client = new SmtpClient(server);
        // Add credentials if the SMTP server requires them.
        client->Credentials = CredentialCache::DefaultNetworkCredentials;
        client->Send(message);
        // Display the values in the ContentDisposition for the attachment.
        ContentDisposition* cd = data->ContentDisposition;
        Console::WriteLine(S"Content disposition");
        Console::WriteLine(cd);
        Console::WriteLine(S"File {0}",cd->FileName);
        Console::WriteLine(S"Size {0}", __box(cd->Size));
        Console::WriteLine(S"Creation {0}", __box(cd->CreationDate));
        Console::WriteLine(S"Modification {0}", __box(cd->ModificationDate));
        Console::WriteLine(S"Read {0}", __box(cd->ReadDate));
        Console::WriteLine(S"Inline {0}", __box(cd->Inline));
        Console::WriteLine(S"Parameters: {0}", __box(cd->Parameters->Count));
        IEnumerator* myEnum1 = cd->Parameters->GetEnumerator();
        while (myEnum1->MoveNext())
        {
            DictionaryEntry* d = __try_cast<DictionaryEntry*>(myEnum1->Current);
            Console::WriteLine(S"{0} = {1}", d->Key, d->Value);
        }
        data->Dispose();
        client->Dispose();
    }
Inheritance Hierarchy

System..::.Object
  System.Net.Mail..::.MailMessage
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0
See Also

Reference



Community Content

Noelle Mallory - MSFT
What? No VB Example for class?
Would be nice to have a VB example for this article.

jmaciak
Carboncopy field
Just a slight note ... the Carbon copy field is not CC as mentioned, but Cc
Tags : contentbug

BigGeek02
Authenticate

And what about authentication with the smtp server?

See the SmtpClient class. That controls credentials.

Tags :

Thomas Lee
VB Examples
I agree with above comments. Why general lack of VB examples for .Net 3.5?

mhh12
Where is the VB example?

Where is the VB example? If you are tryingl to discourage the use of VB, just say so. Grow up and say what you mean.

Mark H.

Tags : contentbug

alihaz
VB6 Example
Imports System.Net.Mail
  
Sub SendEmail(ByVal pathandfilename AsString)
    'create the mail message
    Dim mail As New MailMessage() 
  
'set the addresses
    mail.From = New MailAddress("peter@msn.com") 
    mail.To.Add("jon@msn.com") 
  
'set the content
    mail.Subject = "This is an e-mail"
    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
  
'add an attachment from the filesystem
    mail.Attachments.Add(New Attachment(pathandfilename)) 
  
'send the message
    Dim smtp As New SmtpClient("mail.smtpserver.com") 
    smtp.Credentials = New System.Net.NetworkCredential("username", "password") 
  
Try
        smtp.Send(mail)

Finally
        mail.Dispose()
        smtp = Nothing
    End Try
End Sub 'SendEmail
Tags :

DonkeyMaster
"To" property is a collection!

Note that the To: property is a MailAddressCollection, and it has a *get* property only. Instead of the obvious msg.To = "user @ cotoso.com", get a MailAddressCollection and Add the mail recipient to the collection.

message.To.Add("user @contoso.com");
Tags :

baillie11
Maile merge to email
This is a great example and very usefull, however, I have a document already created ans would like to use this to create a mail merge that emails out the document to each individual. Are there any code examples for this?

Thanks
Tags : email mail merge

Jeffrey Walton
To Send Plaintext Email (No, Really - Plaintext)

Setting 'IsHtmlBody = False' will still get you a quoted printable encoding. That is, CRLF's in the message body will be converted to '=0D=0A'.

When viewing web base email on some browsers, such as IE8, the browser will attempt to add hot links to URLs. But if the line is:
URL<CRLF>
Some other stuff here
Then IE8 will [incorrectly parse and] continue the URL link into 'Some other stuff here'.

To truly get a 'plain text' message body, try:

'Create the mail message
Dim mail As New MailMessage()
mail.BodyEncoding = Text.Encoding.ASCII
mail.SubjectEncoding = Text.Encoding.ASCII
mail.IsBodyHtml = False

'set the addresses
mail.From = New MailAddress("xxx@example.com")
mail.ReplyTo = New MailAddress("xxx@example.com")
mail.To.Add(xxx@example.com")

'Set the subject
mail.Subject = "Encoding Test"

' And the plaintext body
Dim body as string = "Line 1" & vbCrLf & "Line 2"
Dim plainText As AlternateView = _
AlternateView.CreateAlternateViewFromString(body, Encoding.ASCII, "text/plain")
plainText.TransferEncoding = Net.Mime.TransferEncoding.SevenBit
mail.AlternateViews.Add(plainText)

'Send the message
Dim smtp As New SmtpClient()
smtp.Send(mail)

Laxmi1234
MailMessage Size
how to know the size of mailmessage before sending the mail with smtpclient?

I know how to set maximum mail size on IIS but know clue how to get the actual size(i.e shown when we recive the mail in inbox) of mail before sending.

if we know size we can decide whther to send or not.
Tags :

Page view tracker