using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace Sevomin.Models.Helpers { public enum EmailType { EmailConfirmation, PasswordReset, NewPassword } public class SevominEmailer { public Dictionary Parameters { get; set; } public EmailType EmailType { get; set; } private string EmailFolderPath; private string EmailConfirmationFilePath; private string NewPasswordFilePath; private string PasswordResetFilePath; public SevominEmailer() { EmailFolderPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/app_data"), "emails"); if (!Directory.Exists(EmailFolderPath)) throw new ApplicationException("Emails folder does not exist in the right address."); EmailConfirmationFilePath = Path.Combine(EmailFolderPath, "email-confirmation.html"); NewPasswordFilePath = Path.Combine(EmailFolderPath, "new-password.html"); PasswordResetFilePath = Path.Combine(EmailFolderPath, "password-reset.html"); if(!File.Exists(EmailConfirmationFilePath)) throw new ApplicationException("Email confirmation template does not exist in the right address."); if (!File.Exists(NewPasswordFilePath)) throw new ApplicationException("New password template does not exist in the right address."); if (!File.Exists(PasswordResetFilePath)) throw new ApplicationException("Password reset template does not exist in the right address."); Parameters = new Dictionary(); } public SevominEmailer(Dictionary parameters, EmailType emailType) : this() { Parameters = parameters; EmailType = emailType; } public async Task SendAsync(string to, string subject, bool isHtml) { SmtpClient client = new SmtpClient(); MailMessage msg = new MailMessage(); string template; switch (EmailType) { case EmailType.EmailConfirmation: template = File.ReadAllText(EmailConfirmationFilePath, Encoding.UTF8); break; case EmailType.PasswordReset: template = File.ReadAllText(PasswordResetFilePath, Encoding.UTF8); break; case EmailType.NewPassword: template = File.ReadAllText(NewPasswordFilePath, Encoding.UTF8); break; default: template = string.Empty; break; } foreach (var address in to.Split(',')) msg.To.Add(address); msg.From = new MailAddress("no-reply@sevom.in", "سومین - مرکز کاریابی کنترل پروژه"); msg.SubjectEncoding = Encoding.UTF8; msg.BodyEncoding = Encoding.UTF8; msg.Subject = subject; msg.IsBodyHtml = isHtml; Func getBody = () => { foreach (var param in Parameters) template = template.Replace(string.Format("[{0}]", param.Key), param.Value); return template; }; msg.Body = getBody(); await Task.Run(() => { client.Send(msg); }); } } }