12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- using MailKit.Net.Smtp;
- using Microsoft.Extensions.Options;
- using MimeKit;
- using MTWorkHR.Application.Models.Email;
- using MTWorkHR.Application.Services;
- using MTWorkHR.Core.Global;
- using SendGrid;
- using SendGrid.Helpers.Mail;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace MTWorkHR.Infrastructure.EmailService
- {
- public class EmailSender : IEmailSender
- {
- public EmailSettings _emailSettings { get; }
- public EmailSender(IOptions<EmailSettings> emailSettings)
- {
- _emailSettings = emailSettings.Value;
- }
- public async Task<bool> SendEmailGrid(EmailMessage email)
- {
- var client = new SendGridClient(_emailSettings.ApiKey);
- var to = new EmailAddress(email.To);
- var from = new EmailAddress
- {
- Email = _emailSettings.FromAddress,
- Name = _emailSettings.FromName
- };
- email.Body = email.Body + " /n" + email.url;
- var message = MailHelper.CreateSingleEmail(from, to, email.Subject, email.Body, email.Body);
- var response = await client.SendEmailAsync(message);
- return response.IsSuccessStatusCode;
- }
- public async Task<bool> SendEmail(EmailMessage email)
- {
- var mailTo = email.To;
- var settings = _emailSettings;
- if (settings.FromAddress == null || settings.FromAddress== "" || settings.Password == null || settings.TemplatePath == null || settings.Host == null || settings.Port == 0 || mailTo == null)
- return false;
- //string FilePath = _emailSettings.TemplatePath;
- //StreamReader str = new StreamReader(FilePath);
- //string MailText = str.ReadToEnd();
- //str.Close();
- //MailText = MailText.Replace("[NotificationType]", email.Subject).Replace("[Info]", email.Body).Replace("[Link]", email.url );
- var emailObj = new MimeMessage();
- emailObj.Sender = MailboxAddress.Parse(_emailSettings.FromAddress);
- emailObj.To.Add(MailboxAddress.Parse(mailTo));
- emailObj.Subject = email.Subject;
- var builder = new BodyBuilder();
- email.Body = email.Body + " /n" + email.url;
- builder.HtmlBody = email.Body;
- emailObj.Body = builder.ToMessageBody();
- try
- {
- using var smtp = new SmtpClient();
- smtp.Connect(_emailSettings.Host, _emailSettings.Port, MailKit.Security.SecureSocketOptions.StartTls);
- smtp.Authenticate(_emailSettings.FromAddress, _emailSettings.Password);
- await smtp.SendAsync(emailObj);
- smtp.Disconnect(true);
- }catch (Exception ex) { var ms = ex.Message; }
- return true;
- }
- }
- }
|