Send Email via C# through Google Apps account

There is no need to hardcode all smtp settings in your code. Put them in web.config instead. This way you can encrypt these settings if needed and change them on the fly without recompiling your application.

<configuration>
  <system.net>
    <mailSettings>
      <smtp from="[email protected]" deliveryMethod="Network">
          <network host="smtp.gmail.com" port="587"
              userName="[email protected]" password="password"/>
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

End when you send email just enable SSL on your SmtpClient:

var message = new MailMessage("[email protected]");
// here is an important part:
message.From = new MailAddress("[email protected]", "Mailer");
// it's superfluous part here since from address is defined in .config file
// in my example. But since you don't use .config file, you will need it.

var client = new SmtpClient();
client.EnableSsl = true;
client.Send(message);

Make sure that you're sending email from the same email address with which you're trying to authenticate at Gmail.

Note: Starting with .NET 4.0 you can insert enableSsl="true" into web.config as opposed to setting it in code.


This is what I use in WPF 4

SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("[email protected]", "P@$$w0rD");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;

try 
{
    MailAddress maFrom = new MailAddress("[email protected]", "Sender's Name", Encoding.UTF8),
    MailAddress maTo = new MailAddress("[email protected]", "Recipient's Name", Encoding.UTF8);
    MailMessage mmsg = new MailMessage(maFrom, maTo);
    mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
    mmsg.BodyEncoding = Encoding.UTF8;
    mmsg.IsBodyHtml = true;
    mmsg.Subject = "Some Other Text as Subject";
    mmsg.SubjectEncoding = Encoding.UTF8;

    client.Send(mmsg);
    MessageBox.Show("Done");
} 
catch (Exception ex) 
{
    MessageBox.Show(ex.ToString(), ex.Message);
    //throw;
}

Watch for Firewalls and Anti-Viruses. These creepy things tend to block applications sending email. I use McAfee Enterprise and I have to add the executable name (like Bazar.* for both Bazar.exe and Bazar.vshost.exe) to be able to send emails...


change the port to 465