Sending e-mail using SmtpClient and Gmail

The sample below used SmtpClient to send e-mail from your gmail account using your gmail username and password.

using System;

using System.Net;

using System.Net.Mail;

namespace GMailSample

{

    class SimpleSmtpSend

    {

        static void Main(string[] args)

        {

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);

          client.EnableSsl = true;

            MailAddress from = new MailAddress("YourGmailUserName@gmail.com", "[ Your full name here]");

            MailAddress to = new MailAddress("your recipient e-mail address", "Your recepient name");

          MailMessage message = new MailMessage(from, to);

            message.Body = "This is a test e-mail message sent using gmail as a relay server ";

            message.Subject = "Gmail test email with SSL and Credentials";

            NetworkCredential myCreds = new NetworkCredential("YourGmailUserName@gmail.com", "YourPassword", "");

            client.Credentials = myCreds;

            try

            {

                client.Send(message);

            }

            catch (Exception ex)

       {

                Console.WriteLine("Exception is:" + ex.ToString());

            }

            Console.WriteLine("Goodbye.");

        }

    }

}

 

What happens here is that SmtpClient sends your e-mail to a relay server (in this case the gmail web mail server) and then this relay server sends it to its specified destination. Of course you're not limited to just gmail. The relay server can be another mail server, or a SMTP server/service - you can use a third party one or set your own. I'll update the post to include more detail on this later.

 

You can easily expand this sample to a more elaborate one - with attachments, html content, embeded images, etc. For more detail please refer to our documentation on msdn2 here:

https://msdn2.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx
There is also a very good site containig basic and more advanced samples here:
https://www.systemnetmail.com/faq/3.aspx
https://www.systemnetmail.com/faq/4.aspx