How to Access Gmail with C# .net 61


gmail

Are you trying to connect to GMail using C#, well you have come to the right place. I recently helped someone having issues with connecting to Gmail using C#.

The Gmail API isn’t the same as the other Google APIs you may be used to. This is because of the fact that you are logging into an imap server, or a mail server. Normally we would use OAuth2 to access a Google API but in this instance you use something called XOAuth2.

Developer console

You will need to create an application in the developer console like you would with any other API, but you don’t need to select an API.   I recommend that you select the Google+ API this will enable you to fix the Authenticated users email address.  Without it you will have to have the user give it to you.
[wp_ad_camp_3]

NuGet Packages

If you haven’t included the Google+ API in your application you can skip the Google.Apis.Plus.v1 package.

Install-Package AE.Net.Mail
Install-Package Google.Apis.auth
Install-Package Google.Apis.Plus.v1

Authentication

In order to access Gmail you need the https://mail.google.com/ scope, the email scope gives you access to the currently authenticated users email address though the Google Plus API.
Note: make sure you add the following using
using Google.Apis.Auth.OAuth2;

  UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                                   new ClientSecrets { ClientId = _client_id,
                                                       ClientSecret = _client_secret },
                                   new[] {"https://mail.google.com/ email" },
                                   "Linda",
                                   CancellationToken.None,
                                   new FileDataStore("Analytics.Auth.Store")).Result;

This code will open the normal authentication window asking the user to give you access.

gmail Autentication Form

If you did not add the email scope then the user won’t be asked for that.

Users Email Address

The first thing we need to do is create a plus service we can use to request information from the Google plus API.

result.service = new PlusService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = result.credential,
                    ApplicationName = "Google mail",
                });

Now that we have our service and access to the users Google Plus information we can request their email address.

Google.Apis.Plus.v1.Data.Person me = result.service.People.Get("me").Execute();
 Google.Apis.Plus.v1.Data.Person.EmailsData myAccountEmail = me.Emails.Where(a => a.Type == "account").FirstOrDefault();

A user can have several email address set up but the only ones that are listed are the ones they have set to public. The one we want is the one with type of account.

Imap login

All that was just a precursor to the following, now is when we actually login to the GMail imap server. Notice how we are sending it the access token we got from our OAuth2 login. credential.Token.AccessToken

ImapClient ic = new ImapClient("imap.gmail.com", myAccountEmail.Value, credential.Token.AccessToken,
                                ImapClient.AuthMethods.SaslOAuth, 993, true);

Listing emails

ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
// Get the first *11* messages. 0 is the first message; 
// and it also includes the 10th message, which is really the eleventh ;) 
// MailMessage represents, well, a message in your mailbox 
MailMessage[] mm = ic.GetMessages(0, 10);
foreach (MailMessage m in mm) 
   { 
   Console.WriteLine(m.Subject + " " + m.Date.ToString());
   } 
   // Probably wiser to use a using statement 
   ic.Dispose();

Conclusion

Authenticating access to the Gmail API isn’t the same as Authenticating to the other Google APIs, this is because of the fact that we are logging into an Imap server. This tutorial is small if you would like me to go into more detail and maybe add some examples of reading emails or sending emails leave a comment at the bottom and I will see what I can do. A sample project for this tutorial can be found on Google Drive Sample project


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a Reply to clotaire Gouala Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

61 thoughts on “How to Access Gmail with C# .net

  • Khulan

    Hello
    I am trying to create simple installed application on .net c# using google admin sdk that manage my domain users. I could not find any tutorial and sample code. I create a project on developer console.

    Thanks
    Please reply soon.

  • Jon

    I have a MVC application that uses Google Auth with ASP.NET Identity for authentication. Is it possible to add the GMail API without having to have the user re-authenticate? Your example here assumes authenticating just for the GMail API.

  • Maria

    Could you please post some code on how to access the mailbox (inbox, sent, draft) of a user in my domain?
    I do not want a monitor, I want to directly access the user mailbox….step by step explanation will be very welcomed. Thanks

  • minh

    Thank you for this tutorial.
    I just got acquainted with google api, specific gmail api, and OAuth2.

    I read the gmail quickstart, Authorizing Your App with Gmail, and watched “Google I/O 2012 – OAuth 2.0 for Identity and Data Access ” on youtube and am still very confused how to add the authentication process in my code.

    Would you do an additional tutorial with full sample code or guide me to further reading to help clarify the process some more.

    My goal is to create a standalone Windows Forms App that can access user gmail account.

    I’m using VS12 C#/.NET.

    Thank you

    • Milton

      Thank you. I am trying to develop a console app that will check inbox every x amount of time and as soon as it detects an email( looking by specific text on header), will do something. Is this possible? Any directions, tips?? Thank you for your time.

      • Linda Lawton Post author

        You are going to have to use OAuth2 to start, Gmail doesn’t support service accounts I don’t think. When your application installs it should prompt the user for authentication once then save that authentication. Create a windows service that checks gmail ever x amount of time, if it finds something fire off your console app. I don’t recommend doing all the work in the windows service I have had issues with windows services that run for an extend amount of time.

    • Linda Lawton

      I don’t think its possible. How would you give a service account access to your Gmail account? If you want to automate it then i would just use normal Oauth2, save your refresh token you will be able to access it automated with that.

      • ilkapo

        Yes you can use a Service account, at least on a google-for-work domain.
        In this scenario you have to: enable GMail API and give complete access to the service account, using the admin console -> security.
        Then use normal Oauth2 and impersonate the desired user.

  • Mark

    Do you offer any direct consulting? I’m working on an application that needs to read and send gmail as a service. I need to setup the persistent OAuth so that gmail can be sent and fetched in the background.

  • Harish

    Hello , i am making a c# app which checks number of emails in our gmail account and tells the user the output…can u help me with source code or any key points please…

      • Harish

        Hello madam, I executed your sample code you provided, but I got this error.

        401, The OAuth client was not found.

        I think in this step, I made mistake..

        GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = _client_id }, new[] { “https://mail.google.com/” }, “titanheartz@gmail.com”, CancellationToken.None, new FileDataStore(“Analytics.Auth.Store”)).Result;

        please correct me where am I wrong..

        thank you.

          • Harish

            I didn’t change anything…downloaded the project and ran it…but it returned an error like this :

            401. That’s an error.

            Error: deleted_client

            The OAuth client was deleted….

          • Harish

            yes, I changed the client id and client secret to mine and then I ran the project…it redirected to request permission page….and asked that the app is requesting permission to access the account…

            I gave accept option and then the app terminated without displaying number of emails…:(

          • Harish

            it’s ok madam…thank you for your help…i’ll see what i can do…i’ll notify you once i get the working version..thank you..

          • Balaban Senol

            Hello I have a similar question, where to find the client Secret?
            In the google developer console I only get the options to generate a json file or a p12 certificate.

            Sincerely.

  • Narender

    Hi Linda, i am trying to create new gmail accounts (users) from an installed application. Please suggest the steps to create the users using google APIs and also any sample projects would be helpful.

  • clotaire Gouala

    Hi !
    I wish to create gmail accounts as if they were created by a user on the gmail interface, but no interface rather programmatically in C # for example.
    Would you know how to do it and where I can have info on this approach.

    Best Regard

    • Narender

      Hi Clotaire!!
      I had the same requirement of creating gmail accounts(users) programmatically using C#.

      By using the below blog i was able to create the gmail accounts programmatically in C# using Google Admin SDK. I hope it would help you as well. Happy coding!!

  • Sangeetha

    m creating C# Window Service to Import Gmail Contact Details(Like Email ID, Name)
    Below is my Code … Now m getting error of Execution of authentication request returned unexpected result: 404. Kindly help me its urgent for me
    RequestSettings rs = new RequestSettings(“MyNetwork Web Application!”, EmailID, pass);
    rs.AutoPaging = true;
    ContactsRequest cr = new ContactsRequest(rs);
    Feed f = cr.GetContacts();

    foreach (Contact entry in f.Entries)
    {
    }

  • Farid

    hello! been checking out your example, what I need is to access a Gmail account which I have username and password for , but I have not clear how this relates to client id and client secret, I downloaded the solution from github and replaced id and secret for ones I generated to this particular google account using the https://console.developers.google.com website, however when I run the application it redirects me to a redirect_uri_mismatch error from google.
    I hope you can give me any advice, thank you very much

    • Linda Lawton

      You must have created a Client ID for web application to test a console application you need to create a Client ID for native application

      You cant add code for login and password this is called client login and has been shut down by google. You need to use Oauth2 which is the client id and client secret you have. When the Oauth2 authentication screen pops up you will be able to login with your Google account and authenticate the code.

  • amit gupta

    In this link,a whole source code is given for google plus authentication in windows app. This is running successfully but i want to extract user’s email id and show it in main page. Can anyone help? http://windowsapptutorials.com/windows-phone/google-services/how-to-add-google-login-using-oauth-2-0-in-windows-phone-8-app/ I want to use a method something like this which i used in facebook authentication

    private async void GetUserData(string UserID, string Token)
    {

    var httpclient = new HttpClient();
    string uri = “https://graph.facebook.com/v2.4/” + UserID + “?fields=name,email,gender&access_token=” + Token + “”;
    var URI = new Uri(uri);
    var response = await httpclient.GetAsync(URI);
    var jsonString = await response.Content.ReadAsStringAsync();

    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(RootObject));
    // contains user name,id,email
    RootObject UserData = (RootObject)ser.ReadObject(ms);

    string hu = “”;
    hu = hu + “” + UserData.email.ToString();
    Username.Text = hu;
    }
    the above code is written for facebook authentication in which we need id and token both..but in google plus,i think we need only token…so how we can access token

  • Sameer

    Hi Linda,
    I tried the solution you suggested. Its working great!
    What I need is to get all the SENT messages. I tried changing “INBOX” with “SENT” but got error :
    “NO [NONEXISTENT] Unknown Mailbox: SENT (Failure)”
    Can you shed some light on this? How can I get all the mails SENT?

    thanks,
    Sameer

    • Linda Lawton Post author

      I am going to turn this into another post later tonight but in the mean time try:

      setting the q for search to in:sent or lableids to SENT.

      I have just hacked this out of the API using the try it at the bottom. I haven’t tested it in C# yet. I will get you some code for this tonight.

    • Linda Lawton Post author

      As far as I know Google’s services don’t support EML format.

      I ran across something a while back that might help you user.messages I haven’t had time to play with this but check the raw field.

      raw bytes The entire email message in an RFC 2822 formatted and base64url encoded string. Returned in messages.get and drafts.get responses when the format=RAW parameter is supplied.

      This might be what you are looking for. If you do get it working please let us know.

  • Kishore Gund

    I have created a small app to read the emails from my account. I m providing a separate path to store the gmail access token files. The access token files are re-generated if deleted in development mode but once i deploy the application using IIS the google access token files are not generated and i could not read the emails.
    Please advice.

    Thanks for your help!

  • sapir

    hi,
    you use in your code a var name “result ” , but what type is it ?
    im using the code you gave here https://github.com/LindaLawton/Google-Dotnet-Samples/blob/master/Google-Gmail/Google.mail.DotNet/Google.mail.DotNet/GAAutentication.cs
    but again the var “result” cause a problem , its remain empty and the funcrion ended after the line :
    if (result.credential != null)

    can you please explain what result stend for ? and what use i have with it so i will know what to put in it ?
    the only like about it is :
    GAAutentication result = new GAAutentication();

    thank you

  • Alex

    Hello Linda Lawton.

    I hope you can guide me to share all GooglePlusDomain use for a certain individual. Thank so much!

    Alex

  • darshan dave

    Hello Mam,
    I have one web application and right now i can access only one gmail account using gmail api but how to more then more then one gmail account in one web application. I have developed in .net mvc

  • yasir

    Dear maiam I have to access gmail account of other user here you are getting “me” own account mail how it could be possible to get other email on basis of email and password.

  • Pregunton Cojonero

    Great blog. Marvellous Google APIS and NET. What’s a pity not more good documentation by Google.

    What is Install-Package AE.Net.Mail ? AE.Net.Mail is not Google Component?

  • Dilpreet Kaur

    Hi Linda,
    Thanks for your code and information. I am new in this field. I have made a c# asp.net web forms application in visual studio 2015. I wanna use gmail API to read all my inbox, send emails and to use all basic functions of gmail. Can you please help me in this how can i use gmail API in my web forms application as all I find on internet is for mvc and I have no idea about it. If you can help with a simple example that will be great. All of your help would be much appreciated. Thanks in advance!!

  • Saeideh

    Hello,
    Thanks for your great articles.
    I have a mvc application that sends email through Gmail api .
    I have setup my app and got access_token and refresh_token and since it is a web application I chose GoogleAuthorizationCodeFlow and I initialized it like this:
    var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
    {
    ClientSecrets = new ClientSecrets
    {
    ClientId = “my_clientid”,
    ClientSecret = “my_appSecret”
    },
    Scopes = new[] { GmailService.Scope.GmailCompose },

    });

    var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse()
    {
    //AccessToken = access_token
    RefreshToken = refresh_token

    };

    var service = new GmailService(new BaseClientService.Initializer()
    {
    HttpClientInitializer = new UserCredential(flow, “user”, token),
    ApplicationName = ApplicationName,
    });

    service.Users.Messages.Send(newMsg, “me”).Execute();

    While I was testing my code I found out that my code works properly just with Refresh_token ( I commented access_token out in y code )
    I wanted to make sure if it is correct to just use Refresh_token?
    I have just one gmail account to access (which is my application gmail account) and I do not want to access my users gmail account.
    please correct me if I am wrong..
    Thanks

  • Rive

    HI Linda

    Great tutorial. I got it working on a console example but I am struggling to get one to working with ASP.NET(web forms).Is it possible to do a tutorial on it

  • Dionne Owens

    Good day

    I have been tasked with writing a script to gather and save in a csv file all of our users google alias’.

    The IT team were giving secondary admin writes to the overall google account so from the Google console we created an auth json file (readonly / not requiring user access approval)

    When we ran the code (similar to your sample above) we go the following error:

    Google.GoogleApiException: ‘Google.Apis.Requests.RequestError
    Not Authorized to access this resource/api [403]

    Errors [
    Message[Not Authorized to access this resource/api] Location[ – ] Reason[forbidden] Domain[global]
    ]
    Then we had the main admin person with higher rights create an auth json file and we got the same error.

    *Note withiin the json file there is no key value pair for “Client Secret”

    Can you advise us?

  • Sailaja

    Hi Linda,

    We are trying to login to gmail from our code. But it asks to enter captcha. Is there any way to login to gmail without using the captcha.
    Could you please let me know whether we can use google api to login to gmail. and access inbox files.
    Thanks in advance,
    Sailaja

    • Linda Lawton Post author

      My code should not be asking for captcha unless you mean when you are logging into your google account. There is nothing you can do to change that thats part of the google login developers have no control over that.