简体   繁体   English

如何使用服务帐户 ID 访问我的帐户电子邮件?

[英]How can I access my account emails with service account id?

I created a project in google cloud platform and created a OAuth service account id for my gmail account.我在 google 云平台中创建了一个项目,并为我的 gmail 帐户创建了一个 OAuth 服务帐户 ID。 With this service account id I'm unable to read emails as it says I don't have access to this scope GmailReadonly.使用此服务帐户 ID,我无法阅读电子邮件,因为它说我无权访问此范围 GmailReadonly。

I went through google to find that I need scope access from Gsuite admin but if the access is given, it says it can be used to retrieve all the organization users emails.我通过谷歌发现我需要 Gsuite 管理员的范围访问权限,但如果授予访问权限,它表示它可以用于检索所有组织用户的电子邮件。 Is this information correct?这些信息正确吗? If yes, is there any other way to access just my account's emails?如果是,是否还有其他方法可以仅访问我帐户的电子邮件?

Below is the c# code which I used to access emails.下面是我用来访问电子邮件的 c# 代码。 Please let me know if there is any way to achieve it.请让我知道是否有任何方法可以实现它。

 #region saggezza account id read
        ServiceAccountCredential serviceAccountCredential = new ServiceAccountCredential(
          new ServiceAccountCredential.Initializer("xxx@projectname.iam.gserviceaccount.com")
          {
              User = "xxx@organization.com",
              Scopes = new[] { GmailService.Scope.GmailReadonly }
          }.FromPrivateKey("-----BEGIN PRIVATE KEY-----xxxxxxxxxxxxxxxxx-----END PRIVATE KEY-----\n"));

        if (serviceAccountCredential != null)
        {
            var service3 = new GmailService(new BaseClientService.Initializer
            {
                HttpClientInitializer = serviceAccountCredential,
                ApplicationName = ApplicationName
            });

            var list = service3.Users.Messages.List("me").Execute();
            var count = "Message Count is: " + list.Messages.Count();                
        }

You need to create a service account on Google developer console , enable the Gmail api.您需要在Google 开发者控制台上创建一个服务帐户,启用 Gmail api。 Then you need to properly set up domain wide delication with your gsuite account before its going to work.然后,您需要使用您的 gsuite 帐户正确设置域范围的详细信息,然后才能开始工作。 delegate settings 委托设置

ServiceAccount.cs 服务帐户

 public static class ServiceAccountExample
    {

        /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
        public static GmailService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes, string email)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");                

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new GmailService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Gmail Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

                    var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        user = email,
                        Scopes = scopes
                    }.FromCertificate(certificate));

                    // Create the  Gmail service.
                    return new GmailService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Gmail Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {                
                throw new Exception("CreateServiceAccountGmailFailed", ex);
            }
        }
    }
}

note笔记

service3.Users.Messages.List(email).Execute();  

me is going to be the service account which does not have any emails.我将成为没有任何电子邮件的服务帐户。 You need to use a user.您需要使用用户。 You need to supply the email address of the user whos email you would like to access.您需要提供您要访问其电子邮件的用户的电子邮件地址。 This again must be a user on the gsuite domain.这又必须是 gsuite 域上的用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在SharePoint2010上将我的帐户模拟为服务帐户 - How to impersonate my account to service account on SharePoint2010 如何使用Win32 API在与LocalSystem帐户不同的帐户下安装服务? - How can I install a service under a different account than the LocalSystem account using Win32 API? 如何在基于REST的服务中隐藏帐户信息? - How can I hide account information in a REST based service? 如何授予对NETWORK SERVICE帐户的SQL访问权限? - How to give SQL access to NETWORK SERVICE account? 我的访问令牌不能跟随Instagram帐户 - My Access token is not can Follow account instagram 如何使用ASPNET用户帐户访问私钥? - How can I access a private key with the ASPNET user account? 如何从 outlook email 帐户获取数据,例如电子邮件、联系人和日历事件,并将其显示在列表中? - How can I get the data from an outlook email account, such as emails, contacts, and calendar events, and show it inside a list? gmail API 使用服务帐户删除电子邮件 - gmail API deleting eMails using service account 我们可以使用服务帐户访问 GMAIL API 吗? - Can we access GMAIL API using Service Account? 如何使用 c# 以编程方式安装系统服务以使用组托管服务帐户 (gMSA)? - How can I programmatically install a system service using c# to use a Group Managed Service Account (gMSA)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM