如何在win服务中使用Gmail API

时间:2017-03-07 12:02:16

标签: c# .net gmail-api

我正在尝试从Gmail检索邮件。以下代码的问题是,它第一次会提示您授权访问。

我按照link寻求帮助。

如何使用Win服务实现这一目标?

这是我的代码:

var result = (from projectCost in db.ProjectCost 
              join subCostType in db.SubCostType on projectCost.SubCostType equals subCostType.SubCostTypeId
              join costType in db.CostType on subCostType.CostType equals costType.CostTypeId
              where costType.CostTypeId == selectedCostTypeId  
              select projectCost );

3 个答案:

答案 0 :(得分:0)

您必须初始化OAuth2才能启动,Gmail不支持服务帐户。 “当你的应用程序安装它时,它应该提示用户进行身份验证,然后保存该身份验证。创建一个Windows服务,检查gmail是否有多少时间,如果它发现某些内容从你的控制台应用程序中触发”,如tutorial中所述。同样在相关的SO post中,“快速入门应用程序是一个简化的命令行应用程序,它可以减少一些角落,使入门体验更快,但它仍然可以用作Windows服务的起点。” p>

答案 1 :(得分:-1)

首次流动不能在服务代码上,因为您无法与用户进行互动。

您可以尝试创建安装程序,然后向他询问凭据。

答案 2 :(得分:-1)

我们可以通过Gsuit的服务帐户来实现这一点。 我们需要创建项目,启用API,创建服务帐户并获取p12文件。 Follow this link-Delegating domain-wide authority to the service account

在Gsuit帐户中配置服务帐户邮件ID和客户端ID(请查看上面的链接)。

这是我的代码

    static void Main(string[] args)
    {
        Console.WriteLine("Plus API - Service Account");
        Console.WriteLine("==========================");

        String serviceAccountEmail = "xxxx@xxxx-xxxx.xx.gserviceaccount.com";

        var certificate = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory +
             "xxxxxxxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(serviceAccountEmail)
           {
               Scopes = new[] { GmailService.Scope.MailGoogleCom },
               User = "xxxx@xxxxxxx.net"//ur Gsuit Id
           }.FromCertificate(certificate));

        // Create the service.
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "xxxxx",
        });

要获取邮件,请使用此link

快乐编码:)