public async Task <bool> SendMessageWithPurpose <TModel>(MailModel model, EmailPurpose emailPurpose, TModel templateModel) where TModel : class { try { var result = await _email .To(model.ToEmail) .Subject(model.Subject) .UsingTemplateFromFile(_templateStorageService.GetPathByKey(emailPurpose.ToString()), templateModel) .SendAsync(); if (!result.Successful) { _logger.LogError("Failed to send an email.\n{Errors}", string.Join(Environment.NewLine, result.ErrorMessages)); } return(result.Successful); } catch (Exception ex) { _logger.LogError(ex, $"{DateTime.Now}: Failed to send email with purpose {emailPurpose.ToString()} ❌! ({ex.Message})"); return(false); } }
/// <summary> /// Sends an email for the given <see cref="EmailPurpose"/> to the <see cref="ApplicationUser"/> /// </summary> /// <param name="user">The <see cref="ApplicationUser"/> as the recipient of the email.</param> /// <param name="purpose">The <see cref="EmailPurpose"/> of the email.</param> private async Task SendCodeByEmail(ApplicationUser user, EmailPurpose purpose) { string code; _userEmailTask.Timeout = TimeSpan.FromMinutes(1); _userEmailTask.EmailCultureInfo = CultureInfo.CurrentUICulture; _userEmailTask.ToEmail = user.Email; switch (purpose) { case EmailPurpose.ConfirmYourEmail: _userEmailTask.Subject = _localizer["Please confirm your email address"].Value; _userEmailTask.ViewNames = new [] { ViewNames.Emails.EmailPleaseConfirmEmail, ViewNames.Emails.EmailPleaseConfirmEmailTxt }; _userEmailTask.LogMessage = "Send email confirmation mail"; code = _dataProtector.Encrypt(user.Email, DateTimeOffset.UtcNow.Add(_dataProtectionTokenProviderOptions.Value.TokenLifespan)).Base64UrlEncode(); _userEmailTask.Model = (Email : user.Email, CallbackUrl : Url.Action(nameof(Register), nameof(Account), new { Organization = _siteContext.UrlSegmentValue, code }, protocol : HttpContext.Request.Scheme), _siteContext); break; case EmailPurpose.ForgotPassword: _userEmailTask.Subject = _localizer["This is your password recovery key"].Value; _userEmailTask.ViewNames = new [] { ViewNames.Emails.EmailPasswordReset, ViewNames.Emails.EmailPasswordResetTxt }; _userEmailTask.LogMessage = "Password recovery email"; code = (await _signInManager.UserManager.GeneratePasswordResetTokenAsync(user)).Base64UrlEncode(); _userEmailTask.Model = (Email : user.Email, CallbackUrl : Url.Action(nameof(ResetPassword), nameof(Account), new { Organization = _siteContext.UrlSegmentValue, id = user.Id, code }, protocol : HttpContext.Request.Scheme), _siteContext); break; default: _logger.LogError($"Illegal enum type for {nameof(EmailPurpose)}"); break; } _queue.QueueTask(_userEmailTask); }
/// <summary> /// Sends an email for the given <see cref="Account.EmailPurpose"/> to the <see cref="ApplicationUser"/> /// </summary> /// <param name="user">The <see cref="ApplicationUser"/> as the recipient of the email.</param> /// <param name="purpose">The <see cref="Account.EmailPurpose"/> of the email.</param> /// <param name="model">The model parameter for the view.</param> private async Task SendEmail(ApplicationUser user, EmailPurpose purpose, string model) { _userEmailTask1.Timeout = _userEmailTask2.Timeout = TimeSpan.FromMinutes(1); _userEmailTask1.EmailCultureInfo = _userEmailTask2.EmailCultureInfo = CultureInfo.CurrentUICulture; switch (purpose) { case EmailPurpose.NotifyCurrentPrimaryEmail: _userEmailTask1.ToEmail = user.Email; _userEmailTask1.Subject = _localizer["Your primary email is about to be changed"].Value; _userEmailTask1.ViewNames = new[] { ViewNames.Emails.NotifyCurrentPrimaryEmail, ViewNames.Emails.NotifyCurrentPrimaryEmailTxt }; _userEmailTask1.LogMessage = "Notify current primary email about the requested change"; _userEmailTask1.Model = (Email : model, CallbackUrl : string.Empty, OrganizationContext : _siteContext); _queue.QueueTask(_userEmailTask1); break; case EmailPurpose.ConfirmNewPrimaryEmail: var newEmail = model; _userEmailTask2.ToEmail = newEmail; _userEmailTask2.Subject = _localizer["Please confirm your new primary email"].Value; _userEmailTask2.ViewNames = new [] { ViewNames.Emails.ConfirmNewPrimaryEmail, ViewNames.Emails.ConfirmNewPrimaryEmailTxt }; _userEmailTask2.LogMessage = "Email to confirm the new primary email"; var code = (await _userManager.GenerateChangeEmailTokenAsync(user, newEmail)).Base64UrlEncode(); _userEmailTask2.Model = (Email : newEmail, CallbackUrl : Url.Action(nameof(ConfirmNewPrimaryEmail), nameof(Manage), new { Organization = _siteContext.UrlSegmentValue, id = user.Id, code, e = newEmail.Base64UrlEncode() }, protocol : HttpContext.Request.Scheme), OrganizationContext : _siteContext); _queue.QueueTask(_userEmailTask2); break; default: _logger.LogError($"Illegal enum type for {nameof(EmailPurpose)}"); break; } }
/// <summary> /// Sends an email for the given <see cref="EmailPurpose"/> to the <see cref="ApplicationUser"/> /// </summary> /// <param name="user">The <see cref="ApplicationUser"/> as the recipient of the email.</param> /// <param name="purpose">The <see cref="EmailPurpose"/> of the email.</param> private async Task SendCodeByEmail(ApplicationUser user, EmailPurpose purpose) { string code; var deadline = DateTime.UtcNow.Add(_dataProtectionTokenProviderOptions.Value.TokenLifespan); // round down to full hours deadline = new DateTime(deadline.Year, deadline.Month, deadline.Day, deadline.Hour, 0, 0); switch (purpose) { case EmailPurpose.PleaseConfirmEmail: code = _dataProtector.Encrypt(user.Email, DateTimeOffset.UtcNow.Add(_dataProtectionTokenProviderOptions.Value.TokenLifespan)).Base64UrlEncode(); _sendEmailTask.SetMessageCreator(new ChangeUserAccountCreator { Parameters = { Email = user.Email, Subject = _localizer["Please confirm your email address"].Value, CallbackUrl = Url.Action(nameof(Register), nameof(Account), new { Organization= _tenantContext.SiteContext.UrlSegmentValue, code }, protocol: HttpContext.Request.Scheme), DeadlineUtc = deadline, CultureInfo = CultureInfo.CurrentUICulture, TemplateNameTxt = TemplateName.PleaseConfirmEmailTxt, TemplateNameHtml = TemplateName.PleaseConfirmEmailHtml } }); break; case EmailPurpose.PasswordReset: code = (await _signInManager.UserManager.GeneratePasswordResetTokenAsync(user)).Base64UrlEncode(); _sendEmailTask.SetMessageCreator(new ChangeUserAccountCreator { Parameters = { Email = user.Email, Subject = _localizer["Please confirm your email address"].Value, CallbackUrl = Url.Action(nameof(ResetPassword), nameof(Account), new { Organization= _tenantContext.SiteContext.UrlSegmentValue, id = user.Id,code }, protocol: HttpContext.Request.Scheme), DeadlineUtc = deadline, CultureInfo = CultureInfo.CurrentUICulture, TemplateNameTxt = TemplateName.PasswordResetTxt, TemplateNameHtml = TemplateName.PasswordResetHtml } }); break; default: _logger.LogError($"Illegal enum type for {nameof(EmailPurpose)}"); break; } _queue.QueueTask(_sendEmailTask); }
public EmailForm(EmailPurpose use, int messageIndex = -1, IList<int> fromIndexList = null) { // set up this form so it's all ready to go for whatever purpose we need this.use = use; InitializeComponent(); if (use == EmailPurpose.Receive) { rtbWrite.Dispose(); btnSend.TabIndex--; tlpMain.SetColumnSpan(wbrView, 3); lblFrom.Text = "From"; btnSend.Text = "Close"; this.messageIndex = messageIndex; txtSubject.ReadOnly = true; } else if (use == EmailPurpose.Send || use == EmailPurpose.Reply || use == EmailPurpose.Forward) { wbrView.Dispose(); btnForward.Dispose(); btnReply.Dispose(); rtbWrite.TabIndex--; btnSend.TabIndex--; tlpMain.SetColumn(rtbWrite, 0); tlpMain.SetColumnSpan(rtbWrite, 3); this.fromIndexList = fromIndexList; // we need this for replying and forwarding this.messageIndex = messageIndex; lblFrom.Text = "To"; btnSend.Text = "Send"; } else if (use == EmailPurpose.Bcc || use == EmailPurpose.MassEmail) { wbrView.Dispose(); btnForward.Dispose(); btnReply.Dispose(); rtbWrite.TabIndex--; btnSend.TabIndex--; tlpMain.SetColumn(rtbWrite, 0); tlpMain.SetColumnSpan(rtbWrite, 3); this.fromIndexList = fromIndexList; lblFrom.Text = "BCC"; btnSend.Text = "Send"; } }
public bool SendMessage(string[] toAddress, string[] toName, string strSubject, string strHTML, EmailPurpose purpose = EmailPurpose.Send) { // set up a try, catch thing... sending emails is tricky business try { MailMessage mail = new MailMessage(); // Note to self: change this mail.From = new System.Net.Mail.MailAddress(strAddress, ClsStorage.currentClub.strName); // check that the address and name arrays are the same int iLength = toAddress.Length; if (iLength != toName.Length) return false; else { // add the to names // if bcc'ing, then only bcc if (purpose == EmailPurpose.Send || purpose == EmailPurpose.Forward || purpose == EmailPurpose.Reply) for (int i = 0; i < iLength; i++) mail.To.Add(new System.Net.Mail.MailAddress(toAddress[i], toName[i])); else for (int i = 0; i < iLength; i++) mail.Bcc.Add(new System.Net.Mail.MailAddress(toAddress[i], toName[i])); // now set the meat of the message mail.Subject = strSubject; mail.IsBodyHtml = true; mail.Body = strHTML; // send it! sendClient.Send(mail); // success! return true; } } catch { return false; } }
public static string replySubject(string strSubject, EmailPurpose use) { if (use == EmailPurpose.Reply && !strSubject.StartsWith("re:", true, null)) return "RE: " + strSubject; else if (use == EmailPurpose.Forward && !strSubject.StartsWith("fw:", true, null)) return "FW: " + strSubject; else return strSubject; }
public static string replyHeader(string strFromAddress, string strFromName, DateTime timeSent, string strTo, string strSubject, EmailPurpose use) { // go through the various elements and implement them string output = "<p class=MsoNormal><span style='color:#1F497D'><o:p> </o:p></span></p><div><div style='border:none;border-top:solid #E1E1E1 1.0pt;padding:3.0pt 0cm 0cm 0cm'><p class=MsoNormal><b>"; output += "<span lang=EN-US style='mso-fareast-language:EN-CA'>From:</span></b><span lang=EN-US style='mso-fareast-language:EN-CA'>"; output += String.Format(" {0} [mailto:{1}] <br>", strFromName, strFromAddress); output += "<b>Sent:</b> " + timeSent.ToLongDateString() + " " + timeSent.ToLongTimeString() + "<br>"; output += "<b>To:</b> " + strTo + "<br><b>Subject:</b> "; // correctly mark whether this is a reply or forwarding output += replySubject(strSubject, use); output += strSubject + "<o:p></o:p></span></p>"; return output; }
public EmailType EmailTypeWithPurposeExists(IUnitOfWork uow, EmailPurpose emailPurpose) { return(uow.Session.QueryOver <EmailType>() .Where(x => x.EmailPurpose == emailPurpose).Take(1) .SingleOrDefault <EmailType>()); }