【问题标题】:Gmail API Create and Send Email .NET C#Gmail API 创建和发送电子邮件 .NET C#
【发布时间】:2021-09-10 14:31:14
【问题描述】:

问题

我正在尝试将 Gmail API 实施到 API 应用程序中。我创建了一个服务帐户并保存了 p12 密钥和 json 凭据。我正在谈论一个失败的先决条件。我认为这可能与我要发送的信息有关。

代码

String serviceAccountEmail = "SERVICE-ACC-EMAIL";
X509Certificate2 certificate = new X509Certificate2("./key.p12", "notasecret", X509KeyStorageFlags.Exportable);
// FileStream stream = new FileStream("./credentials.json", FileMode.Open, FileAccess.Read); // ! Not Used
            
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
    User = serviceAccountEmail,
    Scopes = new[] { GmailService.Scope.MailGoogleCom }
}.FromCertificate(certificate));
GmailService service = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential,
    ApplicationName = "Testing Application",
}); 
var result = service.Users.Messages.Send(CreateEmail.CreateEmailMessage(), "me").Execute();

异常

An unhandled exception of type 'Google.GoogleApiException' occurred in System.Private.CoreLib.dll: 'Google.Apis.Requests.RequestError
Precondition check failed. [400]
Errors [
    Message[Precondition check failed.] Location[ - ] Reason[failedPrecondition] Domain[global]
]'

构建邮件消息(不起作用)

在 CreateEmail.CreateEmailMessage 方法中,我构建了一个新的 Google.Apis.Gmail.v1.Data.Message 实例。设置有效负载和标头。以此为参考。我不确定这是否是这样做的方法,但我似乎找不到创建新消息的方法。我只能找到用 Java 或 Python 编写的东西,我尝试将其转换为 C#,但失败了

var msg2 = new Message()
{
    Payload = new MessagePart()
    {
        Body = new MessagePartBody()
        {
            Data = Convert.ToBase64String(Encoding.UTF8.GetBytes("Hello world"))
        },
        Headers = new List<MessagePartHeader>() {
            new MessagePartHeader() { Name = "To", Value = "My email"},
...

【问题讨论】:

  • @jdweng Node.Js 不是 C#,它们完全不同,除非这个问题的作者知道 node.js,否则这可能无济于事,请坚持使用作者使用的语言来帮助防止混淆。
  • 我知道 Node.Js,但我必须使用 C# 来完成这项工作,不过感谢您的评论!

标签: c# .net gmail-api google-workspace service-accounts


【解决方案1】:

前提条件检查失败。 [400]

使用 Gmail api 和服务帐户通常意味着您没有正确设置服务帐户的域范围委派。

Implementing Server-Side Authorization

在您的情况下,这可能是因为您委派给不在您域中的用户。

User = serviceAccountEmail,

不是服务帐户电子邮件地址,而是您希望服务帐户模拟的 Google Workspace 用户。

string ApplicationName = "Gmail API .NET Quickstart";
const string serviceAccount = "clawskeyboard-smtp@clawskeyboard-api.iam.gserviceaccount.com";
    
var certificate = new X509Certificate2(@"D:\api-ed4859a67674.p12", "notasecret", X509KeyStorageFlags.Exportable);
    
var gsuiteUser = "xxx@YourWorkGroupDomain.com";
    
var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount)
                {
                    User = gsuiteUser,
                    Scopes = new[] { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels }
    
                }.FromCertificate(certificate);

【讨论】:

  • 非常感谢! ? 我得到另一个关于“客户端未授权......使用此方法或没有请求范围”的异常我猜我只需要在 Google 方面解决这个问题。
  • 客户端未授权是一个奇怪的检查,您在谷歌云控制台上的项目中启用了 gmail api。
  • 嗯,我启用了 API 和其他东西,但我认为我没有正确设置权限? 如果它与政策有关,我可能需要联系我们的云管理员
  • 会做?谢谢你!
  • 在询问我们的工作区团队后,我得到了正确的权限范围,他们正确地设置了我的权限。我不知道怎么做,所以我不能把它包括在答案中?
猜你喜欢
  • 2021-09-11
  • 2022-06-17
  • 2012-07-14
  • 2014-10-30
  • 2013-02-03
  • 2018-01-26
  • 2019-10-16
  • 2021-10-14
  • 2015-01-02
相关资源
最近更新 更多