此技术提示解释了 .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;
}