Send Email from your Gmail account using C#

Internet

GmailIn this article I am going to show you how to programmatically send an email to any email address using your Gmail account.

The .NET 2.0 framework makes sending emails pretty easy. It contains a System.Net.Mail.MailMessage class which allows you to quickly build an email message.

Before we begin building our message we must add the following namespaces to our class, since we will soon need to make use of some of the classes within these namespaces:

using System.Net.Mail;
using System.Net;

Now lets create a MailMessage object and start building our message. We start by adding a recipient, a subject and a message body as shown below:

// Create a System.Net.Mail.MailMessage object
MailMessage message = new MailMessage();

// Add a recipient
message.To.Add("daveoncsharp@gmail.com");

// Add a message subject
message.Subject = "Email message from Dave on C-Sharp";

// Add a message body
message.Body = "Test email message from www.daveoncsharp.com.";

In the above code we are adding a single recipient for our message. If you want to add multiple recipients just separate the addresses with a comma (‘,’) like this:

// Add multiple recipients
message.To.Add("person1@address.com,person2@address.com,person3@address.com");

Next we must set the sender email address, so lets create an instance of the System.Net.Mail.MailAddress class, populate our sender email address and display name, and add them to our message.

// Create a System.Net.Mail.MailAddress object and 
// set the sender email address and display name.
message.From = new MailAddress("daveoncsharp@gmail.com", "Dave on C-Sharp");

To send emails we need an SMTP host, so lets set the host’s IP address or name, and port number. In this example I am going to use Gmail as our SMTP host but you can use a different host if you wish. Gmail’s host name is smtp.gmail.com and it uses port 587.

// Create a System.Net.Mail.SmtpClient object
// and set the SMTP host and port number
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);

Now to send emails using Gmail, they require that you are authenticated as a Gmail user, therefore we must send our encrypted Gmail account credentials over SSL to authenticate and send an email. This is shown in the code below:

// Enable Secure Socket Layer (SSL) for connection encryption
smtp.EnableSsl = true;

// Do not send the DefaultCredentials with requests
smtp.UseDefaultCredentials = false;

// Create a System.Net.NetworkCredential object and set
// the username and password required by your SMTP account
smtp.Credentials = new NetworkCredential("you@address.com",  "yourpassword");

If you are using an SMTP server which does not require authentication you can leave out the above block of code.

Once all the above is done, we can finally send our email message:

// Send the message
smtp.Send(message);

Note that the SmtpClient.Send() method might take a few seconds to send the email depending on your Internet connection.

Below is a full code listing of the SendEmail() method we just created:

private void SendEmail()
{
    // Create a System.Net.Mail.MailMessage object
    MailMessage message = new MailMessage();

    // Add a recipient
    message.To.Add("daveoncsharp@gmail.com");

    // Add a message subject
    message.Subject = "Email message from Dave on C-Sharp";

    // Add a message body
    message.Body = "Test email message from www.daveoncsharp.com.";

    // Create a System.Net.Mail.MailAddress object and 
    // set the sender email address and display name.
    message.From = new MailAddress("daveoncsharp@gmail.com", "Dave on C-Sharp");

    // Create a System.Net.Mail.SmtpClient object
    // and set the SMTP host and port number
    SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);

    // If your server requires authentication add the below code
    // =========================================================
    // Enable Secure Socket Layer (SSL) for connection encryption
    smtp.EnableSsl = true;

    // Do not send the DefaultCredentials with requests
    smtp.UseDefaultCredentials = false;

    // Create a System.Net.NetworkCredential object and set
    // the username and password required by your SMTP account
    smtp.Credentials = new NetworkCredential("you@address.com", "yourpassword");
    // =========================================================

    // Send the message
    smtp.Send(message);
}

When testing this code please remember to use your Gmail address and password. Also make sure that you don’t have a firewall blocking any outgoing email connections.

I hope you enjoyed this article and got something out of it. Hope to see you back here soon.

Dave

7 comments… add one
  • Areku Link Reply

    I got and error on the code Cannot implicitly convert type `System.Net.NetworkCredential’ to `System.Net.ICredentialsByHost’. An explicit conversion exists (are you missing a cast?)
    In this line

    smtp.Credentials = new NetworkCredential("you@address.com", "yourpassword");

    how can i fix this?

    • anji4u_2345 Link Reply

      Dear Areku !…….

      smtp.credentials=new system.net.networkCredential("Your mail Id(sender)","your pwd(sender)");
      
  • José Augusto Thomas Link Reply

    Areku, I’ve got the same error, so try to convert, as an explicit conversion exists (:
    It should look like so:

    smtp.Credentials = new NetworkCredential("you@address.com", "yourpassword") as ICredentialsByHost;
    
  • Areku Link Reply

    Jose Augusto the error disappear but now I got the following:

    InvalidOperationException: SSL authentication error: RemoteCertificateNotAvailable, RemoteCertificateChainErrors
    System.Net.Mail.SmtpClient.m__4 (System.Object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, SslPolicyErrors sslPolicyErrors)
    System.Net.Security.SslStream+c__AnonStorey7.m__A (System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Int32[] certErrors)
    Mono.Security.Protocol.Tls.SslClientStream.OnRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors)
    Mono.Security.Protocol.Tls.SslStreamBase.RaiseRemoteCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] errors)
    Mono.Security.Protocol.Tls.SslClientStream.RaiseServerCertificateValidation (System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Int32[] certificateErrors)
    Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.validateCertificates (Mono.Security.X509.X509CertificateCollection certificates)
    Mono.Security.Protocol.Tls.Handshake.Client.TlsServerCertificate.ProcessAsTls1 ()
    Mono.Security.Protocol.Tls.Handshake.HandshakeMessage.Process ()
    (wrapper remoting-invoke-with-check) Mono.Security.Protocol.Tls.Handshake.HandshakeMessage:Process ()
    Mono.Security.Protocol.Tls.ClientRecordProtocol.ProcessHandshakeMessage (Mono.Security.Protocol.Tls.TlsStream handMsg)
    Mono.Security.Protocol.Tls.RecordProtocol.InternalReceiveRecordCallback (IAsyncResult asyncResult)
    Rethrow as IOException: The authentication or decryption has failed.
    Mono.Security.Protocol.Tls.SslStreamBase.AsyncHandshakeCallback (IAsyncResult asyncResult)
    Rethrow as SmtpException: Message could not be sent.
    System.Net.Mail.SmtpClient.Send (System.Net.Mail.MailMessage message)
    

    Any ideas on this case?

    • anji4u_2345 Link Reply

      Dear Areku !

      First U have an INTERNET.

      MailMessage MailMsg = new MailMessage();
      MailMsg.From = new MailAddress("varikuti.anji9999@gmail.com");
      MailMsg.Subject = "hi this iz ur attachment";
      MailMsg.Priority = MailPriority.High;
              
      MailMsg.To.Add(new MailAddress("msnarayana98@gmail.com,varikuti.anji9999@gmail.com,rams.varikuti@gmail.com,anjinaidu@gmail.com "));
            
      MailMsg.Attachments.Add(new Attachment("F:\\9999\\9 9 9 9\\ME\\joharr.jpg"));
      
      MailMsg.Body = "Joharrrrrrrrrr YSR  ";
      SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
      
      smtp.Credentials = new System.Net.NetworkCredential("ur id(sender(", "ur pwd(sender)");
      smtp.EnableSsl = true;
      smtp.Send(MailMsg);
      Label1.Text = "Message Sent Successfully";
      
  • R.K Link Reply

    Hello,
    I`m working on a project that the client want to send email once a month at the same time with some data through the gmail account to the client email account.
    It works great if it is only one mail but when I tried to send 4 or 5 at the same time it failed.
    Just to explain it is not a spam, my client is using this program to get data that his client input into the program and need to be send once a month every month to my client.
    Please, help with that. How can I do it?

  • victor Link Reply

    when i try to send the email the following massage appears, there is no email program associated to perform the requested action. please install an email program or if one is already installed, create an association in the default programs control pannel

Leave a Comment