Archive for the ‘Email’ category

C#: Send Email with SMTP

September 30th, 2008

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(
        "",   // FROM
        ""         // 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(
            "", // Server address
            587               // Server port
// GMail uses SSL
smtp.EnableSsl = true;
// GMail uses authentication
smtp.UseDefaultCredentials = false;
    = new System.Net.NetworkCredential (
        "", // Account Name
        "MyPassword"           // Account Password
// Finally, send the message!

Here’s a few extra things you might want to know about…
» Read more: C#: Send Email with SMTP