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.
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
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.
Unfortunately i cant help you i don’t have a Google Apps account so i cant create tutorials for it.
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.
you can just add the Gmail scopes, if the user hasn’t authenticated with the new scope they should be prompted to do so the next time they login.
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
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
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.
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.
Please help me to connec Gmail Api with Service account. If its possible to do this???
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.
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.
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.
I sure do and would be happy to help you any way i can Consulting service
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…
The sample project i have for Gmail can be found here if you need anything else let me know i am willing to work with your to extend the sample project to help you and others.
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.
Yes go back to the authentication section you shouldn’t have changed anything there. Download the project from github and just run it dont change anything it should work.
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….
Did you change the client id and client secret in the project to yours?
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…:(
you may want to add a breakpoint in or something stop it its just a test app I am not sure if i set stops or not.
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..
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.
you should start by reading my tutorial on Types of Open Authentcation if you are seeing p12 then you have created a service account.
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.
I dont think this is what you are looking for but its the only thing i have been able to find. https://developers.google.com/admin-sdk/directory/v1/guides/migrate
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
I don’t think you can programmatic create Google Accounts. If you can its not anything i have heard of before.
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!!
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)
{
}
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
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.
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
This was such an great question i thought i would turn it into a blog post. Find users Email with Google APIs I hope it helps.
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
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.
Great!
I think is if possible download gmail mails in EML format ?
thx
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.
This might be what you are looking for. If you do get it working please let us know.
Hello,
I’m build a asp.net web api project that uses gmail api. I encountered a problem and posted it on stackoverflow, maybe you can help me please:
http://stackoverflow.com/questions/33069148/using-gmail-api-with-asp-net-web-api?noredirect=1#comment53990981_33069148
thanks in advance
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!
sounds like the code is not able to save your access tokens. Where are you saving them to make sure IIS has access to that directory
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
Hello Linda Lawton.
I hope you can guide me to share all GooglePlusDomain use for a certain individual. Thank so much!
Alex
Unfortunately i cant be of much help I dont have access to a Google Plus Domain account so have been unable to test it.
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
Changing the user parameter in GoogleWebAuthorizationBroker.AuthorizeAsyn (i have it set to “Linda”) will switch users. You might like reading Google .net – FileDatastore demystified it explains how you control filedatastore.
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.
not using the gmail api you will have to go though the gmail smtp or imap clients.
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?
No AE.Net.Mail is not a Google library.
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!!
you should follow this to start with to get access https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web-applications-aspnet-mvc
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
Thats fine you dont need access token.
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
authentication method is different for webapps vs installed applications https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#web-applications-aspnet-mvc
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?
I dont have access to a gsuite account i am assuming you are trying to set up a service account you may want to check this out https://developers.google.com/admin-sdk/reports/v1/guides/delegation
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
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.
Link broken Google Drive Sample project