From 5fe47a855b26ed152957c2b6666ea3d54a74d270 Mon Sep 17 00:00:00 2001 From: Tohirjon-Odilov Date: Sun, 3 Mar 2024 22:24:35 +0500 Subject: [PATCH] add email sender --- .../IServices/IEmailSenderService.cs | 7 +++ .../Services/EmailSenderService.cs | 47 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 Exam.StockManagement.Application/Abstractions/IServices/IEmailSenderService.cs create mode 100644 Exam.StockManagement.Application/Services/EmailSenderService.cs diff --git a/Exam.StockManagement.Application/Abstractions/IServices/IEmailSenderService.cs b/Exam.StockManagement.Application/Abstractions/IServices/IEmailSenderService.cs new file mode 100644 index 0000000..291b5c6 --- /dev/null +++ b/Exam.StockManagement.Application/Abstractions/IServices/IEmailSenderService.cs @@ -0,0 +1,7 @@ +namespace Exam.StockManagement.Application.Abstractions.IServices +{ + public interface IEmailSenderService + { + public Task SendEmailAsync(string email, string path); + } +} diff --git a/Exam.StockManagement.Application/Services/EmailSenderService.cs b/Exam.StockManagement.Application/Services/EmailSenderService.cs new file mode 100644 index 0000000..d650f64 --- /dev/null +++ b/Exam.StockManagement.Application/Services/EmailSenderService.cs @@ -0,0 +1,47 @@ +using Exam.StockManagement.Application.Abstractions.IServices; +using Microsoft.Extensions.Configuration; +using System.Net; +using System.Net.Mail; + +namespace Exam.StockManagement.Application.Services +{ + public class EmailSenderService : IEmailSenderService + { + private IConfiguration _config; + + public EmailSenderService(IConfiguration config) + { + _config = config; + } + + public async Task SendEmailAsync(string email, string path) + { + var code = new Random().Next(1000, 9999).ToString(); + + IConfigurationSection? emailSettings = _config.GetSection("EmailSettings"); + MailMessage? mailMessage = new MailMessage + { + From = new MailAddress(emailSettings["Sender"]!, emailSettings["SenderName"]), + Subject = "Ro'yhatdan o'tishingiz uchun parol.", + Body = $"Sizning kodingiz: {code}", + IsBodyHtml = true, + + }; + mailMessage.To.Add(email!); + + using var smtpClient = new SmtpClient(emailSettings["MailServer"], int.Parse(emailSettings["MailPort"]!)) + { + Port = Convert.ToInt32(emailSettings["MailPort"]), + DeliveryMethod = SmtpDeliveryMethod.Network, + Credentials = new NetworkCredential(emailSettings["Sender"], emailSettings["Password"]), + EnableSsl = true, + }; + + await File.WriteAllTextAsync(path, code); + + //smtpClient.UseDefaultCredentials = true; + await smtpClient.SendMailAsync(mailMessage); + return code; + } + } +}