【问题标题】:Send mail through SMTP using OAuth 2使用 OAuth 2 通过 SMTP 发送邮件
【发布时间】:2019-09-27 05:36:53
【问题描述】:

我需要通过 OAuth 2 发送 SMTP 邮件。我创建了一些代码来获取令牌,但得到以下错误响应:

错误:“unauthorized_client”,描述:“客户端未经授权无法使用此方法检索访问令牌,或者客户端未获得任何请求范围的授权。”,Uri:

代码:

var certificate = new X509Certificate2(Server.MapPath("folder/serviceaccountgenratedcredecialfile.p12"), "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("service-account-email@my-project-name.iam.gserviceaccount.com")
                     {
                         Scopes = new[] { "https://mail.google.com/" },
                         User = "user-email@gmail.com"
                     }.FromCertificate(certificate));

bool result = credential.RequestAccessTokenAsync(CancellationToken.None).Result;

【问题讨论】:

    标签: c# .net smtp


    【解决方案1】:

    例如Gmail:

    void SendMailWithXOAUTH2(string userEmail, string accessToken)
    {
        try
        {
            // Gmail SMTP server address
            SmtpServer oServer = new SmtpServer("smtp.gmail.com");
            // enable SSL connection
            oServer.ConnectType = SmtpConnectType.ConnectSSLAuto;
            // Using 587 port, you can also use 465 port
            oServer.Port = 587;
    
            // use Gmail SMTP OAUTH 2.0 authentication
            oServer.AuthType = SmtpAuthType.XOAUTH2;
            // set user authentication
            oServer.User = userEmail;
            // use access token as password
            oServer.Password = accessToken;
    
            SmtpMail oMail = new SmtpMail("TryIt");
            // Your gmail email address
            oMail.From = userEmail;
            oMail.To = "support@emailarchitect.net";
    
            oMail.Subject = "test email from gmail account with OAUTH 2";
            oMail.TextBody = "this is a test email sent from c# project with gmail.";
    
            Console.WriteLine("start to send email using OAUTH 2.0 ...");
    
            SmtpClient oSmtp = new SmtpClient();
            oSmtp.SendMail(oServer, oMail);
    
            Console.WriteLine("The email has been submitted to server successfully!");
        }
        catch (Exception ep)
        {
            Console.WriteLine("Exception: {0}", ep.Message);
        }
    

    使用客户端 ID 和客户端密码获取访问令牌。 现在您可以使用客户端 ID 和客户端密码来获取用户电子邮件地址和访问令牌。基本上,OAUTH 使用 HTTP 协议,首先,用户在 Google Web Authentication 中输入用户和密码,Google 将访问令牌返回给您的应用程序,最后,您的应用程序使用访问令牌访问Gmail SMTP server。您可以在EASendMail Installation Path\Samples_{Programming language/Developer Tool}\GmailOauth.* 项目中找到示例代码。

    你必须申请你的client id和client secret,不要在示例项目中使用client id,因为现在有限制。如果您收到“此应用未验证”信息,请点击"advanced" -> Go to ...进行测试。

    【讨论】:

    • 我需要 accessToken 怎么获取 accessToken ?
    【解决方案2】:

    我认为 smtp 支持的唯一身份验证方式是基本身份验证(用户/密码)。如果你想使用 auth,你应该考虑使用 ews (Exchange Web Service)。

    【讨论】:

      【解决方案3】:
              MailMessage mailMessage = new MailMessage();
              mailMessage.From = new MailAddress("abc@abc.com"); //From Email Id
              mailMessage.Subject = Subj; //Subject of Email
              mailMessage.Body = Message; //body or message of Email
              mailMessage.IsBodyHtml = true;
              List<string> ToEmailList = ToEmail.Split(',').ToList();
              ToEmailList.ForEach(x => mailMessage.To.Add(new MailAddress(x.ToString())));
              SmtpClient smtp = new SmtpClient("smtpout.secureserver.net", 25);
              smtp.Credentials = new System.Net.NetworkCredential()
              {
                  UserName = "abc@abc.com",
                  Password = "abc@001"
              };
              smtp.EnableSsl = true;
      

      【讨论】:

      • Bhanu Pratap 我认为这没有使用 OAuth 2
      猜你喜欢
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 2016-06-05
      • 2012-09-10
      • 2010-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多