EmailSender.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using MailKit.Net.Smtp;
  2. using Microsoft.Extensions.Options;
  3. using MimeKit;
  4. using MTWorkHR.Application.Models.Email;
  5. using MTWorkHR.Application.Services;
  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 EmailSender : IEmailSender
  17. {
  18. public EmailSettings _emailSettings { get; }
  19. public EmailSender(IOptions<EmailSettings> emailSettings)
  20. {
  21. _emailSettings = emailSettings.Value;
  22. }
  23. public async Task<bool> SendEmailGrid(EmailMessage email)
  24. {
  25. var client = new SendGridClient(_emailSettings.ApiKey);
  26. var to = new EmailAddress(email.To);
  27. var from = new EmailAddress
  28. {
  29. Email = _emailSettings.FromAddress,
  30. Name = _emailSettings.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 = _emailSettings;
  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 = _emailSettings.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(_emailSettings.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(_emailSettings.Host, _emailSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
  60. smtp.Authenticate(_emailSettings.FromAddress, _emailSettings.Password);
  61. await smtp.SendAsync(emailObj);
  62. smtp.Disconnect(true);
  63. }catch (Exception ex) { var ms = ex.Message; }
  64. return true;
  65. }
  66. }
  67. }