using System; using System.Threading.Tasks; using MimeKit; using Serilog; using MailKit.Net.Smtp; using webapi.Infractructure.Helpers; using webapi.Infrastructure.Model; using System.Collections.Generic; using webapi.Infractructure.Resources; using System.Linq; using webapi.Infrastructure.Core; using webapi.Application.Services; namespace webapi.Infrastructure.Services { public class EmailService: IEmailService { readonly IEmailSettings _settings; readonly ILogger _log; readonly IConfigureService _configureService; readonly ISPHandlerService _spHandlerService; public EmailService(ILogger log, IConfigureService configureService, IEmailSettings settings, ISPHandlerService handlerService) { _settings = settings; _configureService = configureService; _spHandlerService = handlerService; _log = log; } public async Task SendRegisterNewEmail(string username, string password, string email) { var letter = new Letter() { Username = username, Password = password }; //string emailError = string.Empty; var bodyBuilder = new BodyBuilder() { HtmlBody = TemplateHelper.Generate(letter, Constants.Email.TEMPLATE_REGISTER_NEW), //TextBody = $"Для подтверждения e-mail кликните на этой ссылке: {url}" }; string subj = TaloyhtioCondoCommon.RegisterBox_EmailSubject; _log.Information($"SendRegisterNewEmail message sent to email: {email}, Message: \n{bodyBuilder.HtmlBody}"); await Send(email, subj, bodyBuilder.ToMessageBody()); _log.Information($"SendRegisterNewEmail message sent"); } public async Task SendRegisterExistingEmail(string username, string email) { var letter = new Letter() { Username = username }; //string emailError = string.Empty; var bodyBuilder = new BodyBuilder() { HtmlBody = TemplateHelper.Generate(letter, Constants.Email.TEMPLATE_REGISTER_EXISTING), //TextBody = $"Для подтверждения e-mail кликните на этой ссылке: {url}" }; //string body = TemplateHelper.Generate(letter, Constants.Email.TEMPLATE_REGISTER_EXISTING); string subj = TaloyhtioCondoCommon.RegisterBox_EmailSubject; _log.Information($"SendRegisterExistingEmail message sent to email: {email}, Message: \n{bodyBuilder.HtmlBody}"); await Send(email, subj, bodyBuilder.ToMessageBody()); _log.Information($"SendRegisterExistingEmail message sent"); } public async Task SendUserFlatApprovalEmail(Guid pmcId, IEnumerable approverEmails, string userName, string flatTitle) { _log.Information($"pmcId: {pmcId}"); var pmcUrl = await _spHandlerService.GetTaylohtioPMCUrl(pmcId); _log.Information($"pmc url: {pmcUrl}"); var letter = new Letter() { FlatTitle = flatTitle, Url = pmcUrl.Trim('"') + "/_layouts/15/Taloyhtio/IDP/PendingApprovalRequest.aspx" }; //string emailError = string.Empty; //var lang = await _spService.GetPMCLang(pmcId); //Thread.CurrentThread.CurrentCulture = new CultureInfo(lang); //Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang); _log.Information($"Templates folder path: {System.Web.Hosting.HostingEnvironment.MapPath("~\\bin\\Templates")}"); var bodyBuilder = new BodyBuilder() { HtmlBody = TemplateHelper.Generate(letter, Constants.Email.TEMPLATE_NOTIFY_APPROVER), //TextBody = $"Для подтверждения e-mail кликните на этой ссылке: {url}" }; string subj = TaloyhtioCondoCommon.Approver_EmailSubject; foreach (var email in approverEmails) { _log.Information($"SendUserFlatApprovalEmail message sent to email: {email}, Message: \n{bodyBuilder.HtmlBody}"); await Send(email, subj, bodyBuilder.ToMessageBody()); _log.Information($"SendUserFlatApprovalEmail message sent"); } } public async Task SendUserFlatApprovalRequestApprovedEmail(Guid pmcId, string email, string userName, string flatTitle) { var letter = new Letter() { FlatTitle = flatTitle }; //string emailError = string.Empty; //var lang = await _spService.GetPMCLang(pmcId); //Thread.CurrentThread.CurrentCulture = new CultureInfo(lang); //Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang); _log.Information($"Templates folder path: {System.Web.Hosting.HostingEnvironment.MapPath("~\\bin\\Templates")}"); var bodyBuilder = new BodyBuilder() { HtmlBody = TemplateHelper.Generate(letter, Constants.Email.TEMPLATE_REQUEST_APPROVED), //TextBody = $"Для подтверждения e-mail кликните на этой ссылке: {url}" }; string subj = TaloyhtioCondoCommon.RequestApproved_EmailSubject; _log.Information($"SendUserFlatApprovalRequestApprovedEmail message sent to email: {email}, Message: \n{bodyBuilder.HtmlBody}"); await Send(email, subj, bodyBuilder.ToMessageBody()); _log.Information($"SendUserFlatApprovalRequestApprovedEmail message sent "); } public async Task SendUserFlatApprovalRequestRejectedEmail(Guid pmcId, string email, string userName, string flatTitle) { var letter = new Letter() { FlatTitle = flatTitle }; //string emailError = string.Empty; //var lang = await _spService.GetPMCLang(pmcId); //Thread.CurrentThread.CurrentCulture = new CultureInfo(lang); //Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang); _log.Information($"Templates folder path: {System.Web.Hosting.HostingEnvironment.MapPath("~\\bin\\Templates")}"); var bodyBuilder = new BodyBuilder() { HtmlBody = TemplateHelper.Generate(letter, Constants.Email.TEMPLATE_REQUEST_REJECTED), }; string subj = TaloyhtioCondoCommon.RequestRejected_EmailSubject; _log.Information($"SendUserFlatApprovalRequestRejectedEmail message sent to email: {email}, Message: \n{bodyBuilder.HtmlBody}"); await Send(email, subj, bodyBuilder.ToMessageBody()); _log.Information($"SendUserFlatApprovalRequestRejectedEmail message sent "); } private async Task Send(string toAddressesStr, string subj, MimeEntity body, string fromAddress = null) { try { _log.Information($"Message about to send toAddressesStr: {toAddressesStr}, subj: {subj}, body: {body == null}, fromAddress: {fromAddress}"); if (string.IsNullOrEmpty(toAddressesStr)) { _log.Warning($"Argument is null: {nameof(toAddressesStr)}"); return false; } var toAddresses = toAddressesStr.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (toAddresses.Length == 0) { _log.Warning($"Argument is empty: {nameof(toAddresses)}"); return false; } await CheckSPSettings(); //string smtpServer = SPAdministrationWebApplication.Local.OutboundMailServiceInstance.Server.Address; //string smtpFrom = fromAddress ?? SPAdministrationWebApplication.Local.OutboundMailSenderAddress; var smtpServer = _settings.SmtpServer; var smtpFrom = _settings.FromAddress; foreach (string to in toAddresses) { var mailMessage = new MimeMessage( (fromAddress ?? smtpFrom).Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => new MailboxAddress(x)), new[] { new MailboxAddress(to) }, subj, body); //Create the SMTP client object and send the message using (var emailClient = new SmtpClient()) { _log.Warning($"Send email via : {smtpServer}:{_settings.SmtpPort}, to: {string.Join(";", mailMessage.To)}, from: {string.Join(";", mailMessage.From)}"); emailClient.Connect(smtpServer, _settings.SmtpPort); //, _settings.SmtpPort, true); _log.Information($"Sending email body: {mailMessage.HtmlBody}"); await emailClient.SendAsync(mailMessage); emailClient.Disconnect(true); } } return true; } catch (Exception x) { _log.Error($"Error occured during sending email: {x.Message}\n{x.StackTrace}", x); return false; } } private async Task CheckSPSettings() { await Task.CompletedTask; //var spSettings = await _configureService.GetEmailSettings(); //if (spSettings != null) //{ // _settings.SmtpServer = spSettings.SmtpServer; // _settings.FromAddress = spSettings.FromAddress; //} } } }