无法使用服务帐户通过

时间:2020-02-01 23:41:33

标签: c# asp.net-core gmail mailkit

我已经工作了一段时间,尝试使该系统与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/"}

编辑: 更新代码并更新错误消息。

1 个答案:

答案 0 :(得分:0)

您使用了错误的范围。 “ https://www.googleapis.com/auth/gmail.send”作用域用于使用基于HTTP的协议库发送消息。

您需要将“ https://mail.google.com/”范围用于IMAP,POP3和/或SMTP协议。

相关问题