public async Task<ActionResult> MassEmail(CustomEmailViewModel model) { if (model.Subject.IsEmpty() || model.Body.IsEmpty()) return Json(new { status = 0, error = "Both a Subject and a Body must be provided." }); int numSent; try { Dictionary<string, string> recipients; using (NickBeckyWedding db = new NickBeckyWedding()) { var query = from ra in db.RSVPAttendees join r in db.RSVPs on ra.RSVP_ID equals r.ID select new { ra.Name, Email = ra.EmailAddress, r.Attending }; if (model.RecipientSelection != "All") query = query.Where(r => r.Attending); query = query.Distinct(); recipients = await query.ToDictionaryAsync(r => r.Name, r => r.Email); } numSent = await SendMassEmailAsync(model, recipients); } catch (Exception ex) { return Json(new { status = 0, error = ex.Message }); } return Json(new { status = 1, message = "All " + numSent + " emails successfully sent." }); }
public async Task<ActionResult> TestMassEmail() { CustomEmailViewModel model = new CustomEmailViewModel { Body = "This is a test email message. We'll want to test some HTML in here as well. <p>This is a separate paragraph</p><br /><br />That was two line breaks.<br /><br /><h3>This is an H3</h3><h2>H2</h2><h1>This is an H1</h1><a href='http://kalashianfamily.com/'>This is a link to KalashianFamily.com</a>. <p>Thanks,</p><p>Connor Gray</p>", Subject = "Test Email" }; Dictionary<string, string> recipients = new Dictionary<string, string> { { "Connor Outlook", "*****@*****.**" }, { "Connor Gmail", "*****@*****.**" }, { "Connor School", "*****@*****.**" }, { "Connor Work", "*****@*****.**" } }; await SendMassEmailAsync(model, recipients); return HttpNotFound(); }
private async Task<int> SendMassEmailAsync(CustomEmailViewModel model, Dictionary<string, string> recipients) { string baseBody = this.RenderPartialViewToString("EmailShell", model); SendGrid.Web transportWeb = new SendGrid.Web(ConfigurationManager.AppSettings["sendgrid:APIKey"]); int count = 0; foreach (KeyValuePair<string, string> recipient in recipients) { SendGridMessage message = new SendGridMessage { From = new MailAddress("*****@*****.**", "Becky & Nick"), Subject = model.Subject, Html = baseBody.Replace("-recipientName-", recipient.Key) }; message.AddTo($"{recipient.Key} <{recipient.Value}>"); await transportWeb.DeliverAsync(message); count++; } return count; }