From fc0ef2e89f4c6ec544a4641d784ae558b2d8204c Mon Sep 17 00:00:00 2001 From: he <109787524@qq.com> Date: Tue, 18 Nov 2025 10:40:08 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8E=88=E6=9D=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Service/Common/EmailLogService.cs | 125 ++++++++++++++++-- 1 file changed, 114 insertions(+), 11 deletions(-) diff --git a/IRaCIS.Core.Application/Service/Common/EmailLogService.cs b/IRaCIS.Core.Application/Service/Common/EmailLogService.cs index 41993244b..0aee97137 100644 --- a/IRaCIS.Core.Application/Service/Common/EmailLogService.cs +++ b/IRaCIS.Core.Application/Service/Common/EmailLogService.cs @@ -10,6 +10,7 @@ using IRaCIS.Core.Application.ViewModel; using IRaCIS.Core.Domain.Models; using IRaCIS.Core.Infra.EFCore; using IRaCIS.Core.Infrastructure.Extention; +using IdentityModel.Client; using MailKit; using MailKit.Net.Imap; using MailKit.Search; @@ -95,12 +96,11 @@ public class EmailLogService(IRepository _emailLogRepository, try { client.Connect(_systemEmailConfig.Imap, 993, SecureSocketOptions.SslOnConnect); - client.Authenticate(_systemEmailConfig.FromEmail, _systemEmailConfig.AuthorizationCode); - var sentFolder = client.GetFolder("已发送"); - sentFolder.Open(FolderAccess.ReadOnly); + AuthenticateImap(client); + var sentFolder = OpenSentFolder(client); var uid = new UniqueId(uint.Parse(emailInfo.UniqueId)); var message = sentFolder.GetMessage(uid); - emailInfo.Content = message.HtmlBody ?? string.Empty; + emailInfo.Content = message.HtmlBody ?? message.TextBody ?? string.Empty; if (emailInfo.AttachmentList.Count == 0) @@ -182,12 +182,11 @@ public class EmailLogService(IRepository _emailLogRepository, try { client.Connect(_systemEmailConfig.Imap, 993, SecureSocketOptions.SslOnConnect); - client.Authenticate(_systemEmailConfig.FromEmail, _systemEmailConfig.AuthorizationCode); - var sentFolder = client.GetFolder("已发送"); - sentFolder.Open(FolderAccess.ReadOnly); + AuthenticateImap(client); + var sentFolder = OpenSentFolder(client); var uid = new UniqueId(uint.Parse(emailInfo.UniqueId)); var message = sentFolder.GetMessage(uid); - emailInfo.Content = message.HtmlBody ?? string.Empty; + emailInfo.Content = message.HtmlBody ?? message.TextBody ?? string.Empty; sentFolder.Close(); } catch (Exception ex) @@ -246,9 +245,8 @@ public class EmailLogService(IRepository _emailLogRepository, try { client.Connect(_systemEmailConfig.Imap, 993, SecureSocketOptions.SslOnConnect); - client.Authenticate(_systemEmailConfig.FromEmail, _systemEmailConfig.AuthorizationCode); - var sentFolder = client.GetFolder("已发送"); - sentFolder.Open(FolderAccess.ReadOnly); + AuthenticateImap(client); + var sentFolder = OpenSentFolder(client); var startDate = maxTime ?? DateTime.MinValue; var searchQuery = SearchQuery.All.And(SearchQuery.DeliveredAfter(startDate)); @@ -334,6 +332,111 @@ public class EmailLogService(IRepository _emailLogRepository, } } + private IMailFolder OpenSentFolder(ImapClient client) + { + IMailFolder folder = null; + try + { + folder = client.GetFolder(SpecialFolder.Sent); + } + catch { } + + if (folder == null) + { + var candidates = new[] { "已发送", "已发送邮件", "Sent", "Sent Items", "[Gmail]/Sent Mail" }; + foreach (var name in candidates) + { + try + { + var f = client.GetFolder(name); + if (f != null) + { + folder = f; + break; + } + } + catch { } + } + } + + if (folder == null) + { + try + { + var personal = client.GetFolder(client.PersonalNamespaces.FirstOrDefault()); + if (personal != null) + { + foreach (var sub in personal.GetSubfolders(false)) + { + if (string.Equals(sub.FullName, "Sent", StringComparison.OrdinalIgnoreCase) || + string.Equals(sub.FullName, "Sent Items", StringComparison.OrdinalIgnoreCase)) + { + folder = sub; + break; + } + } + } + } + catch { } + } + + if (folder == null) + throw new InvalidOperationException("未找到已发送文件夹"); + + folder.Open(FolderAccess.ReadOnly); + return folder; + } + + private void AuthenticateImap(ImapClient client) + { + try + { + client.Authenticate(_systemEmailConfig.FromEmail, _systemEmailConfig.AuthorizationCode); + } + catch (AuthenticationException) + { + //if (_systemEmailConfig.UseOAuth2 && _systemEmailConfig.OAuth2AccessToken.IsNotNullOrEmpty()) + //{ + // var sasl = new SaslMechanismOAuth2(_systemEmailConfig.FromEmail, _systemEmailConfig.OAuth2AccessToken); + // client.Authenticate(sasl); + // return; + //} + //if (_systemEmailConfig.OAuth2AccessToken.IsNullOrEmpty()) + //{ + // var token = AcquireOAuth2TokenByPassword(); + // if (token.IsNotNullOrEmpty()) + // { + // _systemEmailConfig.OAuth2AccessToken = token; + // var sasl = new SaslMechanismOAuth2(_systemEmailConfig.FromEmail, token); + // client.Authenticate(sasl); + // return; + // } + //} + throw; + } + } + + //private string AcquireOAuth2TokenByPassword() + //{ + // if (_systemEmailConfig.OAuthTenantId.IsNullOrEmpty() || _systemEmailConfig.OAuthClientId.IsNullOrEmpty()) + // return string.Empty; + + // using var http = new HttpClient(); + // var req = new PasswordTokenRequest + // { + // Address = $"https://login.microsoftonline.com/{_systemEmailConfig.OAuthTenantId}/oauth2/v2.0/token", + // ClientId = _systemEmailConfig.OAuthClientId, + // ClientSecret = _systemEmailConfig.OAuthClientSecret, + // Scope = "offline_access https://outlook.office365.com/IMAP.AccessAsUser.All", + // UserName = _systemEmailConfig.FromEmail, + // Password = _systemEmailConfig.AuthorizationCode + // }; + // var resp = http.RequestPasswordTokenAsync(req).GetAwaiter().GetResult(); + // if (resp.IsError || resp.AccessToken.IsNullOrEmpty()) + // return string.Empty; + // return resp.AccessToken; + //} + // 取skip的值 public int CalcReverseSkip(int pageIndex, int pageSize, int totalCount) {