如何在 .NET 应用程序中使用 OAuth 访问 SMTP 和 IMAP 服务器

一则或许对你有用的小广告

欢迎加入小哈的星球 ,你将获得:专属的项目实战 / 1v1 提问 / Java 学习路线 / 学习打卡 / 每月赠书 / 社群讨论

  • 新项目:《从零手撸:仿小红书(微服务架构)》 正在持续爆肝中,基于 Spring Cloud Alibaba + Spring Boot 3.x + JDK 17...点击查看项目介绍 ;
  • 《从零手撸:前后端分离博客项目(全栈开发)》 2 期已完结,演示链接: http://116.62.199.48/ ;

截止目前, 星球 内专栏累计输出 63w+ 字,讲解图 2808+ 张,还在持续爆肝中.. 后续还会上新更多项目,目标是将 Java 领域典型的项目都整一波,如秒杀系统, 在线商城, IM 即时通讯,权限管理,Spring Cloud Alibaba 微服务等等,已有 2200+ 小伙伴加入学习 ,欢迎点击围观

此技术提示解释了 .NET 开发人员如何在 .NET 应用程序中 使用 OAuth 访问 SMTP 和 IMAP 服务器 。 Aspose.Email for .NET 可用于访问 SMTP 和 IMAP 服务器。由于 OAuth 1.0 已于 2012 年 4 月 20 日正式弃用,因此仅在 2.0 版中实现了对 Google 邮件的 OAuth 支持。目前,Google 仅支持 Google Apps Platform 的 OAuth,公共邮件帐户不能与 OAuth 一起使用机制。创建新的 Google Apps 帐户时,应为此帐户注册一个新的“已安装的应用程序”,以便在 API 控制台中进行测试。可以创建免费试用帐户,由 Google Apps for Business 提供。

使用 Aspose.Email 访问 SMTP 和 IMAP 服务器的代码示例如下所示:


 //[C# Code Sample]

static void Main(string[] args) { // The authorizationCode should be replaced with your value. // To get authorizationCode use the URL bellow: // https://accounts.google.com/o/oauth2/auth?redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=929645059575.apps.googleusercontent.com&scope=https%3A%2F%2Fmail.google.com%2F string authorizationCode = "4/zx4_I4ZhhUdmgLdsejpjeMkwAAMs.kk7o1Qx9U28VOl05ti8ZT3Y1uIlidQI"; // authorizationCode should be replaced with new value !!!!!!! string accessToken = GetAccessToken(authorizationCode); AccessSMTPServer(accessToken); AccessIMAPServer(accessToken); }

static void AccessSMTPServer(string accessToken)
{
    MailMessage message = new MailMessage(
        "user1@testaccount1913.narod2.ru",
        "user1@testaccount1913.narod2.ru",
        "NETWORKNET-33499 - " + Guid.NewGuid().ToString(),
        "Access to SMTP servers using OAuth");
    using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "user1@testaccount1913.narod2.ru", accessToken, true))
    {
        client.Timeout = 400000;
        client.SecurityMode = SmtpSslSecurityMode.Implicit;
        client.EnableSsl = true;
        client.Send(message);
    }
}


static void AccessIMAPServer(string accessToken)
{
    using (ImapClient client = new ImapClient("imap.gmail.com", 993, "user1@testaccount1913.narod2.ru", accessToken, true))
    {
        client.EnableSsl = true;
        client.SecurityMode = ImapSslSecurityMode.Implicit;
        client.Connect();
        client.SelectFolder("Inbox");
        ImapMessageInfoCollection messageInfoCol = client.ListMessages();
    }
}

internal static string GetAccessToken(string authorizationCode)
{
    string actionUrl = "https://accounts.google.com/o/oauth2/token";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(actionUrl);
    request.CookieContainer = new CookieContainer();
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    string encodedParameters = string.Format(
        "client_id={1}&code={0}&client_secret={2}&redirect_uri={3}&grant_type={4}",
        HttpUtility.UrlEncode(authorizationCode),
        HttpUtility.UrlEncode("929645059575.apps.googleusercontent.com"),
        HttpUtility.UrlEncode("USnH5eQRsC4XrjJbpGG7WVq5"),
        HttpUtility.UrlEncode("urn:ietf:wg:oauth:2.0:oob"),
        HttpUtility.UrlEncode("authorization_code")
        );
    byte[] requestData = Encoding.UTF8.GetBytes(encodedParameters);
    request.ContentLength = requestData.Length;
    if (requestData.Length > 0)
        using (Stream stream = request.GetRequestStream())
            stream.Write(requestData, 0, requestData.Length);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string responseText = null;
    using (TextReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
        responseText = reader.ReadToEnd();
    string accessToken = null;
    foreach (string sPair in responseText.
        Replace("{", "").
        Replace("}", "").
        Replace("\"", "").
        Split(new string[] { ",\n" }, StringSplitOptions.None))
    {
        string[] pair = sPair.Split(':');
        if ("access_token" == pair[0].Trim())
        {
            accessToken = pair[1].Trim();
            break;
        }
    }
    return accessToken;
}



 //[C# Code Sample]

static void Main(string[] args) { // The authorizationCode should be replaced with your value. // To get authorizationCode use the URL bellow: // https://accounts.google.com/o/oauth2/auth?redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=929645059575.apps.googleusercontent.com&scope=https%3A%2F%2Fmail.google.com%2F string authorizationCode = "4/zx4_I4ZhhUdmgLdsejpjeMkwAAMs.kk7o1Qx9U28VOl05ti8ZT3Y1uIlidQI"; // authorizationCode should be replaced with new value !!!!!!! string accessToken = GetAccessToken(authorizationCode); AccessSMTPServer(accessToken); AccessIMAPServer(accessToken); }

static void AccessSMTPServer(string accessToken)
{
    MailMessage message = new MailMessage(
        "user1@testaccount1913.narod2.ru",
        "user1@testaccount1913.narod2.ru",
        "NETWORKNET-33499 - " + Guid.NewGuid().ToString(),
        "Access to SMTP servers using OAuth");
    using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587, "user1@testaccount1913.narod2.ru", accessToken, true))
    {
        client.Timeout = 400000;
        client.SecurityMode = SmtpSslSecurityMode.Implicit;
        client.EnableSsl = true;
        client.Send(message);
    }
}


static void AccessIMAPServer(string accessToken)
{
    using (ImapClient client = new ImapClient("imap.gmail.com", 993, "user1@testaccount1913.narod2.ru", accessToken, true))
    {
        client.EnableSsl = true;
        client.SecurityMode = ImapSslSecurityMode.Implicit;
        client.Connect();
        client.SelectFolder("Inbox");
        ImapMessageInfoCollection messageInfoCol = client.ListMessages();
    }
}

internal static string GetAccessToken(string authorizationCode)
{
    string actionUrl = "https://accounts.google.com/o/oauth2/token";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(actionUrl);
    request.CookieContainer = new CookieContainer();
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    string encodedParameters = string.Format(
        "client_id={1}&code={0}&client_secret={2}&redirect_uri={3}&grant_type={4}",
        HttpUtility.UrlEncode(authorizationCode),
        HttpUtility.UrlEncode("929645059575.apps.googleusercontent.com"),
        HttpUtility.UrlEncode("USnH5eQRsC4XrjJbpGG7WVq5"),
        HttpUtility.UrlEncode("urn:ietf:wg:oauth:2.0:oob"),
        HttpUtility.UrlEncode("authorization_code")
        );
    byte[] requestData = Encoding.UTF8.GetBytes(encodedParameters);
    request.ContentLength = requestData.Length;
    if (requestData.Length > 0)
        using (Stream stream = request.GetRequestStream())
            stream.Write(requestData, 0, requestData.Length);
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    string responseText = null;
    using (TextReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
        responseText = reader.ReadToEnd();
    string accessToken = null;
    foreach (string sPair in responseText.
        Replace("{", "").
        Replace("}", "").
        Replace("\"", "").
        Split(new string[] { ",\n" }, StringSplitOptions.None))
    {
        string[] pair = sPair.Split(':');
        if ("access_token" == pair[0].Trim())
        {
            accessToken = pair[1].Trim();
            break;
        }
    }
    return accessToken;
}


相关文章