MailSender.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using MailKit.Net.Smtp;
  2. using Microsoft.Extensions.Options;
  3. using MimeKit;
  4. using MTWorkHR.Core.Email;
  5. using MTWorkHR.Core.Entities;
  6. using MTWorkHR.Core.Global;
  7. using SendGrid;
  8. using SendGrid.Helpers.Mail;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. namespace MTWorkHR.Infrastructure.EmailService
  15. {
  16. public class MailSender : IMailSender
  17. {
  18. public AppSettingsConfiguration _configuration { get; }
  19. public MailSender(AppSettingsConfiguration configuration)
  20. {
  21. _configuration = configuration;
  22. }
  23. public async Task<bool> SendEmailGrid(EmailMessage email)
  24. {
  25. var client = new SendGridClient(_configuration.MailSettings.ApiKey);
  26. var to = new EmailAddress(email.To);
  27. var from = new EmailAddress
  28. {
  29. Email = _configuration.MailSettings.FromAddress,
  30. Name = _configuration.MailSettings.FromName
  31. };
  32. email.Body = email.Body + " /n" + email.url;
  33. var message = MailHelper.CreateSingleEmail(from, to, email.Subject, email.Body, email.Body);
  34. var response = await client.SendEmailAsync(message);
  35. return response.IsSuccessStatusCode;
  36. }
  37. public async Task<bool> SendEmail(EmailMessage email)
  38. {
  39. var mailTo = email.To;
  40. var settings = _configuration.MailSettings;
  41. if (settings.FromAddress == null || settings.FromAddress== "" || settings.Password == null || settings.TemplatePath == null || settings.Host == null || settings.Port == 0 || mailTo == null)
  42. return false;
  43. //string FilePath = _configuration.MailSettings.TemplatePath;
  44. //StreamReader str = new StreamReader(FilePath);
  45. //string MailText = str.ReadToEnd();
  46. //str.Close();
  47. //MailText = MailText.Replace("[NotificationType]", email.Subject).Replace("[Info]", email.Body).Replace("[Link]", email.url );
  48. var emailObj = new MimeMessage();
  49. emailObj.Sender = MailboxAddress.Parse(_configuration.MailSettings.FromAddress);
  50. emailObj.To.Add(MailboxAddress.Parse(mailTo));
  51. emailObj.Subject = email.Subject;
  52. var builder = new BodyBuilder();
  53. email.Body = email.Body + " /n" + email.url;
  54. builder.HtmlBody = email.Body;
  55. emailObj.Body = builder.ToMessageBody();
  56. try
  57. {
  58. using var smtp = new SmtpClient();
  59. smtp.Connect(_configuration.MailSettings.Host, _configuration.MailSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
  60. smtp.Authenticate(_configuration.MailSettings.FromAddress, _configuration.MailSettings.Password);
  61. await smtp.SendAsync(emailObj);
  62. smtp.Disconnect(true);
  63. }catch (Exception ex) { var ms = ex.Message; }
  64. return true;
  65. }
  66. }
  67. }