| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- using Admin.NET.Core.Service;
- namespace Admin.NET.Plugin.ApprovalFlow.Service;
- /// <summary>
- /// 邮件推送(P4-16)
- /// 复用 Admin.NET.Core 的 SysEmailService.SendEmail(content, title, toEmail),按目标用户 Email 逐个发送。
- /// </summary>
- public class EmailNotifyPusher : INotifyPusher, ITransient
- {
- public string Channel => "Email";
- private readonly SysEmailService _emailService;
- private readonly SqlSugarRepository<SysUser> _userRep;
- public EmailNotifyPusher(SysEmailService emailService, SqlSugarRepository<SysUser> userRep)
- {
- _emailService = emailService;
- _userRep = userRep;
- }
- public bool IsEnabled(NotifyChannelConfig cfg) => cfg?.Email == true;
- public async Task<FlowNotifyPushResult> PushAsync(List<long> userIds, FlowNotification notification)
- {
- if (userIds.Count == 0) return FlowNotifyPushResult.Ok(0);
- var users = await _userRep.AsQueryable()
- .Where(u => userIds.Contains(u.Id) && !string.IsNullOrEmpty(u.Email))
- .Select(u => new { u.Id, u.Email, u.RealName })
- .ToListAsync();
- if (users.Count == 0) return FlowNotifyPushResult.Ok(0);
- var html = $"<p>{System.Net.WebUtility.HtmlEncode(notification.Content)}</p>" +
- $"<hr><p style='color:#888;font-size:12px'>该邮件由系统自动发送,请勿直接回复。实例 Id:{notification.InstanceId}</p>";
- var errors = new List<string>();
- var successCount = 0;
- foreach (var user in users)
- {
- try
- {
- await _emailService.SendEmail(html, notification.Title, user.Email);
- successCount++;
- }
- catch (Exception ex)
- {
- errors.Add($"[{user.Id}]{ex.Message}");
- }
- }
- if (successCount > 0 && errors.Count == 0)
- return FlowNotifyPushResult.Ok(successCount);
- if (successCount > 0)
- return new FlowNotifyPushResult
- {
- Success = true,
- ActualTargetCount = successCount,
- ErrorMessage = $"部分失败: {string.Join("; ", errors)}"
- };
- return FlowNotifyPushResult.Fail(string.Join("; ", errors));
- }
- }
|