【问题标题】:Send Google Mail in C# failed because of 403 Insufficient permissions由于 403 权限不足,在 C# 中发送 Google Mail 失败
【发布时间】:2020-03-13 04:23:51
【问题描述】:

我创建了一个控制台应用程序,它向一个地址发送电子邮件,它显示如下:

    private static string[] Scopes = { GmailService.Scope.GmailCompose, GmailService.Scope.GmailSend };
    private static string ApplicationName = "Gmail API Quickstart";

    private const string SUBJECT = "Some simple subject";
    private static string[] emails = new string[] { "teodorescumihail2008@live.com" };

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

        using (var stream =
            new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            string credPath = Environment.GetFolderPath(
                Environment.SpecialFolder.Personal);
            credPath = Path.Combine(credPath, ".credentials/gmail-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 Gmail API service.
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });

        var msg = new AE.Net.Mail.MailMessage
        {
            Subject = SUBJECT,
            Body = "Test body",
            From = new MailAddress("teodorescumihail2008@gmail.com")
        };

        msg.To.Add(new MailAddress("teodorescumihail2008@live.com"));
        StringWriter sw = new StringWriter();
        msg.Save(sw);

        var result = service.Users.Messages.Send(new Message
        {
            Raw = Base64UrlEncode(sw.ToString())
        }, "me").Execute();

        Console.Read();
    }

    private static string Base64UrlEncode(string input)
    {
        var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
        // Special "url-safe" base64 encode.
        return Convert.ToBase64String(inputBytes)
          .Replace('+', '-')
          .Replace('/', '_')
          .Replace("=", "");
    }

执行发送电子邮件时,我收到:

我的错误在哪里?

【问题讨论】:

标签: c# gmail-api


【解决方案1】:

我假设您更改了代码中的范围,而没有从 Gmail 重新授权/获取新的凭据文件。问题是 GmailAPI 不知道您的范围已更新。您必须在 GmailAPI 中重新授权您的应用,方法是删除您的应用权限并重新生成您的 credentials.json,以便在 GmailAPI 上更新您的范围。

删除您的应用权限:click here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-08
    • 2022-01-19
    • 2018-11-14
    • 2019-07-21
    • 1970-01-01
    • 2015-10-11
    • 2017-02-20
    • 2018-05-20
    相关资源
    最近更新 更多