Ejemplo n.º 1
0
        public string BodyGenerate(EmailType emailType, string callbackUrl)
        {
            string mailBody = string.Empty;

            if (emailType.ToString() == EmailType.Account.ToString())
            {
                mailBody = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath("~/Content/AccountTemplate.html"));
            }
            else if (emailType.ToString() == EmailType.ChangePassword.ToString())
            {
                mailBody = System.IO.File.ReadAllText(System.Web.HttpContext.Current.Server.MapPath("~/Content/ChangePasswordTemplate.html"));
            }
            mailBody = mailBody.Replace("{{callbackUrl}}", callbackUrl);
            return(mailBody);
        }
Ejemplo n.º 2
0
        private Format(User user, EmailType type, Object layoutType)
        {
            var config   = user.Config;
            var language = config.Language;
            var theme    = config.Theme;
            var misc     = user.Control.Misc;

            var layoutName = layoutType.ToString();
            var replaces   = getReplaces(type.ToString(), layoutName, language);

            replaces.Add("MiscColor", misc.Color);
            replaces.Add("MiscAntenna", misc.Antenna);
            replaces.Add("MiscEye", misc.Eye);
            replaces.Add("MiscArm", misc.Arm);
            replaces.Add("MiscLeg", misc.Leg);

            var background = misc.Color.Replace("0", "6").Replace("1", "3");

            replaces.Add("MiscBackground", background);

            var border = misc.Color.Replace("1", "F");

            replaces.Add("MiscBorder", border);

            Subject = replaces["Subject"];
            Layout  = FormatEmail(theme, type, replaces, misc);
        }
Ejemplo n.º 3
0
        private Task <IRestResponse> SendMailAsync(EmailType emailType, String from, String to, String subject, String message)
        {
            RestClient client = new RestClient
            {
                BaseUrl       = new Uri("https://api.mailgun.net/v3"),
                Authenticator = new HttpBasicAuthenticator("api", Environment.GetEnvironmentVariable("MAILGUN"))
            };
            RestRequest request = new RestRequest();

            request.AddParameter("domain", "coupon.osoeasypromo.com", ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", from);
            request.AddParameter("to", to);
            request.AddParameter("subject", subject);
            request.AddParameter("text", message);
            request.AddParameter("o:tag", emailType.ToString());


            //Can only send a maxinum of 3 days in the future...
            //https://tools.ietf.org/html/rfc2822.html#section-3.3
            // request.AddParameter ("o:deliverytime", "Fri, 14 Oct 2011 23:10:10 -0000");

            request.Method = Method.POST;
            return(client.ExecutePostTaskAsync(request));
        }
Ejemplo n.º 4
0
        private EmailTemplate GetEmailFromStandardFile(EmailType type, Language lang)
        {
            var           emailTemplates = JsonConvert.DeserializeObject <List <EmailTemplate> >(File.ReadAllText(HostingEnvironment.MapPath("~/App_Data/emailtemplates.json")));
            EmailTemplate template       = emailTemplates.Where(a => a.Type == type.ToString() && a.Lang == lang.ToString()).FirstOrDefault();

            template.Body = File.ReadAllText(HostingEnvironment.MapPath(template.BodyUrl));
            return(template);
        }
Ejemplo n.º 5
0
        public virtual MvcMailMessage Message(IMailModel model, EmailType type)
        {
            ViewData.Model = model;

            return(Populate(x =>
            {
                x.BodyEncoding = Encoding.UTF8;
                x.IsBodyHtml = true;
                x.Subject = model.Subject;
                x.ViewName = type.ToString();
                x.To.Add(model.ReceiverEmail);
            }));
        }
Ejemplo n.º 6
0
        public virtual MvcMailMessage Message(IMailModel model, EmailType type)
        {
            ViewData.Model = model;

            return Populate(x =>
            {
                x.BodyEncoding = Encoding.UTF8;
                x.IsBodyHtml = true;
                x.Subject = model.Subject;
                x.ViewName = type.ToString();
                x.To.Add(model.ReceiverEmail);
            });
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserEmailEntity"/> class.
        /// </summary>
        /// <param name="userId">
        /// The user id.
        /// </param>
        /// <param name="locationId">
        /// The location Id.
        /// </param>
        /// <param name="emailDate">
        /// The email date.
        /// </param>
        /// <param name="emailType">The type of email</param>
        public UserEmailEntity(Guid userId, string locationId, DateTime emailDate, EmailType emailType)
        {
            PartitionKey = userId.ToString();
            var inverseTimeKey = DateTime
                                 .MaxValue
                                 .Subtract(emailDate)
                                 .TotalMilliseconds.ToString(CultureInfo.InvariantCulture);

            RowKey     = string.Format("{0}-{1}", inverseTimeKey, Guid.NewGuid());
            EmailDate  = emailDate;
            LocationId = locationId;
            EmailType  = emailType.ToString();
        }
Ejemplo n.º 8
0
        void IEmailService.SendTemplatedEmail(EmailType emailType, string emailAddress, IDictionary replacements, string subject)
        {
            if (string.IsNullOrEmpty(emailAddress))
            {
                throw new ArgumentNullException("receipient Email-address");
            }

            EmailType = emailType;

            SendTemplatedEmail(
                emailAddress, IposConfig.AutomatedFromEmail,
                subject ?? EmailType.ToString()
                , IposConfig.AppName, replacements
                );
        }
Ejemplo n.º 9
0
        public static void Seed(string vFirstName, string vLastName, string vEmailAddress, EmailType vEmailType)
        {
            DatabaseContext context = new DatabaseContext();


            List <Contact> contacts = new List <Contact> {
                new Contact {
                    FirstName = vFirstName, LastName = vLastName
                }
            };

            contacts.ForEach(c => context.Contacts.Add(c));

            List <EmailAddresses> emailAddresses = new List <EmailAddresses> {
                new EmailAddresses {
                    Email = vEmailAddress, EmailType = vEmailType.ToString()
                }
            };

            emailAddresses.ForEach(e => context.EmailAddresses.Add(e));

            context.SaveChanges();
        }
Ejemplo n.º 10
0
        public static string Value(this EmailType val)
        {
            var attributes = (DescriptionAttribute[])val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);

            return(attributes.Length > 0 ? attributes[0].Description : string.Empty);
        }
Ejemplo n.º 11
0
        private EmailTemplate GetRandomEmailTemplateForType(EmailType Type)
        {
            // Get all templates by type
            List <EmailTemplate> templates = (from t in LangResources.CurLang.EmailTemplates
                                              where t.Type == Type
                                              select t).ToList();
            int count = templates.Count();

            // return a random one from the list, or just the one in the list if only one
            if (count == 0)
            {
                throw new Exception(String.Format("No emails available for type {0}", Type.ToString()));
            }
            else if (count == 1)
            {
                return(templates[0]);
            }
            else
            {
                Maths u = new Maths();
                int   r = u.RandomInclusive(0, count - 1);
                return(templates[r]);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Sends an email notification out for the workflow process
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="emailType">the type of email to be sent</param>
        /// <param name="errorDetail"></param>
        public async Task <string> Send(WorkflowInstancePoco instance, EmailType emailType, string errorDetail = "")
        {
            var msg = new MailMessage();

            if (!_settings.SendNotifications)
            {
                return(null);
            }

            if (!instance.TaskInstances.Any())
            {
                instance.TaskInstances = _tasksService.GetTasksWithGroupByInstanceGuid(instance.Guid);
            }

            if (!instance.TaskInstances.Any())
            {
                Log.Error($"Notifications not sent - no tasks exist for instance { instance.Id }");
                return(null);
            }

            try
            {
                WorkflowTaskPoco[] flowTasks = instance.TaskInstances.OrderBy(t => t.ApprovalStep).ToArray();

                // always take get the emails for all previous users, sometimes they will be discarded later
                // easier to just grab em all, rather than doing so conditionally
                List <string> emailsForAllTaskUsers = new List <string>();

                // in the loop, also store the last task to a variable, and keep the populated group
                var taskIndex = 0;
                int taskCount = flowTasks.Length;

                foreach (WorkflowTaskPoco task in flowTasks)
                {
                    taskIndex += 1;

                    UserGroupPoco group = await _groupService.GetPopulatedUserGroupAsync(task.GroupId);

                    if (group == null)
                    {
                        continue;
                    }

                    emailsForAllTaskUsers.AddRange(group.PreferredEmailAddresses());
                    if (taskIndex != taskCount)
                    {
                        continue;
                    }

                    _finalTask           = task;
                    _finalTask.UserGroup = group;
                }

                if (_finalTask == null)
                {
                    Log.Error("No valid task found for email notifications");
                    return(null);
                }

                // populate list of recipients
                List <string> to = GetRecipients(emailType, instance, emailsForAllTaskUsers);
                if (!to.Any())
                {
                    return(null);
                }

                string body = GetBody(emailType, instance, out string typeDescription, errorDetail);

                var client = new SmtpClient();

                msg = new MailMessage
                {
                    Subject    = $"{emailType.ToString().ToTitleCase()} - {instance.Node.Name} ({typeDescription})",
                    IsBodyHtml = true,
                    Body       = string.Format(EmailBody, msg.Subject, body)
                };

                if (_settings.Email.HasValue())
                {
                    msg.From = new MailAddress(_settings.Email);
                }

                // if offline is permitted, email group members individually as we need the user id in the url
                if (emailType == EmailType.ApprovalRequest && _finalTask.UserGroup.OfflineApproval)
                {
                    string docTitle = instance.Node.Name;
                    string docUrl   = UrlHelpers.GetFullyQualifiedContentEditorUrl(instance.NodeId);

                    foreach (User2UserGroupPoco user in _finalTask.UserGroup.Users)
                    {
                        var msgBody = body + string.Format(EmailOfflineApprovalString, _settings.SiteUrl, instance.NodeId,
                                                           user.UserId, _finalTask.Id, instance.Guid);

                        msg.Body = string.Format(EmailBody, msg.Subject, msgBody);

                        msg.To.Clear();
                        msg.To.Add(user.User.Email);

                        client.Send(msg);
                    }
                }
                else
                {
                    msg.To.Add(string.Join(",", to.Distinct()));
                    client.Send(msg);
                }

                Log.Info($"Email notifications sent for task { _finalTask.Id }, to { msg.To }");
            }
            catch (Exception e)
            {
                Log.Error($"Error sending notifications for task { _finalTask.Id }", e);
            }

            return(msg.Body);
        }
        public async Task SendEmail(string communityName, string managerEmail, string invitationId, string?message,
                                    string?clientIp, bool existingUser)
        {
            if (EmailSettings.Type == EmailSettings.EmailTypeDisabled)
            {
                // Email shouldn't be disabled, but if it is, we want to
                // fail this job so it retries
                throw new Exception("Email is disabled, failing job to it will retry");
            }

            var invitation = await Db.Get <Invitation>(invitationId);

            if (invitation == null)
            {
                throw new EmailJobException("No Invitation");
            }
            var member = await Db.Get <Member>(invitation.MemberId);

            if (member == null)
            {
                logger.LogDebug($"Sending email to invitation {invitation.Id} that doesn't have valid member");
                return;
            }
            if (invitation.Email.PlainText == null)
            {
                logger.LogDebug($"Sending email to invitation {invitation.Id} that doesn't have an email address");
                return;
            }

            string emailTo;
            string emailToName;

            if (this.EmailType == EmailConstants.EmailTypes.CommunityInvitation)
            {
                emailTo = invitation.Email.PlainText !;
                string linkId = invitation.Id;

                // Let the front-end know if it's a known email address, and show the sign-in form by default.
                string knownEmail = existingUser ? "signin" : "register";

                Attributes.Add("AcceptLink", this.MakeEmailLink("invite", "accept", linkId, knownEmail).ToString());
                Attributes.Add("RejectLink", this.MakeEmailLink("invite", "reject", linkId, knownEmail).ToString());
                // NOTE for stegru: please make the generated email work properly...and then redirect to the currently-hardcoded "/not-me" link
                // Attributes.Add("ReportLink", this.MakeEmailLink("invite", "report", linkId, knownEmail).ToString());
                Attributes.Add("ReportLink", "https://morphic.org/not-me"); // temporary hard-coded link
                emailToName = member.FullName ?? string.Empty;
            }
            else
            {
                emailTo     = managerEmail;
                emailToName = string.Empty;
                // The manager's copy doesn't contain the links.
            }

            Attributes.Add("EmailType", EmailType.ToString());
            Attributes.Add("ToUserName", emailToName);
            Attributes.Add("ToEmail", emailTo);
            Attributes.Add("FromUserName", EmailSettings.EmailFromFullname);
            Attributes.Add("FromEmail", EmailSettings.EmailFromAddress);
            Attributes.Add("ClientIp", clientIp ?? UnknownClientIp);
            Attributes.Add("Community", communityName);
            Attributes.Add("ManagerEmail", managerEmail);
            Attributes.Add("InviteeEmail", invitation.Email.PlainText !);
            Attributes.Add("Message", message ?? "");
            await SendOneEmail(EmailType, Attributes);
        }
Ejemplo n.º 14
0
        public static string GetSendGridTemplateId(EmailType emailType)
        {
            var s = emailType.ToString();

            return(ConfigurationManager.AppSettings[emailType.ToString()]);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Get CourseMate email tamplate.
        /// </summary>
        /// <param name="type">Enumartion of all avalible email tamplate.</param>
        /// <returns>HTML email template.</returns>
        private static string GetEmailTamplateByType(EmailType type)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                string path = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
                doc.Load(path + @"\EmailsTemplate.xml");
                string mainTemplate = doc.GetElementsByTagName("MainTemplate")[0].InnerText;
                string content = doc.GetElementsByTagName(type.ToString())[0].InnerText;

                return string.Format(mainTemplate, content);
            }
            catch (Exception)
            {

            }
            return string.Empty;
        }
Ejemplo n.º 16
0
        public static void Send(User toUser, IRepository repository, EmailType emailType, IDictionary <string, string> emailProperties = null)
        {
            try
            {
                var fromEmail          = repository.GetSettings(SettingsKey.EmailSettings_EmailFrom);
                var adminEmail         = repository.GetSettings(SettingsKey.EmailSettings_EmailAdmin);
                var smtpServer         = repository.GetSettings(SettingsKey.EmailSettings_SmtpServer);
                var smtpServerPort     = repository.GetSettings(SettingsKey.EmailSettings_SmtpServerPort);
                var smtpServerLogin    = repository.GetSettings(SettingsKey.EmailSettings_SmtpServerLogin);
                var smtpServerPassword = repository.GetSettings(SettingsKey.EmailSettings_SmtpServerPassword);
                var enableSSL          = repository.GetSettings(SettingsKey.EmailSettings_EnableSSL) == "true";

                if (!string.IsNullOrWhiteSpace(fromEmail) && !string.IsNullOrWhiteSpace(smtpServer) && !string.IsNullOrWhiteSpace(adminEmail))
                {
                    var         emailTypeString = emailType.ToString();
                    SettingsKey emailSubjectKey, emailBodyKey;
                    string      emailSubject, emailBody;

                    if (Enum.TryParse <SettingsKey>(emailTypeString + "Subject", out emailSubjectKey) &&
                        !string.IsNullOrWhiteSpace(emailSubject = repository.GetSettings(emailSubjectKey)) &&
                        Enum.TryParse <SettingsKey>(emailTypeString + "Body", out emailBodyKey) &&
                        !string.IsNullOrWhiteSpace(emailBody = repository.GetSettings(emailBodyKey)))
                    {
                        foreach (var replacement in emailReplacements)
                        {
                            var value = replacement.Value(toUser);
                            emailSubject = emailSubject.Replace(replacement.Key, value);
                            emailBody    = emailBody.Replace(replacement.Key, value);
                        }

                        if (emailProperties != null)
                        {
                            foreach (var property in emailProperties)
                            {
                                emailSubject = emailSubject.Replace(property.Key, property.Value);
                                emailBody    = emailBody.Replace(property.Key, property.Value);
                            }
                        }

                        string to = isAdminEmail.Contains(emailType)
                            ? adminEmail
                            : toUser.Email;

                        if (string.IsNullOrWhiteSpace(to))
                        {
                            repository.LogError("[code] email address of the recipient is null or empty.", DateTime.Now, null, null, null, null, null);
                            return;
                        }

                        Send(
                            to,
                            fromEmail,
                            smtpServer,
                            int.Parse(smtpServerPort),
                            smtpServerLogin,
                            smtpServerPassword,
                            emailSubject,
                            emailBody,
                            enableSSL);
                    }
                }
            }
            catch (Exception exception)
            {
                repository.LogError(exception, DateTime.Now, "[code] EmailManager.Send", null, null, null, null);
            }
        }
        private async Task <string> GetEmailContent(EmailType emailType)
        {
            string emailName = Regex.Replace(emailType.ToString(), "[A-Z]", " $0").Trim();

            return(await context.Emails.Where(x => x.Name == emailName).Select(x => x.Content).SingleOrDefaultAsync());
        }
Ejemplo n.º 18
0
        public Result SendEmail(string from, IEnumerable <string> tos, EmailType type, object model, IEnumerable <Attachment> attachments = null)
        {
            EmailEntity entity = new EmailEntity();

            try
            {
                var message = new MailMessage()
                {
                    From       = new MailAddress(ConfigurationManager.AppSettings["configuration.email.from"], ConfigurationManager.AppSettings["configuration.email.fromName"] ?? ConfigurationManager.AppSettings["configuration.email.from"]),
                    IsBodyHtml = true,
                };

                foreach (var to in tos)
                {
                    message.To.Add(to);
                }

                if (attachments != null)
                {
                    foreach (var attachment in attachments)
                    {
                        message.Attachments.Add(attachment);
                    }
                }

                var con   = new DapperConnectionManager();
                var query = new QueryEntity();

                query.Query  = @"SELECT * FROM Emails
                            where Type = @Type";
                query.Entity = new { Type = type.ToString() };

                var result = con.ExecuteQuery <EmailEntity>(query);

                if (!result.Success)
                {
                    return(result);
                }

                entity = ((IEnumerable <EmailEntity>)result.Entity).FirstOrDefault();



                dynamic renderModel = new ExpandoObject();

                AddProperty(renderModel, "SiteUrl", ConfigurationManager.AppSettings["mnf.website"] ?? System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority));
                AddProperty(renderModel, "AssetUrl", string.Join("/", ConfigurationManager.AppSettings["mnf.content"] ?? System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority), "assets"));

                AddProperty(renderModel, "EmailType", entity.Type);

                AddProperty(renderModel, "EmailTo", string.Join(";", tos.FirstOrDefault()));
                AddProperty(renderModel, "EmailFrom", message.From);

                var currentUserToken = System.Web.HttpContext.Current?.Request?.Cookies?["MNFCMS"]?.Value ?? System.Web.HttpContext.Current?.Request?.Headers?["Authorization"] ?? string.Empty;

                var credentialsManager = new CredentialsManager();
                var currentUserResult  = credentialsManager.ValidateUserToken(currentUserToken);
                if (!currentUserResult.Success)
                {
                    currentUserResult = credentialsManager.ValidateAdminToken(currentUserToken);
                }

                if (currentUserResult.Success)
                {
                    AddProperty(renderModel, "UserId", (currentUserResult.Entity as UserEntity)?.UserId ?? (currentUserResult.Entity as AdministratorEntity)?.AdministratorId);
                    AddProperty(renderModel, "UserName", (currentUserResult.Entity as UserEntity)?.Name ?? (currentUserResult.Entity as AdministratorEntity)?.Name ?? (currentUserResult.Entity as AdministratorEntity)?.Username);
                    AddProperty(renderModel, "UserEmail", (currentUserResult.Entity as UserEntity)?.Email);
                }


                foreach (var prop in model.GetType().GetProperties())
                {
                    AddProperty(renderModel, prop.Name, prop.GetValue(model));
                }

                var renderResult = RenderEmail(entity, renderModel) as Result;

                if (renderResult.Success)
                {
                    message.Body    = renderResult.Message;
                    message.Subject = entity.Title;

                    foreach (var prop in renderModel as IDictionary <string, object> )
                    {
                        message.Subject = message.Subject.Replace($"@Model.{prop.Key}", prop.Value?.ToString());
                    }

                    MailClient.Send(message);
                }
                else
                {
                    //renderResult.Message += " ||| UserId: " + renderModel["UserId"] + " ||| UserName: "******"UserName"] + "  ||| UserEmail: " + renderModel["UserEmail"] ;

                    foreach (var prop in renderModel as IDictionary <string, object> )
                    {
                        renderResult.Message += " ||| " + prop.Key + prop.Value?.ToString();
                    }

                    return(renderResult);
                }
            }
            catch (Exception e)
            {
                Logger.Log(e);
                var res = new Result();
                res.Entity  = e;
                res.Message = "Failed in SendMail - Email Manager ||| " + e.InnerException + " ||| " + e.StackTrace + " ||| BODY: " + entity.Body + " ||| TITLE: " + entity.Title + " ||| TYPE: " + entity.Type + " ||| EMAILID: " + entity.EmailId;
                res.Success = false;
                return(res);
            }

            return(new Result(true));
        }
Ejemplo n.º 19
0
 public static string EmailTypeName(EmailType type)
 {
     return(Utility.PascalCaseToTitleCase(type.ToString()));
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Sends an email notification out for the workflow process
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="emailType">the type of email to be sent</param>
        public async void Send(WorkflowInstancePoco instance, EmailType emailType)
        {
            WorkflowSettingsPoco settings = _settingsService.GetSettings();

            if (!settings.SendNotifications)
            {
                return;
            }

            if (!instance.TaskInstances.Any())
            {
                instance.TaskInstances = _tasksService.GetTasksWithGroupByInstanceGuid(instance.Guid);
            }

            if (!instance.TaskInstances.Any())
            {
                Log.Error($"Notifications not sent - no tasks exist for instance { instance.Id }");
                return;
            }

            WorkflowTaskPoco finalTask = null;

            try
            {
                string docTitle = instance.Node.Name;
                string docUrl   = UrlHelpers.GetFullyQualifiedContentEditorUrl(instance.NodeId);

                WorkflowTaskPoco[] flowTasks = instance.TaskInstances.OrderBy(t => t.ApprovalStep).ToArray();

                // always take get the emails for all previous users, sometimes they will be discarded later
                // easier to just grab em all, rather than doing so conditionally
                List <string> emailsForAllTaskUsers = new List <string>();

                // in the loop, also store the last task to a variable, and keep the populated group
                var taskIndex = 0;
                int taskCount = flowTasks.Length;

                foreach (WorkflowTaskPoco task in flowTasks)
                {
                    taskIndex += 1;

                    UserGroupPoco group = await _groupService.GetPopulatedUserGroupAsync(task.GroupId);

                    if (group == null)
                    {
                        continue;
                    }

                    emailsForAllTaskUsers.AddRange(group.PreferredEmailAddresses());
                    if (taskIndex != taskCount)
                    {
                        continue;
                    }

                    finalTask           = task;
                    finalTask.UserGroup = group;
                }

                if (finalTask == null)
                {
                    Log.Error("No valid task found for email notifications");
                    return;
                }

                List <string> to = new List <string>();

                var    body                = "";
                string typeDescription     = instance.WorkflowType.Description(instance.ScheduledDate);
                string typeDescriptionPast = instance.WorkflowType.DescriptionPastTense(instance.ScheduledDate);

                switch (emailType)
                {
                case EmailType.ApprovalRequest:
                    to   = finalTask.UserGroup.PreferredEmailAddresses();
                    body = string.Format(EmailApprovalRequestString,
                                         to.Count > 1 ? "Umbraco user" : finalTask.UserGroup.Name, docUrl, docTitle, instance.AuthorComment,
                                         instance.AuthorUser.Name, typeDescription, string.Empty);
                    break;

                case EmailType.ApprovalRejection:
                    to = emailsForAllTaskUsers;
                    to.Add(instance.AuthorUser.Email);
                    body = string.Format(EmailRejectedString,
                                         "Umbraco user", docUrl, docTitle, finalTask.Comment,
                                         finalTask.ActionedByUser.Name, typeDescription.ToLower());

                    break;

                case EmailType.ApprovedAndCompleted:
                    to = emailsForAllTaskUsers;
                    to.Add(instance.AuthorUser.Email);

                    //Notify web admins
                    to.Add(settings.Email);

                    if (instance.WorkflowType == WorkflowType.Publish)
                    {
                        IPublishedContent n = _utility.GetPublishedContent(instance.NodeId);
                        docUrl = UrlHelpers.GetFullyQualifiedSiteUrl(n.Url);
                    }

                    body = string.Format(EmailApprovedString,
                                         "Umbraco user", docUrl, docTitle,
                                         typeDescriptionPast.ToLower()) + "<br/>";

                    body += instance.BuildProcessSummary();

                    break;

                case EmailType.ApprovedAndCompletedForScheduler:
                    to = emailsForAllTaskUsers;
                    to.Add(instance.AuthorUser.Email);

                    body = string.Format(EmailApprovedString,
                                         "Umbraco user", docUrl, docTitle,
                                         typeDescriptionPast.ToLower()) + "<br/>";

                    body += instance.BuildProcessSummary();

                    break;

                case EmailType.WorkflowCancelled:
                    to = emailsForAllTaskUsers;

                    // include the initiator email
                    to.Add(instance.AuthorUser.Email);

                    body = string.Format(EmailCancelledString,
                                         "Umbraco user", typeDescription, docUrl, docTitle, finalTask.ActionedByUser.Name, finalTask.Comment);
                    break;

                case EmailType.SchedulerActionCancelled:
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(emailType), emailType, null);
                }

                if (!to.Any())
                {
                    return;
                }

                var client = new SmtpClient();
                var msg    = new MailMessage
                {
                    Subject    = $"{emailType.ToString().ToTitleCase()} - {instance.Node.Name} ({typeDescription})",
                    IsBodyHtml = true,
                };

                if (settings.Email.HasValue())
                {
                    msg.From = new MailAddress(settings.Email);
                }

                // if offline is permitted, email group members individually as we need the user id in the url
                if (emailType == EmailType.ApprovalRequest && finalTask.UserGroup.OfflineApproval)
                {
                    foreach (User2UserGroupPoco user in finalTask.UserGroup.Users)
                    {
                        string offlineString = string.Format(EmailOfflineApprovalString, settings.SiteUrl, instance.NodeId,
                                                             user.UserId, finalTask.Id, instance.Guid);

                        body = string.Format(EmailApprovalRequestString,
                                             user.User.Name, docUrl, docTitle, instance.AuthorComment,
                                             instance.AuthorUser.Name, typeDescription, offlineString);

                        msg.To.Clear();
                        msg.To.Add(user.User.Email);
                        msg.Body = string.Format(EmailBody, msg.Subject, body);

                        client.Send(msg);
                    }
                }
                else
                {
                    msg.To.Add(string.Join(",", to.Distinct()));
                    msg.Body = string.Format(EmailBody, msg.Subject, body);

                    client.Send(msg);
                }

                Log.Info($"Email notifications sent for task { finalTask.Id }, to { msg.To }");
            }
            catch (Exception e)
            {
                Log.Error($"Error sending notifications for task { finalTask.Id }", e);
            }
        }
        public async Task GenerateEmailAsync(string emailAddress, EmailType emailType, params string[] data)
        {
            var subject = "No subject defined for " + emailType.ToString();
            var message = "No message defined for " + emailType.ToString();

            switch (emailType)
            {
            case EmailType.TestEmail:
                subject = "Test email message";
                if (data != null && data.Length > 0)
                {
                    message = $"Test message:{Environment.NewLine}{data[0]}";
                }
                break;

            case EmailType.EmailVerification:
                subject = "Please verify your email address";
                if (data != null && data.Length > 0)
                {
                    message = $@"
<html><body>
<p>Hello,
<br/></p>
<p>
Thank you for registering your email address with {_webSiteOptions.WebSiteTitle}!
<br/></p>
<p></br></p>
<p>
In order to complete the sign-up process, please click on the following link to confirm your email address, or
copy-and-paste it into your web browser:<br/>
<br/>
<a href='{data[0]}'>{data[0]}</a><br/>
<br/>
This link will be valid for a limited time.  If you do not verify your email address before the link expires, you
will need to sign up again.  If you have any questions or concerns, feel free to contact us at
{_webSiteOptions.SiteUrl}/contact.
<br/></p>
<p></br></p>
<p>
Thank you,<br/>
<br/>
JamesQMurphy<br/>
</p>
</body></html>
";
                }
                break;

            case EmailType.EmailAlreadyRegistered:
                subject = "Somebody tried to sign up with your email address";
                message = $@"
<html><body>
<p>Hello,
<br/></p>
<p>
We thought you should know that somebody tried to sign up at {_webSiteOptions.WebSiteTitle} using your email address.
If this was you, then you may have forgotten that you are already registered on {_webSiteOptions.WebSiteTitle} with this
email address.  You can sign in with your email address and password here:

{_webSiteOptions.SiteUrl}/account/{nameof(JamesQMurphy.Web.Controllers.accountController.forgotpassword)}

There is also a link on that page to reset your password.

If you think it is somebody else, don't worry... that person cannot use your email address.  If you have any questions or
concerns, feel free to contact us at {_webSiteOptions.SiteUrl}/contact.
<br/></p>
<p></br></p>
<p>
Thank you,<br/>
<br/>
JamesQMurphy<br/>
</p>
</body></html>
";
                break;

            case EmailType.PasswordReset:
                subject = "Reset Your Password";
                if (data != null && data.Length > 0)
                {
                    message = $@"
<html><body>
<p>Hello,<br/>
<br/></p>
<p></br></p>
<p>
Somebody (hopefully you!) requested to reset your password on {_webSiteOptions.WebSiteTitle}, and we want to
make sure it was really you.  To reset your password, click this link (or copy/paste it into your
browser) to be taken to the website, where you will be able to enter a new password:</br>
<br/>
<a href='{data[0]}'>{data[0]}</a><br/>
<br/>
If this wasn't you, or you've changed your mind, don't worry... we haven't done anything yet.  You 
can safely delete this message and nothing will happen.  If you have any questions or
concerns, feel free to contact us at our <a href='{_webSiteOptions.SiteUrl}/contact'>Get In Touch</a> page.
<br/></p>
<p></br></p>
<p>
Thank you,<br/>
<br/>
JamesQMurphy<br/>
</p>
</body></html>
";
                }
                break;

            case EmailType.PasswordChanged:
                subject = $"Password changed on {_webSiteOptions.WebSiteTitle}";
                message = $@"
<html><body>
<p>Hello,
<br/></p>
<p>
We are just letting you know that your password has been successfully changed on {_webSiteOptions.WebSiteTitle}.  If
this was you, then there's nothing to worry about.  But if you think that somebody else has changed
your password, please contact us immediately at our <a href='{_webSiteOptions.SiteUrl}/contact'>Get In Touch</a> page.
<br/></p>
<p></br></p>
<p>
Thank you,<br/>
<br/>
JamesQMurphy<br/>
</p>
</body></html>
";
                break;


            case EmailType.Comments:
                subject = $"Comments from {_webSiteOptions.WebSiteTitle} Contact Page";
                message = $@"
Somebody has sent a comment from the {_webSiteOptions.WebSiteTitle} Contact Page:

Username: {(string.IsNullOrWhiteSpace(data[0]) ? "(not logged in)" : data[0])}
Comments:
{data[1]}
";
                break;
            }

            _ = await _emailService.SendEmailAsync(new EmailMessage {
                EmailAddress = emailAddress,
                Subject      = subject,
                Body         = message
            });
        }
Ejemplo n.º 22
0
 private static string GetTemplateFromFile(EmailType emailType)
 {
     return(File.ReadAllText($"{Directory.GetCurrentDirectory()}\\Seed\\{emailType.ToString()}.html"));
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Removes an <see cref="Email"/> object instance. More than one instance can be defined for this object because it is a repeatable field element.
 /// </summary>
 /// <param name="Type">Identifies the Email object to remove by its Type value</param>
 /// <remarks>
 /// <para>Version: 1.5r1</para>
 /// <para>Since: 1.5r1</para>
 /// </remarks>
 public void RemoveEmail(EmailType Type)
 {
     RemoveChild(HrfinDTD.VENDORINFO_EMAIL, new String[] { Type.ToString() });
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Gets an <see cref="Email"/> object instance. More than one instance can be defined for this object because it is a repeatable field element.
 /// </summary>
 /// <param name="Type">Identifies the Email object to return by its "Type" attribute value</param>
 /// <returns>An Email object</returns>
 /// <remarks>
 /// <para>Version: 1.5r1</para>
 /// <para>Since: 1.5r1</para>
 /// </remarks>
 public Email GetEmail(EmailType Type)
 {
     return((Email)GetChild(HrfinDTD.VENDORINFO_EMAIL, new string[] { Type.ToString() }));
 }
Ejemplo n.º 25
0
        public static bool SendEmail(EmailType emailType, Issue issue, List<IssueDistributionUser> newlyAddedDistributionUsers = null)
        {
            log.Info("Called SendEmailNotification() with  emailType = {0}, issue = {1}", emailType.ToString(), issue.Id);

            if (emailType == EmailType.EMPTY)
            {
                //throw new ArgumentException(");
                log.Info("emailType == EmailType.EMPTY");
                return false;
            }

            string settingValue = Util.GetAppSettingValue(Common.AppSettingKey.EmailSendEnabled);

            //Sends email only if its enable in web.config
            if (settingValue.ToLower() != "true")
            {
                log.Info("WebConfig setting 'SendEmailEnabled' is set to False.  Exiting SendEmail() method.");
                return false;
            }

            StringBuilder body = new StringBuilder();
            string filePath = GetMailDefinitionFilePath("IssueMailMessageDefinition.html"); //TODO - shift to appsetting?

            if (!File.Exists(filePath))
            {
                log.Error("Could not find html file for email named '{0}'.", filePath);
                throw new FileNotFoundException(string.Format("Could not find html file for email named '{0}'.", filePath));
            }

            using (StreamReader sr = new StreamReader(filePath))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    body.Append(line);
                }
            }

            MailDefinition md = new MailDefinition();

            //TEMPLATE
            ListDictionary replacements = BuildReplacements(issue);

            MailMessage message;
            string defaultEmailAddress = Util.GetAppSettingValue(Common.AppSettingKey.EmailAdminAccount);

            //TO
            if (IsValidEmailaddress(issue.CurrentlyAssignedToUser.EmailAddress))
            {
                message = md.CreateMailMessage(issue.CurrentlyAssignedToUser.EmailAddress, replacements, body.ToString(), new Control());
            }
            else
            {
                message = md.CreateMailMessage(defaultEmailAddress, replacements, body.ToString(), new Control());
                message.From = new MailAddress(defaultEmailAddress);
            }

            //FROM
            message.From = new MailAddress(defaultEmailAddress);

            message.IsBodyHtml = true;

            //SUBJECT
            message.Subject = BuildEmailSubject(emailType, issue);

            //CC
            if (newlyAddedDistributionUsers != null && newlyAddedDistributionUsers.Count > 0)
            {
                BuildCcUsers(message, newlyAddedDistributionUsers);
            }
            else
            {
                BuildCcUsers(issue, message);
            }

            SmtpClient client = new SmtpClient();

            client.Host = Util.GetAppSettingValue(Common.AppSettingKey.EmailMailHost);

            try
            {
                //SEND!
                string testEmail = Util.GetAppSettingValue(Common.AppSettingKey.EmailDefaultTest);

                if (IsValidEmailaddress(testEmail))
                {
                    InterceptEmail(message, testEmail);
                }

                log.Info("Sending email.{0}From = {1}{0}To = {2}{0}Cc = {3}{0}Host = {4}.",
                         Environment.NewLine, message.From, message.To, message.CC, client.Host);

                log.Verbose("Email body: {0}", message.Body);

                client.Send(message);
            }
            catch (Exception exception)
            {
                log.Error(exception.Message, exception, "Possible relay error");
                if (exception.InnerException != null)
                {
                    log.Error(exception.InnerException.Message, exception.InnerException, "Possible relay error inner exception.");
                }
            }

            return true;
        }