C#: Send Email with SMTP

September 30th, 2008 by Mel Leave a reply »

So I’ve actually had to do this before for a project I was working on, and thought that I’d go ahead and post a brief example of how to accomplish it here.

This example sends a simple email to a single recipient by using GMail. Please note that the principle classes used (MailMessage, SmtpClient, and NetworkCredential) are only available in the .NET Library 2.0 or later. For .NET < 2.0 you’ll want to see the System.Web namespace.

// Create the mail object.
System.Net.Mail.MailMessage msgMail =
    new System.Net.Mail.MailMessage(
        "TestEmail@mel-gree.com",   // FROM
        "mel@mel-green.com"         // TO
// Set the subject of the message
msgMail.Subject = "Hello from C#";
// Set that the body of this message will be HTML
msgMail.IsBodyHtml = true;
// Set the body of the email. Since I specified that
// I'm using HTML this will be fully qualified HTML/XHTML
msgMail.Body =
    "" +
      "" +
<h4>Hello There!</h4>
" +
 You've been selected to receive this email." +
" +
      "" +
// Now I'll create an SMTP object to send the message
// by means of a SMTP server.
System.Net.Mail.SmtpClient smtp =
    new System.Net.Mail.SmtpClient(
            "smtp.gmail.com", // Server address
            587               // Server port
// GMail uses SSL
smtp.EnableSsl = true;
// GMail uses authentication
smtp.UseDefaultCredentials = false;
    = new System.Net.NetworkCredential (
        "mastermel@gmail.com", // Account Name
        "MyPassword"           // Account Password
// Finally, send the message!

Here’s a few extra things you might want to know about…

If you’d like to send the email to multiple recipients simply create your MailMessage this way:

// Create the mail object.
System.Net.Mail.MailMessage msgMail =
    new System.Net.Mail.MailMessage();
// Set the sending address
msgMail.From = "TestEmail@mel-green.com";
// Add the recipients

If you’d like to add attachments to your message this is how you do it:

    new System.Net.Mail.Attachment("testFile.doc"));
    new System.Net.Mail.Attachment("testFile2.doc"));


  1. Erin says:

    I like this one.  I think I have several uses for it.   This will be fun.

  2. Mel says:

    Hey, you’re welcome buddy, glad you found something useful!

    Btw, I didn’t know you had a blog. That’s awesome! Keep up the good work. :wink:

  3. Bill says:

    Hey Mel!

    great post! very informative. I was trying to do the opposite of what this is doing a couple months ago, but i was missing a few things. now i think i know what i was missing, Thank You!

Leave a Reply