1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- using MailKit.Net.Smtp;
- using Microsoft.Extensions.Options;
- using MimeKit;
- using MTWorkHR.Application.Models.Email;
- using MTWorkHR.Application.Services;
- using MTWorkHR.Core;
- 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();
- 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);
- return true;
- }
- }
- }
|