Example #1
0
        private async Task SendMailAsync(MailListSubscription reg, string fullTemplateName)
        {
            MailboxAddress fromAddress = new MailboxAddress(reg.MailList.FromEmailName, reg.MailList.FromEmailAddress);

            MailboxAddress[] toAddresses = new MailboxAddress[] { MailboxAddress.Parse(reg.EmailAddress) };
            MimeMessage      message     = await mailCreator.CreateMailAsync(fullTemplateName, reg, GetViewBagForTemplate(), null);

            await mailSender.SendMailAsync(GetMessages(reg, message, fromAddress, toAddresses), false);
        }
Example #2
0
 private IEnumerable <MailToSend> GetMessages(MailListSubscription sub, MimeMessage message, MailboxAddress fromAddress, IEnumerable <MailboxAddress> toAddresses)
 {
     foreach (MailboxAddress toAddress in toAddresses)
     {
         message.From.Clear();
         message.To.Clear();
         message.From.Add(fromAddress);
         message.To.Add(toAddress);
         yield return(new MailToSend {
             Subscription = sub, Message = message
         });
     }
 }
Example #3
0
        /// <summary>
        /// Unsubscribe from a mailing list
        /// </summary>
        /// <param name="db">DB</param>
        /// <param name="listName">List name</param>
        /// <param name="token">Unsubscribe token</param>
        /// <returns>True if unsubscribed, false if not</returns>
        public static bool UnsubscribeFromMailingList(this MailDemonDatabase db, string listName, string token)
        {
            MailListSubscription foundReg = db.Subscriptions.FirstOrDefault(r => r.UnsubscribeToken == token && r.ListName == listName && r.UnsubscribedDate == default);

            if (foundReg != null)
            {
                foundReg.UnsubscribedDate = DateTime.UtcNow;
                foundReg.SubscribeToken   = null;
                db.SaveChanges();
                return(true);
            }
            ;
            return(false);
        }
Example #4
0
 public IActionResult Subscribers(string id, string action, long?subId)
 {
     if (action == "delete" && subId != null)
     {
         using MailDemonDatabase db = dbProvider.GetDatabase();
         MailListSubscription sub = db.Subscriptions.FirstOrDefault(s => s.Id == subId);
         if (sub != null)
         {
             db.Subscriptions.Remove(sub);
             db.SaveChanges();
         }
     }
     return(RedirectToAction(nameof(Subscribers), new { id }));
 }
Example #5
0
        public async Task <IActionResult> DebugTemplate(string id)
        {
            if (HttpContext.Request.Method == "POST")
            {
                // switch to GET request, to avoid stupid double form post popup
                return(RedirectToAction(nameof(DebugTemplate), new { id }));
            }

            id = (id ?? string.Empty).Trim();
            if (id.Length == 0)
            {
                return(NotFound());
            }
            string   listName = MailTemplate.GetListName(id);
            MailList list;

            using (MailDemonDatabase db = dbProvider.GetDatabase())
            {
                list = db.Lists.FirstOrDefault(l => l.Name == listName);
            }
            if (list == null)
            {
                return(NotFound());
            }

            string unsubscribeToken      = Guid.NewGuid().ToString("N");
            MailListSubscription tempReg = new MailListSubscription
            {
                EmailAddress     = "*****@*****.**",
                IPAddress        = HttpContext.GetRemoteIPAddress().ToString(),
                FirstName        = "Bob",
                LastName         = "Smith",
                Company          = "Fake Company",
                ListName         = list.Name,
                SubscribedDate   = DateTime.UtcNow,
                SubscribeToken   = Guid.NewGuid().ToString("N"),
                Expires          = DateTime.MinValue,
                MailList         = list,
                UnsubscribeToken = unsubscribeToken,
                UnsubscribeUrl   = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}/{nameof(Unsubscribe)}/{list.Name}?token={unsubscribeToken}"
            };
            MimeMessage msg = await mailCreator.CreateMailAsync(id, tempReg, GetViewBagForTemplate(), (_html, subject) =>
            {
                return(_html.Replace("<body>", "<body><div style='padding: 10px; width: 100%; background-color: #2A2A2A; border-bottom: 1px solid #444444;'>SUBJECT: " + System.Web.HttpUtility.HtmlEncode(subject) + "</div>"));
            });

            string html = msg.HtmlBody;

            return(Content(msg.HtmlBody, "text/html"));
        }
Example #6
0
        private IReadOnlyCollection <MailToSend> GetMessages(MailListSubscription sub, MimeMessage message,
                                                             MailboxAddress fromAddress, IEnumerable <MailboxAddress> toAddresses)
        {
            List <MailToSend> messages = new List <MailToSend>();

            foreach (MailboxAddress toAddress in toAddresses)
            {
                message.From.Clear();
                message.To.Clear();
                message.From.Add(fromAddress);
                message.To.Add(toAddress);
                messages.Add(new MailToSend {
                    Subscription = sub, Message = message
                });
            }
            return(messages);
        }
Example #7
0
        /// <summary>
        /// Confirm subscribe to a mailing list
        /// </summary>
        /// <param name="db">DB</param>
        /// <param name="listName">List name</param>
        /// <param name="token">Subscribe token</param>
        /// <returns>Registration or null if not found</returns>
        public static MailListSubscription ConfirmSubscribeToMailingList(this MailDemonDatabase db, string listName, string token)
        {
            MailListSubscription reg      = null;
            MailListSubscription foundReg = db.Subscriptions.FirstOrDefault(r => r.SubscribeToken == token);

            if (foundReg != null && foundReg.ListName == listName && foundReg.SubscribedDate == default && foundReg.SubscribeToken == token)
            {
                reg = foundReg;
                foundReg.Expires          = DateTime.MaxValue;
                foundReg.SubscribedDate   = DateTime.UtcNow;
                foundReg.UnsubscribedDate = default;
                foundReg.UnsubscribeToken = Guid.NewGuid().ToString("N");
                foundReg.MailList         = db.Lists.FirstOrDefault(l => l.Name == listName);
                foundReg.Result           = "New";
                db.SaveChanges();
            }
            return(reg);
        }
Example #8
0
        /// <summary>
        /// Pre subscribe to a mailing list
        /// </summary>
        /// <param name="db">DB</param>
        /// <param name="reg">Registration, receives new registration if success</param>
        /// <returns>True if success, false if already subscribed</returns>
        public static bool PreSubscribeToMailingList(this MailDemonDatabase db, ref MailListSubscription reg)
        {
            bool   result = false;
            string token  = string.Empty;
            MailListSubscription final = reg;
            MailListSubscription dbReg = db.Subscriptions.FirstOrDefault(r => r.EmailAddress == final.EmailAddress && r.ListName == final.ListName);

            if (dbReg != null)
            {
                dbReg.Fields.Clear();
                foreach (var kv in final.Fields)
                {
                    dbReg.SetField(kv.Key, kv.Value);
                }
                dbReg.Error        = final.Error;
                dbReg.Message      = final.Message;
                dbReg.IPAddress    = final.IPAddress;
                dbReg.MailList     = final.MailList;
                dbReg.TemplateName = final.TemplateName;
                final = dbReg;
            }
            reg = final;
            if (reg.SubscribeToken == null)
            {
                reg.SubscribeToken = Guid.NewGuid().ToString("N");
                reg.Expires        = DateTime.UtcNow.AddHours(1.0);
                if (reg.Id == 0)
                {
                    db.Subscriptions.Add(reg);
                }
                else
                {
                    db.Update(reg);
                }
                result = true;
            }
            db.SaveChanges();
            return(result);
        }
Example #9
0
        public IActionResult SubscribeInitial(string id)
        {
            string result = TempData["result"] as string;

            id = (id ?? string.Empty).Trim();
            if (id.Length == 0)
            {
                return(NotFound());
            }
            MailListSubscription model = (string.IsNullOrWhiteSpace(result) ? new MailListSubscription() : JsonConvert.DeserializeObject <MailListSubscription>(result));

            using (MailDemonDatabase db = dbProvider.GetDatabase())
            {
                model.MailList = db.Lists.FirstOrDefault(l => l.Name == id);
            }
            if (model.MailList == null)
            {
                return(NotFound());
            }
            model.ListName     = id;
            model.TemplateName = MailTemplate.GetFullTemplateName(id, MailTemplate.NameSubscribeInitial);
            return(View(model));
        }
Example #10
0
        public async Task <IActionResult> SubscribeInitialPost(string id, Dictionary <string, string> formFields)
        {
            id = (id ?? string.Empty).Trim();
            if (id.Length == 0)
            {
                return(NotFound());
            }
            string error = null;

            if (RequireCaptcha)
            {
                formFields.TryGetValue("captcha", out string captchaValue);
                error = await MailDemonWebApp.Instance.Recaptcha.Verify(Request.GetDisplayUrl(), captchaValue, nameof(SubscribeInitial), HttpContext.GetRemoteIPAddress().ToString(), formFields);
            }
            MailListSubscription model = new MailListSubscription {
                Message = error, Error = !string.IsNullOrWhiteSpace(error)
            };
            MailList list;

            using (MailDemonDatabase db = dbProvider.GetDatabase())
            {
                list = db.Lists.FirstOrDefault(l => l.Name == id);
            }
            if (list == null)
            {
                return(NotFound());
            }
            model.MailList = list;
            model.ListName = model.MailList.Name;
            if (formFields.ContainsKey("TemplateName"))
            {
                model.TemplateName = formFields["TemplateName"];
            }
            string email = null;

            foreach (KeyValuePair <string, string> field in formFields)
            {
                if (field.Key.StartsWith("ff_"))
                {
                    string value = field.Value?.Trim();
                    string name  = field.Key.Split('_')[1];
                    if (string.IsNullOrWhiteSpace(value))
                    {
                        if (field.Key.EndsWith("_optional", StringComparison.OrdinalIgnoreCase))
                        {
                            model.Fields[name] = string.Empty;
                        }
                        else
                        {
                            model.Message += "<br/>" + field.Key.Split('_')[1] + " is required";
                            model.Error    = true;
                        }
                    }
                    else if (name.Contains("email", StringComparison.OrdinalIgnoreCase))
                    {
                        if (value.TryParseEmailAddress(out _))
                        {
                            email = (email ?? value);
                            model.EmailAddress = email;
                        }
                        else
                        {
                            model.Error = true;
                        }
                    }
                    else
                    {
                        model.Fields[name] = value;
                    }
                }
            }
            model.EmailAddressDomain = model.GetDomainFromEmailAddress();
            TempData["result"]       = JsonConvert.SerializeObject(model);
            if (model.Error || email == null)
            {
                if (email == null)
                {
                    model.Error    = true;
                    model.Message += "<br/>" + Resources.EmailIsInvalid;
                }
                return(View(nameof(SubscribeInitial), model));
            }
            else
            {
                try
                {
                    model.IPAddress = HttpContext.GetRemoteIPAddress().ToString();
                    using (MailDemonDatabase db = dbProvider.GetDatabase())
                    {
                        if (!db.PreSubscribeToMailingList(ref model))
                        {
                            throw new InvalidOperationException(Resources.AlreadySubscribed.FormatHtml(id));
                        }
                    }
                    string url = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}/{nameof(SubscribeWelcome)}/{id}?token={model.SubscribeToken}";
                    model.SubscribeUrl = url;
                    string templateFullName = MailTemplate.GetFullTemplateName(id, MailTemplate.NameSubscribeConfirm);
                    await SendMailAsync(model, templateFullName);

                    return(RedirectToAction(nameof(SubscribeConfirm), new { id = model.ListName }));
                }
                catch (Exception ex)
                {
                    MailDemonLog.Error(ex);
                    model.Error    = true;
                    model.Message += "<br/>" + ex.Message;
                    return(View(nameof(SubscribeInitial), model));
                }
            }
        }