/// <summary> /// dispatch the notification as an email /// </summary> /// <param name="notification">The notification to dispatch</param> /// <param name="users">users to send the email to</param> /// <param name="store"></param> /// <returns></returns> public bool Dispatch(Notification notification,IEnumerable<Organisation.SimpleUser> users,IDocumentStore store ) { //create an email from the notification and user details var email = new Email { Body = notification.Body, Subject = notification.Title, To = users.Where(simpleUser => !string.IsNullOrEmpty(simpleUser.EmailAddress)).Select(u => new EmailRecipient { Email = u.EmailAddress, Name = u.FullName }).ToList() }; if (email.To.Count == 0) { _log.Warn(string.Format("Cannot send email with subject {0} because there is not a valid To address",email.Subject)); return false; } try { if (_emailSender.Send(email)) { using (var session = store.OpenSession()) { session.Store(email); session.SaveChanges(); } _log.Info(string.Format("successfully sent email to {0}", email.To[0].Email)); return true; } _log.Error(string.Format("problem sending email for {0}", email.To[0].Email)); return false; } catch (Exception ex) { _log.Error(string.Format("problem sending email for {0}", email.To[0].Email), ex); return false; } }
/// <summary> /// Send the email /// </summary> /// <param name="email">The email to be sent</param> /// <returns>a flag indicating if the email ewas ent or not (as far as is known)</returns> public bool Send(Email email) { //use restsharp to create a client to talk to the MailGun REST API var client = new RestClient { BaseUrl = ConfigurationManager.AppSettings["MAILGUN_API_URL"], Authenticator = new HttpBasicAuthenticator("api", ConfigurationManager.AppSettings["MAILGUN_API_KEY"]) }; //create a new request to mailgun and fill in the details of the email to be sent var request = new RestRequest(); var mailgunDomain = ConfigurationManager.AppSettings["MAILGUN_DOMAIN"]; request.AddParameter("domain", mailgunDomain , ParameterType.UrlSegment); request.Resource = "{domain}/messages"; request.AddParameter("from", string.Format("Illuminate <illuminate@{0}>", mailgunDomain)); foreach (var to in email.To) { request.AddParameter("to", to.Email); } foreach (var cc in email.Cc) { request.AddParameter("cc", cc.Email); } foreach (var bcc in email.Bcc) { request.AddParameter("bcc", bcc.Email); } request.AddParameter("subject", email.Subject); request.AddParameter("html", email.Body); request.Method = Method.POST; //TODO - test response for errors //execute the request - mailgun should send the email var response = client.Execute(request); return response.ErrorException == null; }
public void DoWork(IlluminateDatabase database,IEmailSender emailSender) { Logger.Information("EmailDailyTasks started"); //we need to get a list of tasks that are Overdue, duetoday or due tomorrow. foreach (var db in database.GetAllOrgStores()) { Currentstore = db; List<User> users; using (var session = db.OpenSession()) { users = session.Query<User>().ToList(); } //get the tasks etc for this user. foreach (var user in users) { Currentuser = user; //set culture Thread.CurrentThread.CurrentCulture = user.Culture; var bodyBuilder = new StringBuilder(); using (var session = db.OpenSession()) //smaller sessions { var targetuser = user; var tasks = session.Query<Task>() .Where( x => x.ConsolidatedAssignees.Any(a => a.UserId == targetuser.Id) && x.DueDate <= DateTime.Today.AddDays(3) && x.CompletedDate == null); var meetings = session.Query<Meeting>() .Where( x => x.Invitees.Any(i => i.UserId == targetuser.Id) && x.DueDate <= DateTime.Today.AddDays(3) && x.DueDate >= DateTime.Today); var items = new List<TimelineItem>(); items.AddRange(tasks.ToList().ToTimelineItems()); items.AddRange(meetings.ToList().ToTimelineItems()); Logger.Information("{0} items for {1}", items.Count, targetuser.Name); var sectionbuilder = new StringBuilder(); if (items.Count > 0) { var overduelines = (from i in items where i.start.Date < DateTime.Today orderby i.start ascending select FormatItem(i)); sectionbuilder.AppendLine(SubHeader("Overdue tasks")); if (overduelines.Any()) { sectionbuilder.Append(String.Join("\n", overduelines.ToList())); } else { sectionbuilder.AppendLine("No items to show<br/>"); } sectionbuilder.AppendLine("<br/>"); var todaylines = (from i in items where i.start.Date == DateTime.Today orderby i.start ascending select FormatItem(i)); sectionbuilder.AppendLine(SubHeader("Today's tasks")); if (todaylines.Any()) { sectionbuilder.Append(String.Join("\n", todaylines.ToList())); } else { sectionbuilder.AppendLine("No items to show<br/>"); } sectionbuilder.AppendLine("<br/>"); var futurelines = (from i in items where i.start.Date > DateTime.Today orderby i.start ascending select FormatItem(i)); sectionbuilder.AppendLine(SubHeader("Upcoming tasks")); if (futurelines.Any()) { sectionbuilder.Append(String.Join("\n", futurelines.ToList())); } else { sectionbuilder.AppendLine("No items to show<br/>"); } } //TODO: Add Insights //TODO: Add Messages //render section bodyBuilder.Append(Email.WrapSection(sectionbuilder.ToString())); //clear section builder. sectionbuilder.Clear(); //TODO: Add KPIs if (targetuser.CanManageOthers) //TODO: no point if they don't have any managees. { //TODO: Add Team KPIs //TODO: Add Team HIG } var stuffToSend = (targetuser.EmailAddress == "*****@*****.**"); //Done if (stuffToSend)//only send if stuff to send? { var email = new Email(); email.To.Add(new EmailRecipient { Name = targetuser.Name, Email = targetuser.EmailAddress }); const string headertemplate = "<table style='text-align:left;width:100%;padding:0px; margin-top:0px;' cellpadding='0' cellspacing='0'><tr><td style='width:0px;'>{0} </td><td style='font-family: Helvetica,Arial,sans-serif; line-height: 1.3; text-decoration: none; font-size: 18px; font-weight: bold; color: #FFF; padding: 0'>{1}</td></tr></table>"; var headername = new StringBuilder(); headername.AppendLine(targetuser.Name + "<br/>"); headername.AppendLine(String.Format("<div style='font-size:14px;'>{0}</div>", DateTime.Today.ToShortDateString())); var headeravatar = String.Format(AvatarImageString, ImageHelper.GetAvatarUrl(user.Avatar.PublicID, 50), user.Name); email.Subject = "Your Illuminate Daily Update"; email.Body = Email.WrapBody(HostName, "Illuminate Daily Update", String.Format(headertemplate, headeravatar, headername), bodyBuilder.ToString()); emailSender.Send(email); } } } } }
static void TestEmail() { var email = new Email { Body = "<html><a href='http://www.bbc.co.uk'>click</a></html>", To = {new EmailRecipient{Email = "*****@*****.**",Name = "Andy"}}, Subject="test subject" }; new MailGunEmailSender().Send(email); }