2007/04/25

Sending mail using System.Net.Mail.SmtpClient and Gmail

This code snippet:
MailMessage message = new MailMessage();
message.From = new MailAddress("somebody@gmail.com");
message.To.Add(new MailAddress("somebody-else@some.server.com"));
message.Subject = "testing...";
message.Body = "This is a test.";

SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;
smtp.Send(message);
along with this app.config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.net>
    <mailSettings>
      <smtp>
        <network
          host="smtp.gmail.com"
          port="587"
          userName="somebody@gmail.com"
          password="some-password"
          defaultCredentials="false"
        />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>
allows to send e-mail from .NET code using Gmail as an SMTP server.

It is crucial to remember to:
  1. set EnableSsl to true;
  2. use port 587 (not 465, clicky).

No comments:

Post a Comment