gmail api发送邮件不起作用C#控制台应用程序(身份验证范围不足)

马克·沃德尔

我是Google Cloud / Gmail API的新手。在C#中,我想使用其gmail API:

  1. 登录到Google Cloud-作品
  2. 阅读清单项目-作品
  3. 发送电子邮件-不起作用

步骤3中的Api返回请求范围不足(403),我确信我已经登录到我的云帐户:我最怀疑的代码行是:

 static string[] Scopes = { GmailService.Scope.GmailAddonsCurrentActionCompose, GmailService.Scope.GmailAddonsCurrentMessageAction };

我收到此错误

 Request had insufficient authentication scopes. [403]
Errors [
        Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]

//代码

 class Program
{
    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/gmail-dotnet-quickstart.json
    static string[] Scopes = { GmailService.Scope.GmailAddonsCurrentActionCompose, GmailService.Scope.GmailAddonsCurrentMessageAction };
    static string ApplicationName = "Gmail API .NET Quickstart";
    static void Main(string[] args)
    {
        UserCredential credential;
        using (var stream =
            new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
        {
            // The file token.json stores the user's access and refresh tokens, and is created
            // automatically when the authorization flow completes for the first time.
            string credPath = "token.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,
        });
        // Define parameters of request.
        UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
        // List labels.
        IList<Label> labels = request.Execute().Labels;
        Console.WriteLine("Labels:");
        if (labels != null && labels.Count > 0)
        {
            foreach (var labelItem in labels)
            {
                Console.WriteLine("{0}", labelItem.Name);
            }
        }
        else
        {
            Console.WriteLine("No labels found.");
        }
        string plainText = "Body Test";
        var newMsg = new Google.Apis.Gmail.v1.Data.Message();
        newMsg.Raw = Program.Base64UrlEncode(plainText.ToString());
        try
        {
            service.Users.Messages.Send(newMsg, "me").Execute();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        /*
         {"Google.Apis.Requests.RequestError\r\nRequest had insufficient authentication scopes. 
          [403]\r\nErrors [\r\n\tMessage[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]\r\n]\r\n"}   Google.GoogleApiException
         */
        Console.Read();
    }
    public static string Base64UrlEncode(string input)
    {
        var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
        return Convert.ToBase64String(inputBytes).Replace("+", "-").Replace("/", "_").Replace("=", "");
    }
}

//从上面输出

Credential file saved to: token.json
Labels:
CHAT
SENT
INBOX
IMPORTANT
TRASH
DRAFT
SPAM
CATEGORY_FORUMS
CATEGORY_UPDATES
CATEGORY_PERSONAL
CATEGORY_PROMOTIONS
CATEGORY_SOCIAL
STARRED
UNREAD
Sent Messages
Pa0
P
Insurance
Junk E-mail
Licenses
Notes
Personal
Receipts
Travel
Work
Tickets
**Google.Apis.Requests.RequestError
Request had insufficient authentication scopes. [403]
Errors [
        Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]**
马克·沃德尔

好的:我决定采用GMAIL.API提供的凭据文件,并将其放入单行环境变量中,然后将JSON转换为GoogleClientSecrets:

    private static GoogleClientSecrets GetSecretsFromEnvironment()
    {
        var environmentConfiguration = new ConfigurationBuilder()
            .AddEnvironmentVariables()
            .Build();   
        var secretsEnv = environmentConfiguration["GoogleSecrets"];
        var secrets = JsonConvert.DeserializeObject<GoogleClientSecrets>(secretsEnv);
        return secrets;
    }

appsettings.json

{
  "MailSettings": {
    "account": "[email protected]",
    "subject": "Please Confirm Account",
    "from": "[email protected]",
    "HTML": "<b>Hello {0}</b>"
  }
}

由Google云控制台提供的凭据.json。我做成一个单行字符串并添加到EnvironmentVariable

在此处输入图片说明 和调用代码:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
namespace SendMail
{
    class Program
    {
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/gmail-dotnet-quickstart.json
        static string[] Scopes = { GmailService.Scope.GmailAddonsCurrentActionCompose, GmailService.Scope.GmailAddonsCurrentMessageAction, GmailService.Scope.GmailSend };
        static string ApplicationName = "Restful Resting Place";
        static async Task Main(params string[] args)
        {
            try
            {
                var configuration = new ConfigurationBuilder()
                    .AddJsonFile("appsettings.json")
                    .Build();
                Dictionary<string, string> MailSettings;
                MailSettings = configuration.GetSection("MailSettings").GetChildren().ToDictionary(x => x.Key, x => x.Value);
                MailSettings.Add("to", args[0]);
                MailSettings.Add("link", args[1]);
                GoogleClientSecrets gSecrets = GetSecretsFromEnvironment();
                string credPath = "token.json";
                UserCredential gcredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                       gSecrets.Secrets,
                       Scopes,
                       MailSettings["account"],
                       CancellationToken.None,
                       new FileDataStore(credPath, true));
                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = gcredential,
                    ApplicationName = ApplicationName,
                });

                SendItTwo(service, MailSettings);
                Console.WriteLine()
            }catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }   
        }
        private static GoogleClientSecrets GetSecretsFromEnvironment()
        {
            var environmentConfiguration = new ConfigurationBuilder()
                .AddEnvironmentVariables()
                .Build();   
            var secretsEnv = environmentConfiguration["GoogleSecrets"];
            var secrets = JsonConvert.DeserializeObject<GoogleClientSecrets>(secretsEnv);
            return secrets;
        }
        public static void SendItTwo(GmailService gmail,   Dictionary<string,string> dict)
        {
            MailMessage mailmsg = new MailMessage();
            {
                mailmsg.Subject = dict["subject"];
                mailmsg.Body = string.Format(dict["HTML"],dict["link"]);
                mailmsg.From = new MailAddress(dict["from"]);
                mailmsg.To.Add(new MailAddress(dict["to"]));         
                mailmsg.IsBodyHtml = true;
            }

            ////add attachment if specified
            if (dict.ContainsKey("attachement"))
            {
                if (File.Exists(dict["attachment"]))
                {
                    Attachment data = new Attachment(dict["attachment"]);
                    mailmsg.Attachments.Add(data);

                }else
                {
                    Console.WriteLine("Error: Invalid Attachemnt");
                }
            }     
            //Make mail message a Mime message
            MimeKit.MimeMessage mimemessage = MimeKit.MimeMessage.CreateFromMailMessage(mailmsg);
            Google.Apis.Gmail.v1.Data.Message finalmessage = new Google.Apis.Gmail.v1.Data.Message();
            finalmessage.Raw = Base64UrlEncode(mimemessage.ToString());  
            var result = gmail.Users.Messages.Send(finalmessage, "me").Execute();
        } 
        public static string Base64UrlEncode(string input)
        {
            var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
            return Convert.ToBase64String(inputBytes).Replace("+", "-").Replace("/", "_").Replace("=", "");
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

脚本使用Gmail发送邮件:无法在SMTP服务器上进行身份验证

来自分类Dev

发送Gmail电子邮件

来自分类Dev

Gmail API的邮件限制

来自分类Dev

使用ruby-gmail阅读Gmail邮件

来自分类Dev

gmail python api身份验证

来自分类Dev

Gmail控制台应用程序C#

来自分类Dev

GMail API C ++示例

来自分类Dev

Gmail API:权限不足

来自分类Dev

如何访问Gmail API?

来自分类Dev

查找Gmail邮件的ID

来自分类Dev

Gmail API发送限制

来自分类Dev

单元测试C#控制台应用程序(“使用”不起作用)

来自分类Dev

Gmail API python实施

来自分类Dev

Gmail API全域委派

来自分类Dev

如何在应用程序脚本gmail中的请求标头中使用具有身份验证的Firebase API用户添加在项目上

来自分类Dev

GMail认为Ubuntu GMail应用是Safari

来自分类Dev

从gmail帐户发送邮件-Python

来自分类Dev

从Gmail帐户删除邮件

来自分类Dev

SlowCheetah在C#控制台应用程序上不起作用

来自分类Dev

使用ruby-gmail阅读Gmail邮件

来自分类Dev

gmail python api身份验证

来自分类Dev

Gmail验证

来自分类Dev

GMail API C ++示例

来自分类Dev

Lubuntu的Gmail通知程序

来自分类Dev

Gmail邮件无法通过C#发送

来自分类Dev

使用gmail api发送电子邮件不起作用

来自分类Dev

使用 gmail API 添加 gmail 的签名

来自分类Dev

Gmail 邮件发送弹出

来自分类Dev

无法使用 SMTP Gmail 服务器发送电子邮件身份验证