如何通过 Gmail API 从 .net 核心控制台应用程序发送电子邮件?
How to send emails from a .net core console application via Gmail API?
我创建了一个控制台应用程序来从 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");
}
}
}
它不发送任何消息,文档也没有提供太多信息,能否请您提供一些有关如何实现此代码工作的信息?
首先你忘了执行。
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 密钥仅适用于 public 端点而不适用于私有端点
我创建了一个控制台应用程序来从 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");
}
}
}
它不发送任何消息,文档也没有提供太多信息,能否请您提供一些有关如何实现此代码工作的信息?
首先你忘了执行。
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 密钥仅适用于 public 端点而不适用于私有端点