c# - 如何在没有用户交互的情况下使用 GMail API 创建草稿
问题描述
我有一个 C# 程序在无人值守的无头服务器上运行。
我需要该程序能够在我的 GMail 帐户中发送电子邮件和创建草稿电子邮件。
因此,我需要一个永久密钥或授权令牌供程序用来访问我的 GMail 帐户。
我一直在大量的 GMail API 文档中看到提示,这是可能的,但我找不到任何关于如何创建这样的密钥或令牌的实际说明。
解决方案
好吧,我最终在https://developers.google.com/identity/protocols/oauth2/service-account找到了说明
您创建一个服务帐户,为其提供适当范围的域范围权限(请参阅https://developers.google.com/gmail/api/auth/scopes),并在 json 文件中下载私钥(我称为 mine server_credentials.json
) .
然后,在您的程序中,您执行以下操作:
GmailService getService() {
GoogleCredential credential;
try {
using (var stream = new FileStream(@"server_credentials.json", FileMode.Open, FileAccess.Read)) {
credential = GoogleCredential.FromStream(stream)
.CreateScoped(GmailService.Scope.GmailCompose)
.CreateWithUser("me@example.com");
}
return new GmailService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Jumbo Accounts" });
} catch(Exception ex) {
throw new ApplicationException("Error logging into Google Mail", ex);
}
}
附加参考:
Gmail API 有一个示例快速入门参考列表,可以指导您如何启用 API、创建凭据甚至是示例代码,具体取决于您首选的编程语言。例如:.NET quickstart、创建项目并启用 API和创建凭据
推荐阅读
- javascript - 如何在javascript中检测浏览器标签关闭事件
- scala - 使用多个 scala 版本编译
- angular - 将 Ionic 3 迁移到 Ionic 5 API
- javascript - 为什么我不能使用 Javascript 更新 DataTable 中一行的单元格?
- amadeus - 使用不同的额外袋子为出站和入站创建订单
- tensorflow - Tensorflow2中的Gloabl Seed和Operation Seed
- mysql - 在 mysql 5.7 中选择具有最大日期的不同行
- c++ - 如何使用 CMake 从 git 下载特定的头文件以创建新的接口目标?
- excel - VBA Excel - 比较同一行中的两个值并根据结果执行操作
- python - 如何在 Python 中阅读时迭代日期?