using System.Net; using MailKit.Net.Smtp; using MailKit.Security; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MimeKit; using Microsoft.AspNetCore.Identity; using Yavsc.Interface; using Yavsc.Settings; using Yavsc.Models; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.Extensions.Localization; using System.Web; namespace Yavsc.Services { public class MailSender : IEmailSender, IEmailSender, ITrueEmailSender { private readonly IStringLocalizer localizer; readonly SiteSettings siteSettings; readonly SmtpSettings smtpSettings; private readonly ILogger logger; public MailSender( IOptions sitesOptions, IOptions smtpOptions, ILoggerFactory loggerFactory, IStringLocalizer localizer ) { this.localizer = localizer; siteSettings = sitesOptions.Value; smtpSettings = smtpOptions.Value; logger = loggerFactory.CreateLogger(); } public Task SendConfirmationLinkAsync(ApplicationUser user, string email, string confirmationLink) { throw new NotImplementedException(); } /// /// /// /// /// /// /// a MessageWithPayloadResponse, /// bool somethingsent = (response.failure == 0 && response.success > 0) /// public Task SendEmailAsync(string email, string subject, string htmlMessage) { return SendEmailAsync("", email, subject, htmlMessage); } public async Task SendEmailAsync(string name, string email, string subject, string htmlMessage) { logger.LogInformation($"SendEmail for {email} : {subject}"); MimeMessage msg = new(); msg.From.Add(new MailboxAddress(siteSettings.Owner.Name, siteSettings.Owner.EMail)); msg.To.Add(new MailboxAddress(name, email)); TextPart text; msg.Body = text = new TextPart("html") { Text = $"{htmlMessage}" }; msg.Subject = subject; msg.MessageId = MimeKit.Utils.MimeUtils.GenerateMessageId( siteSettings.Authority ); using (SmtpClient sc = new()) { sc.Timeout = 30000; sc.Connect( smtpSettings.Host, smtpSettings.Port, SecureSocketOptions.Auto ); if (smtpSettings.UserName != null) { sc.Authenticate(smtpSettings.UserName, smtpSettings.Password); } await sc.SendAsync(msg); logger.LogInformation($"Sent : {msg.MessageId}"); sc.Disconnect(true); } return msg.MessageId; } public void SendEmailFromCriteria(string Criteria) { throw new NotImplementedException(); } public async Task SendPasswordResetCodeAsync(ApplicationUser user, string email, string resetCode) { var callbackUrl = siteSettings.Audience + "/Account/ResetPassword/" + HttpUtility.UrlEncode(user.Id) + "/" + HttpUtility.UrlEncode(resetCode); await SendEmailAsync(user.UserName, user.Email, localizer["Reset Password"], localizer["Please reset your password by "] + " following this link"); throw new NotImplementedException(); } public async Task SendPasswordResetLinkAsync(ApplicationUser user, string email, string resetLink) { await SendEmailAsync(user.UserName, user.Email, localizer["Reset Password"], localizer["Please reset your password by "] + " following this link"); } } }