Skip to main content

Sending email with Gmail in .NET

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();

Comments

Popular posts from this blog