Can we access GMAIL API using Service Account?

前端 未结 6 1673
予麋鹿
予麋鹿 2020-11-29 07:20

I have a desktop application to read mail using GMAIL API over REST Interface. I want to use service account so that we can download the mails using domain setting and user

6条回答
  •  旧巷少年郎
    2020-11-29 07:32

    For C# Gmail API v1, you can use the following code to get the gmail service. Use gmail service to read emails. Once you create the service account in Google Console site, download the key file in json format. Assuming the file name is "service.json".

        public static GoogleCredential GetCredenetial(string serviceAccountCredentialJsonFilePath)
        {
            GoogleCredential credential;
    
            using (var stream = new FileStream(serviceAccountCredentialJsonFilePath, FileMode.Open, FileAccess.Read))
            {
                credential = GoogleCredential.FromStream(stream)
                    .CreateScoped(new[] {GmailService.Scope.GmailReadonly})
                    .CreateWithUser(**impersonateEmail@email.com**);
            }
    
            return credential;
        }
    
        public static GmailService GetGmailService(GoogleCredential credential)
        {
            return new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,                
                ApplicationName = "Automation App",                
            });
        }
    
       // how to use
       public static void main()
       {
            var credential = GetCredenetial("service.json");
            var gmailService = GetGmailService(credential);
    
            // you can use gmail service to retrieve emails. 
            var mMailListRequest = gmailService.Users.Messages.List("me");
            mMailListRequest.LabelIds = "INBOX";
    
            var mailListResponse = mMailListRequest.Execute();            
       }
    

提交回复
热议问题