使用Google Drive-api将云端硬盘中的文件附加到特定的Gmail地址

时间:2017-08-27 10:19:21

标签: c# google-api google-drive-android-api google-drive-realtime-api

我使用以下代码接收来自我的云端硬盘帐户的所有文件:

    static void Main(string[] args)
    {
        UserCredential credential;

        using (var stream =
            new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = System.Environment.GetFolderPath(
                System.Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
            Console.WriteLine("Credential file saved to: " + credPath);
        }

        // Create Drive API service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        // Define parameters of request.
        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = 10;
        listRequest.Fields = "nextPageToken, files(id, name)";

        // List files.
        IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
            .Files;
        Console.WriteLine("Files:");
        if (files != null && files.Count > 0)
        {
            foreach (var file in files)
            {
                Console.WriteLine("{0} ({1})", file.Name, file.Id);
            }
        }
        else
        {
            Console.WriteLine("No files found.");
        }
        Console.Read();

    }


}

运行之后,我得到: enter image description here

这很棒,我得到了我的驱动器帐户中的所有文件。

现在,我想把每个文件都附加并发送到特定的Gmail地址。

我现在应该做些什么?

1 个答案:

答案 0 :(得分:0)

这可能仍取决于您的实施,但您可以使用Gmail API附加驱动器文件并将其发送给特定用户。

以下是发送邮件的代码段:

using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;

// ...

public class MyClass {

  // ...

  /// <summary>
  /// Send an email from the user's mailbox to its recipient.
  /// </summary>
  /// <param name="service">Gmail API service instance.</param>
  /// <param name="userId">User's email address. The special value "me"
  /// can be used to indicate the authenticated user.</param>
  /// <param name="email">Email to be sent.</param>
  public static Message SendMessage(GmailService service, String userId, Message email)
  {
      try
      {
          return service.Users.Messages.Send(email, userId).Execute();
      }
      catch (Exception e)
      {
          Console.WriteLine("An error occurred: " + e.Message);
      }

      return null;
  }

  // ...

}

以下是一些可以帮助您的相关参考资料:

希望这有帮助。