c# - 如何通过 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");
}
}
}
它没有发送任何消息,文档也没有提供太多信息,您能否提供一些有关如何实现此代码工作的信息?
解决方案
首先你忘了执行。
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 密钥仅适用于公共端点而不是私有端点
推荐阅读
- python - 如何从我的 github 存储库中的 docs 文件夹中获取数据?当我尝试部署应用程序时它没有显示目录
- python - 为什么最后一个打印语句不需要变量符号?
- mariadb - Galera Cluster - 失去连接后在集群外启动一个节点
- c# - 如何使用 MailKit 库在电子邮件上获取我的回复?
- r - 刻面后缺少带有 ggpubr 的括号
- pytest - 气流 - Pytest - 找不到夹具'dag'
- javascript - 从数组中返回对象数组
- javascript - 使用 Java 脚本将新行添加到 HTML 表中时如何增加列
- javascript - 在 webdriverIO 中调用基本函数时出错
- xamarin.forms - Xamarin.Forms DatePicker 对话框颜色自定义