C#: Send Email with SMTP


C#: Send Email with SMTP

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 =
    "<html>" +
      "<body>" +
        "<h1>Hello There!</h1>" +
           You've been selected to receive this email. Congratulations!
         </p>" +
      "</body>" +

// 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"));

About the author

Mel administrator

3 Comments so far

ErinPosted on12:19 pm - Oct 1, 2008

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

MelPosted on8:29 am - Oct 1, 2008

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:

BillPosted on8:16 am - Oct 1, 2008

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.