EmailSender.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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;
  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. using var smtp = new SmtpClient();
  57. smtp.Connect(_emailSettings.Host, _emailSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
  58. smtp.Authenticate(_emailSettings.FromAddress, _emailSettings.Password);
  59. await smtp.SendAsync(emailObj);
  60. smtp.Disconnect(true);
  61. return true;
  62. }
  63. }
  64. }