首页 > 解决方案 > 如何通过 Gmail API 从 .net 核心控制台应用程序发送电子邮件?

问题描述

我创建了一个控制台应用程序,以将来自 gmail 帐户的确认消息作为 cron 作业发送,最初它使用 mailkit 但它不再工作,所以我在 google 开发人员控制台上的一个新项目中添加了一个 apikey,然后添加了 Google.Apis.Gmail .v1 到我的项目,我正在尝试使用它,这是我到目前为止。

using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;

namespace sender
{
    class Program
    {
        static void Main(string[] args) {
            var gs = new GmailService(new BaseClientService.Initializer {
                    ApplicationName = "mi-app-sending-emails",
                    ApiKey = "AIzxxxx_E_xxxxxx-Hxxxxx"
                });
                Message b = new Message();
                b.Id = "sender@gmail.com";
                //code here
    
                gs.Users.Messages.Send(b, "customer@gmail.com");
         }
    }
}

它没有发送任何消息,文档也没有提供太多信息,您能否提供一些有关如何实现此代码工作的信息?

标签: c#.netgoogle-apigmail-apigoogle-api-dotnet-client

解决方案


首先你忘了执行。

var result = gs.Users.Messages.Send(b, "customer@gmail.com").Execute();

第二个 API 密钥不适用于 gmail api。您需要获得授权

private static UserCredential GetUserCredential(string clientSecretJson, string userName, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                    throw new ArgumentNullException("userName");
                if (string.IsNullOrEmpty(clientSecretJson))
                    throw new ArgumentNullException("clientSecretJson");
                if (!File.Exists(clientSecretJson))
                    throw new Exception("clientSecretJson file does not exist.");

                // These are the scopes of permissions you need. It is best to request only what you need and not all of them               
                using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                    // Requesting Authentication or loading previously stored authentication for userName
                    var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName,
                                                                             CancellationToken.None,
                                                                             new FileDataStore(credPath, true)).Result;

                    credential.GetAccessTokenForRequestAsync();
                    return credential;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Get user credentials failed.", ex);
            }
        }

/// <summary>
    /// This method get a valid service
    /// </summary>
    /// <param name="credential">Authecated user credentail</param>
    /// <returns>GmailService used to make requests against the Gmail API</returns>
    private static GmailService GetService(UserCredential credential)
    {
        try
        {
            if (credential == null)
                throw new ArgumentNullException("credential");

            // Create Gmail API service.
            return new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Gmail Oauth2 Authentication Sample"
            });
        }
        catch (Exception ex)
        {
            throw new Exception("Get Gmail service failed.", ex);
        }
    }
}

如果您查看message.send的文档,您会注意到它声明您需要被授权才能访问此方法。API 密钥仅适用于公共端点而不是私有端点

在此处输入图像描述


推荐阅读