C# Code, Tutorials and Full Visual Studio Projects

Gmail in C#

Posted by on Nov 16, 2010 in Networking | 7 comments

Gmail in C#

Use C# to send mail using Google’s Gmail. If you’ve ever wanted to send email using your Gmail account then take a look.


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

namespace JarlooGmail
{
    public class Gmail
    {
        public string Username { get; set; }
        public string Password { get; set; }

        public Gmail(string username, string password)
        {
            Username = username;
            Password = password;
        }

        public void Send(MailMessage msg)
        {
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.EnableSsl = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential(Username, Password);
            client.Send(msg);
        }
    }
}



You can call the Gmail c# class like so:

using System.Net.Mail;

namespace JarlooGmail
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Gmail gmail = new Gmail("MyUsername","MyPassword");
            MailMessage msg = new MailMessage("FromMe@here", "ToYou@there");
            msg.Subject = "my subject";
            msg.Body = "the body of the message";
            gmail.Send(msg);
        }
    }
}

7 Comments

Join the conversation and post a comment.

  1. Asaf

    Thanks a lot for this example,
    I got it to work in 2 minutes.
    Keep sharing

  2. Saeed Neamati

    This was truly helpful to me. But I don’t know how many emails per day can we send? I mean, does Google ban us as spammers for sending more than a specified number?

  3. admin

    Google does have a limit but it is set fairly high. Once you exceed the limit they will prevent you from sending emails for a period of time. (It was a few hours if I recall.) This happened to me once as I use Gmail to send me errors from my applications and something that runs every 15 seconds had a problem and so the application started spamming me with emails. (yes bad design on my part)
    What I don’t know is if you keep getting these temporary bans will they eventually make it permanent?

  4. mike

    Thanks, just what I was looking for!

  5. Kelly Elias

    I’ve used IMAP in the past to retrieve email attachments, but I can’t seem to locate any of my code for it. This should point you in the right direction though: http://stackoverflow.com/questions/545724/using-c-sharp-net-librarires-to-check-for-imap-messages-from-gmail-servers

  6. Seiw

    Thanks a lot. It’s very helpfull!

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>