我一直在努力让这个系统与 gmail api 系统和服务帐户一起工作(以避免创建一个空的用户帐户(,但我不确定我哪里出错了。
public static async Task<ServiceResponse> SendMail(ContactUsModel ContactInfo)
{
ServiceResponse response = new ServiceResponse();
try
{
var certificate = new X509Certificate2(@"cert.p12", "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("service account")
{
// Note: other scopes can be found here: https://developers.google.com/gmail/api/auth/scopes
Scopes = new[] { "https://mail.google.com" },
User = "service account"
}.FromCertificate(certificate));
// Note: result will be true if the access token was received successfully
bool result = await credential.RequestAccessTokenAsync(CancellationToken.None);
// create an OAuth2 SASL context
var oauth2 = new SaslMechanismOAuth2("service account", credential.Token.AccessToken);
MimeMessage msg = new MimeMessage();
msg.From.Add(new MailboxAddress(ContactInfo.Name, ContactInfo.EmailAddress));
msg.To.Add(new MailboxAddress("Me", "business email account"));
msg.Subject = ContactInfo.Subject;
msg.Body = new TextPart("plain")
{
Text = $"From: {ContactInfo.Name}nEmail: {ContactInfo.EmailAddress}nDate:{ContactInfo.AppointmentDate.ToString()}nMessage: {ContactInfo.Message}"
};
using(SmtpClient client = new SmtpClient())
{
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
client.Authenticate(oauth2);
client.Send(msg);
client.Disconnect(true);
}
response.Success = true;
response.Message = "Message Sent";
}
catch (Exception e)
{
response.Success = false;
response.Message = "An error occurred. Please call us.";
}
return response;
}
我启用了 gmail api,并将服务帐户设置为云函数调用程序。
这是我目前遇到的错误,我不确定为什么。
{"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"}
编辑: 更新代码并更新错误消息。
您使用了错误的范围。"https://www.googleapis.com/auth/gmail.send"作用域用于使用基于 HTTP 的协议库发送消息。
您需要"https://mail.google.com/"作用域才能与 IMAP、POP3 和/或 SMTP 协议一起使用。