【发布时间】:2022-01-18 06:33:50
【问题描述】:
此代码适用于使用 IMAP 和 SMTP 协议发送和接收电子邮件,但我现在需要使用 EWS(Exchange Web 服务)协议发送和接收电子邮件,以防有人在其帐户上禁用了 IMAP/SMTP 服务。谁能告诉我我必须改变什么才能做到这一点?
using (ImapClient client = new ImapClient())
{
client.Connect("outlook.office365.com", 993, SecureSocketOptions.Auto);
SaslMechanism oauth2;
if (client.AuthenticationMechanisms.Contains("OAUTHBEARER"))
oauth2 = new SaslMechanismOAuthBearer(this.Identity.Email, this.AccessToken);
else
oauth2 = new SaslMechanismOAuth2(this.Identity.Email, this.AccessToken);
client.Authenticate(oauth2);
FolderNamespaceCollection namespaces = client.PersonalNamespaces;
int totalCount = 0;
IList<IMailFolder> folders = client.GetFolders(client.PersonalNamespaces[0], StatusItems.Unread | StatusItems.Count);
foreach (IMailFolder folder in folders)
{
folder.Open(FolderAccess.ReadOnly);
totalCount += folder.Search(SearchQuery.NotSeen).Count;
folder.Close();
}
client.Disconnect(true);
}
using (SmtpClient client = new SmtpClient())
{
client.Connect("smtp-mail.outlook.com", 587, SecureSocketOptions.Auto);
SaslMechanism oauth2;
if (client.AuthenticationMechanisms.Contains("OAUTHBEARER"))
oauth2 = new SaslMechanismOAuthBearer(this.Identity.Email, this.AccessToken);
else
oauth2 = new SaslMechanismOAuth2(this.Identity.Email, this.AccessToken);
client.Authenticate(oauth2);
using (MimeMessage message = new MimeMessage())
{
message.Sender = new MailboxAddress(this.Identity.Email, this.Identity.Email);
message.From.Add(message.Sender);
message.To.Add(new MailboxAddress("<Recipient>", "recipient@email.com"));
message.Subject = "SMTP OAuth Test";
TextPart body = new TextPart
{
Text = "If this was received then it worked"
};
message.Body = body;
client.Send(message);
}
client.Disconnect(true);
}
【问题讨论】:
-
我使用这个 nuget-Package Microsoft.Exchange.WebServices 来读取和写入项目(会议、约会)到不同用户的日历。我没有现成的邮件示例。
标签: c# oauth-2.0 exchangewebservices