EmailNotifyPusher.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using Admin.NET.Core.Service;
  2. namespace Admin.NET.Plugin.ApprovalFlow.Service;
  3. /// <summary>
  4. /// 邮件推送(P4-16)
  5. /// 复用 Admin.NET.Core 的 SysEmailService.SendEmail(content, title, toEmail),按目标用户 Email 逐个发送。
  6. /// </summary>
  7. public class EmailNotifyPusher : INotifyPusher, ITransient
  8. {
  9. public string Channel => "Email";
  10. private readonly SysEmailService _emailService;
  11. private readonly SqlSugarRepository<SysUser> _userRep;
  12. public EmailNotifyPusher(SysEmailService emailService, SqlSugarRepository<SysUser> userRep)
  13. {
  14. _emailService = emailService;
  15. _userRep = userRep;
  16. }
  17. public bool IsEnabled(NotifyChannelConfig cfg) => cfg?.Email == true;
  18. public async Task<FlowNotifyPushResult> PushAsync(List<long> userIds, FlowNotification notification)
  19. {
  20. if (userIds.Count == 0) return FlowNotifyPushResult.Ok(0);
  21. var users = await _userRep.AsQueryable()
  22. .Where(u => userIds.Contains(u.Id) && !string.IsNullOrEmpty(u.Email))
  23. .Select(u => new { u.Id, u.Email, u.RealName })
  24. .ToListAsync();
  25. if (users.Count == 0) return FlowNotifyPushResult.Ok(0);
  26. var html = $"<p>{System.Net.WebUtility.HtmlEncode(notification.Content)}</p>" +
  27. $"<hr><p style='color:#888;font-size:12px'>该邮件由系统自动发送,请勿直接回复。实例 Id:{notification.InstanceId}</p>";
  28. var errors = new List<string>();
  29. var successCount = 0;
  30. foreach (var user in users)
  31. {
  32. try
  33. {
  34. await _emailService.SendEmail(html, notification.Title, user.Email);
  35. successCount++;
  36. }
  37. catch (Exception ex)
  38. {
  39. errors.Add($"[{user.Id}]{ex.Message}");
  40. }
  41. }
  42. if (successCount > 0 && errors.Count == 0)
  43. return FlowNotifyPushResult.Ok(successCount);
  44. if (successCount > 0)
  45. return new FlowNotifyPushResult
  46. {
  47. Success = true,
  48. ActualTargetCount = successCount,
  49. ErrorMessage = $"部分失败: {string.Join("; ", errors)}"
  50. };
  51. return FlowNotifyPushResult.Fail(string.Join("; ", errors));
  52. }
  53. }