using Microsoft.Extensions.Options; using STAFF_API.Configure; using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Threading.Tasks; namespace STAFF_API.Services { public class MailService: IMailService { private readonly MailConfig _config; public MailService(IOptions config) { _config = config.Value; } /// /// Sends an mail message /// /// Sender address /// Recepient address /// Bcc recepient /// Cc recepient /// Subject of mail message /// Body of mail message public async Task SendMailMessage(string from, string[] recepients, string[] bccs, string[] ccs, string subject, string body) { // Instantiate a new instance of MailMessage MailMessage mMailMessage = new MailMessage(); // Set the sender address of the mail message mMailMessage.From = new MailAddress(_config.UserName, from); // Set the recepient address of the mail message foreach (string recepient in recepients) { if (!string.IsNullOrEmpty(recepient)) { mMailMessage.To.Add(new MailAddress(recepient)); } } // Check if the bcc value is nothing or an empty string foreach (string bcc in bccs) { if (!string.IsNullOrEmpty(bcc)) { mMailMessage.Bcc.Add(new MailAddress(bcc)); } } // Check if the cc value is nothing or an empty value foreach (string cc in ccs) { if (!string.IsNullOrEmpty(cc)) { mMailMessage.CC.Add(new MailAddress(cc)); } } // Set the subject of the mail message mMailMessage.Subject = subject; // Set the body of the mail message mMailMessage.Body = body; // Set the format of the mail message body as HTML mMailMessage.IsBodyHtml = true; // Set the priority of the mail message to normal mMailMessage.Priority = MailPriority.Normal; // Instantiate a new instance of SmtpClient SmtpClient mSmtpClient = new SmtpClient(); // Send the mail message mSmtpClient.EnableSsl = _config.EnableSsl; System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(_config.UserName, _config.Password); mSmtpClient.UseDefaultCredentials = _config.DefaultCredentials; mSmtpClient.Credentials = basicAuthenticationInfo; mSmtpClient.Host = _config.Host; mSmtpClient.Port = _config.Port; try { await mSmtpClient.SendMailAsync(mMailMessage); } catch (Exception ex1) { throw ex1; } } } }