Sending email with Gmail in .NET

2:46:00 PM 0 Comments A+ a-

Here is an simple C# and .net example on how to send email using Gmail.



Usings:
using System.Net;
using System.Net.Mail;

Code:
MailAddress fromEmailAddress = new MailAddress("fromEmailAddress@gmail.com", "Sender name");
MailAddress toEmailAddress = new MailAddress("toEmailAddress", "Recipient name");
const string fromPassword = "fromPassword";
const string emailSubject = "Subject of email";
const string emailBody = "Some email text goes here.";

SmtpClient smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromEmailAddress.Address, fromPassword)
};

MailMessage message = new MailMessage(fromEmailAddress, toEmailAddress)
{
    Subject = emailSubject,
    Body = emailBody
};

smtp.Send(message);
message.Dispose();
smtp.Dispose();