要使用服务帐户详细信息发送电子邮件,需要在ASP.NET Core应用程序中安装Google.Apis.Auth和Google.Apis.Gmail.v1 NuGet包。在代码示例中,以下信息需要替换为自己的服务帐户详细信息:
代码示例:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
namespace ConsoleApp
{
class Program
{
static string[] Scopes = { GmailService.Scope.GmailSend };
static string ApplicationName = "Gmail API .NET Core";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
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);
}
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
Message message = new Message();
message.Raw = Base64UrlEncode(CreateMessageWithEmail(CreateEmail()));
try
{
Message sendMessageResponse = service.Users.Messages.Send(message, "me").Execute();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
public static string Base64UrlEncode(string input)
{
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
return Convert.ToBase64String(inputBytes)
.Replace('+', '-')
.Replace('/', '_')
.Replace("=", "");
}