【问题标题】:Obtain email address from GmailService using C# client API使用 C# 客户端 API 从 GmailService 获取电子邮件地址
【发布时间】:2020-09-16 05:11:12
【问题描述】:

Gmail API to get profile info

基于此链接,可以从经过身份验证的个人资料中获取电子邮件地址。 不幸的是,我无法找到如何在 C# API 客户端中获取它。

我试过这个:GmailService.Users.GetProfile("me"),但这不包含电子邮件地址。

我希望有人知道如何使用 C# API 客户端执行此操作。

谢谢。

【问题讨论】:

    标签: c# .net gmail-api nuget-package


    【解决方案1】:

    您可以使用简单的 WebRequest 并解析 JSON 以获取 emailAddress 字段。

    您可以构建一个类似于以下内容的响应模型:

    public class APIResponse 
    {
        public string emailAddress {get; set;}
        public int messagesTotal {get; set;}
        public int threadsTotal {get; set;}
        public int id {get; set;}
    }
    

    然后您将要向 GoogleAPI url 发出 GET 请求并反序列化来自您的 API Response 类的 JSON 响应。

    WebRequest request = WebRequest.Create("https://www.googleapis.com/gmail/v1/users/me/profile");
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
                request.Timeout = 50000;
                //Get response from server
                using (StreamReader stream = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
                {
                    sResponse = stream.ReadToEnd();
                    resp = new JavaScriptSerializer().Deserialize<APIResponse>(sResponse);
                }
    

    那么您只需拨打电话resp.emailAddress.即可取回您的电子邮件地址 我还没有为 GoogleAPI 测试过这段代码,但这应该会让你朝着正确的方向前进。

    【讨论】:

    • Gmail API 有一个用于 C#(NuGet 包)的 api 客户端。我希望它已经包含了我可以调用来检索此信息的必要方法。
    【解决方案2】:

    这对我有用

    // Create Gmail API service.
    GmailService service = new GmailService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = ApplicationName,
    });
    
    var gmailProfile = service.Users.GetProfile("me").Execute();
    var userGmailEmail = gmailProfile.EmailAddress;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2020-10-31
      • 1970-01-01
      • 2021-12-28
      • 2013-06-02
      • 2022-08-08
      • 2014-06-01
      相关资源
      最近更新 更多