SmtpEmailSender.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System.Net;
  2. using System.Net.Mail;
  3. using System.Threading.Tasks;
  4. using Abp.Dependency;
  5. using Abp.Extensions;
  6. namespace Abp.Net.Mail.Smtp
  7. {
  8. /// <summary>
  9. /// Used to send emails over SMTP.
  10. /// </summary>
  11. public class SmtpEmailSender : EmailSenderBase, ISmtpEmailSender, ITransientDependency
  12. {
  13. private readonly ISmtpEmailSenderConfiguration _configuration;
  14. /// <summary>
  15. /// Creates a new <see cref="SmtpEmailSender"/>.
  16. /// </summary>
  17. /// <param name="configuration">Configuration</param>
  18. public SmtpEmailSender(ISmtpEmailSenderConfiguration configuration)
  19. : base(configuration)
  20. {
  21. _configuration = configuration;
  22. }
  23. public SmtpClient BuildClient()
  24. {
  25. var host = _configuration.Host;
  26. var port = _configuration.Port;
  27. var smtpClient = new SmtpClient(host, port);
  28. try
  29. {
  30. if (_configuration.EnableSsl)
  31. {
  32. smtpClient.EnableSsl = true;
  33. }
  34. if (_configuration.UseDefaultCredentials)
  35. {
  36. smtpClient.UseDefaultCredentials = true;
  37. }
  38. else
  39. {
  40. smtpClient.UseDefaultCredentials = false;
  41. var userName = _configuration.UserName;
  42. if (!userName.IsNullOrEmpty())
  43. {
  44. var password = _configuration.Password;
  45. var domain = _configuration.Domain;
  46. smtpClient.Credentials = !domain.IsNullOrEmpty()
  47. ? new NetworkCredential(userName, password, domain)
  48. : new NetworkCredential(userName, password);
  49. }
  50. }
  51. return smtpClient;
  52. }
  53. catch
  54. {
  55. smtpClient.Dispose();
  56. throw;
  57. }
  58. }
  59. protected override async Task SendEmailAsync(MailMessage mail)
  60. {
  61. using (var smtpClient = BuildClient())
  62. {
  63. await smtpClient.SendMailAsync(mail);
  64. }
  65. }
  66. protected override void SendEmail(MailMessage mail)
  67. {
  68. using (var smtpClient = BuildClient())
  69. {
  70. smtpClient.Send(mail);
  71. }
  72. }
  73. }
  74. }