Esempio n. 1
0
        public void SendCampaign(Campaign campaign, EmailAccount emailAccount, string email)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens, _storeContext.CurrentStore, emailAccount);
            var customer = _customerService.GetCustomerByEmail(email);

            if (customer != null)
            {
                _messageTokenProvider.AddCustomerTokens(tokens, customer);
            }

            string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
            string body    = _tokenizer.Replace(campaign.Body, tokens, true);

            _emailSender.SendEmail(emailAccount, subject, body, emailAccount.Email, emailAccount.DisplayName, email, null);
        }
Esempio n. 2
0
        private IList <Token> GenerateTokens(Customer customer)
        {
            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens);
            _messageTokenProvider.AddCustomerTokens(tokens, customer);
            return(tokens);
        }
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual int SendCampaign(Campaign campaign, EmailAccount emailAccount, IEnumerable <NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            if (subscriptions == null || subscriptions.Count() <= 0)
            {
                return(0);
            }

            int totalEmailsSent = 0;

            var subscriptionData = subscriptions
                                   .Where(x => _storeMappingService.Authorize <Campaign>(campaign, x.StoreId))
                                   .GroupBy(x => x.Email);

            foreach (var group in subscriptionData)
            {
                var subscription = group.First();                       // only one email per email address

                var tokens = new List <Token>();
                _messageTokenProvider.AddStoreTokens(tokens, _storeContext.CurrentStore);
                _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokens, subscription);

                var customer = _customerService.GetCustomerByEmail(subscription.Email);
                if (customer != null)
                {
                    _messageTokenProvider.AddCustomerTokens(tokens, customer);
                }

                string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
                string body    = _tokenizer.Replace(campaign.Body, tokens, true);

                var email = new QueuedEmail()
                {
                    Priority       = 3,
                    From           = emailAccount.Email,
                    FromName       = emailAccount.DisplayName,
                    To             = subscription.Email,
                    Subject        = subject,
                    Body           = body,
                    CreatedOnUtc   = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };

                _queuedEmailService.InsertQueuedEmail(email);
                totalEmailsSent++;
            }
            return(totalEmailsSent);
        }
Esempio n. 4
0
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual int SendCampaign(Campaign campaign, EmailAccount emailAccount,
                                        IEnumerable <NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException(nameof(campaign));
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException(nameof(emailAccount));
            }

            var totalEmailsSent = 0;

            foreach (var subscription in subscriptions)
            {
                var customer = _customerService.GetCustomerByEmail(subscription.Email);
                //ignore deleted or inactive customers when sending newsletter campaigns
                if (customer != null && (!customer.Active || customer.Deleted))
                {
                    continue;
                }

                var tokens = new List <Token>();
                _messageTokenProvider.AddStoreTokens(tokens, _storeContext.CurrentStore, emailAccount);
                _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokens, subscription);
                if (customer != null)
                {
                    _messageTokenProvider.AddCustomerTokens(tokens, customer);
                }

                var subject = _tokenizer.Replace(campaign.Subject, tokens, false);
                var body    = _tokenizer.Replace(campaign.Body, tokens, true);

                var email = new QueuedEmail
                {
                    Priority              = QueuedEmailPriority.Low,
                    From                  = emailAccount.Email,
                    FromName              = emailAccount.DisplayName,
                    To                    = subscription.Email,
                    Subject               = subject,
                    Body                  = body,
                    CreatedOnUtc          = DateTime.UtcNow,
                    EmailAccountId        = emailAccount.Id,
                    DontSendBeforeDateUtc = campaign.DontSendBeforeDateUtc
                };
                _queuedEmailService.InsertQueuedEmail(email);
                totalEmailsSent++;
            }

            return(totalEmailsSent);
        }
        /// <summary>
        /// Sends 'New customer' notification message to a store owner
        /// </summary>
        /// <param name="customer">Customer instance</param>
        /// <param name="languageId">Message language identifier</param>
        /// <returns>Queued email identifier</returns>
        public virtual int SendCustomerAppointmentNotificationMessage(Customer customer, int languageId, IList <Token> tokens)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            var store = _storeContext.CurrentStore;

            var messageTemplate = _messageTemplateService.GetMessageTemplateByName("Appointment.New", store.Id);

            if (messageTemplate == null)
            {
                return(0);
            }

            //email account
            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

            _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);
            _messageTokenProvider.AddCustomerTokens(tokens, customer);


            //event notification
            _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

            var toEmail = emailAccount.Email;
            var toName  = emailAccount.DisplayName;

            return(_workflowMessageService.SendNotification(messageTemplate, emailAccount, languageId, tokens, toEmail, toName));
        }
        /// <summary>
        /// Sends password recovery message to a customer
        /// </summary>
        /// <param name="customer">Customer instance</param>
        /// <param name="languageId">Message language identifier</param>
        /// <returns>Queued email identifier</returns>
        public virtual IList <Guid> SendCustomerPasswordRecoveryMessage(Core.Domain.Customers.Customer customer, Guid languageId, Core.Domain.Stores.Store store)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            languageId = EnsureLanguageIsActive(languageId, store.Id);

            var messageTemplates = GetActiveMessageTemplates(MessageTemplateSystemNames.CustomerPasswordRecoveryMessage, store.Id);

            if (!messageTemplates.Any())
            {
                return(new List <Guid>());
            }

            //tokens
            var commonTokens = new List <Token>();

            _messageTokenProvider.AddCustomerTokens(commonTokens, customer);

            return(messageTemplates.Select(messageTemplate =>
            {
                //email account
                var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

                var tokens = new List <Token>(commonTokens);
                _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);

                var toEmail = customer.Email;
                var toName = _customerService.GetCustomerFullName(customer);

                return SendNotification(messageTemplate, emailAccount, languageId, tokens, toEmail, toName);
            }).ToList());
        }
Esempio n. 7
0
        /// <summary>
        /// Sends a welcome message to a customer
        /// </summary>
        /// <param name="customer">Customer instance</param>
        /// <returns>Queued email identifier</returns>
        public int SendCustomerWelcomeMessage(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            var messageTemplate = GetActiveMessageTemplate("Customer.WelcomeMessage");

            if (messageTemplate == null)
            {
                return(0);
            }

            //email account
            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate);

            //tokens
            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens, emailAccount);
            _messageTokenProvider.AddCustomerTokens(tokens, customer);

            //event notification
            _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

            var toEmail = customer.Email;
            var toName  = customer.UserName; //原来是获取全称

            return(SendNotification(messageTemplate, emailAccount,
                                    tokens,
                                    toEmail, toName));
        }
Esempio n. 8
0
        public int SendCustomerNotice(Order order, string licenseTable, int languageId)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }

            var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore;

            languageId = EnsureLanguageIsActive(languageId, store.Id);

            var messageTemplate = GetLocalizedActiveMessageTemplate("Nop.Misc.Licenses.Customer.SendLicense", languageId, store.Id);

            if (messageTemplate == null)
            {
                return(0);
            }
            //email account
            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

            //tokens
            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);
            _messageTokenProvider.AddOrderTokens(tokens, order, languageId);
            _messageTokenProvider.AddCustomerTokens(tokens, order.Customer);
            tokens.Add(new Token("LicenseTable", licenseTable, true));

            var toEmail = order.BillingAddress.Email;
            var toName  = string.Format("{0} {1}", order.BillingAddress.FirstName, order.BillingAddress.LastName);

            return(SendNotification(messageTemplate, emailAccount,
                                    languageId, tokens,
                                    toEmail, toName));
        }
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual int SendCampaign(Campaign campaign, EmailAccount emailAccount,
                                        IEnumerable <NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            int totalEmailsSent = 0;

            foreach (var subscription in subscriptions)
            {
                var tokens = new List <Token>();
                _messageTokenProvider.AddStoreTokens(tokens);
                _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokens, subscription);
                var customer = _customerService.GetCustomerByEmail(subscription.Email);
                if (customer != null)
                {
                    _messageTokenProvider.AddCustomerTokens(tokens, customer);
                }

                string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
                string body    = _tokenizer.Replace(campaign.Body, tokens, true);

                var email = new QueuedEmail()
                {
                    Priority       = 3,
                    From           = emailAccount.Email,
                    FromName       = emailAccount.DisplayName,
                    To             = subscription.Email,
                    Subject        = subject,
                    Body           = body,
                    CreatedOnUtc   = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };
                _queuedEmailService.InsertQueuedEmail(email);
                totalEmailsSent++;
            }
            return(totalEmailsSent);
        }
Esempio n. 10
0
        private int SetupEmail(ref EmailAccount account, ref MessageTemplate messageTemplate, ref List <Token> tokens, Customer customer)
        {
            var languageId = EnsureLanguageIsActive(0, _store.Id);

            account = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

            _messageTokenProvider.AddStoreTokens(tokens, _store, account);
            _messageTokenProvider.AddCustomerTokens(tokens, customer);

            _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

            return(languageId);
        }
        /// <summary>
        ///     Sends 'New customer' notification message to a store owner
        /// </summary>
        /// <param name="customer">Customer instance</param>
        /// <param name="languageId">Message language identifier</param>
        /// <returns>Queued email identifier</returns>
        public virtual int SendCustomerRegisteredNotificationMessage(Customer customer, int languageId)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            languageId = EnsureLanguageIsActive(languageId);

            var messageTemplate = GetActiveMessageTemplate("NewCustomer.Notification");

            if (messageTemplate == null)
            {
                return(0);
            }

            //email account
            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

            //tokens
            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens, EngineContext.Current.Resolve <StoreInformationSettings>(),
                                                 emailAccount);
            _messageTokenProvider.AddCustomerTokens(tokens, customer);

            //event notification
            _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

            var toEmail = emailAccount.Email;
            var toName  = emailAccount.DisplayName;

            return(SendNotification(messageTemplate, emailAccount,
                                    languageId, tokens,
                                    toEmail, toName));
        }
Esempio n. 12
0
        public virtual int SendShareInfoMessage(Customer customer, int languageId, string customerEmail, string customerName, string friendsEmail, string personalMessage)
        {
            //Check customer
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            //Get Store
            var store = _storeContext.CurrentStore;

            //Get language
            languageId = EnsureLanguageIsActive(languageId, store.Id);

            //Get Template
            var messageTemplate = GetActiveMessageTemplate("Cameleo.ShareInfo", store.Id);

            if (messageTemplate == null)
            {
                return(0);
            }

            //email account
            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

            //tokens
            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);
            _messageTokenProvider.AddCustomerTokens(tokens, customer);
            tokens.Add(new Token("EmailAFriend.FullName", customerName));
            tokens.Add(new Token("EmailAFriend.PersonalMessage", personalMessage, true));
            tokens.Add(new Token("EmailAFriend.Email", customerEmail));

            //event notification
            _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

            //Send message
            var toEmail      = friendsEmail;
            var toName       = "";
            int newMessageId = SendShareInfoNotification(messageTemplate, emailAccount, languageId, tokens, toEmail, toName);

            return(newMessageId);
        }
        /// <summary>
        /// Method to send error notification to store owner
        /// </summary>
        /// <param name="order"></param>
        /// <param name="languageId"></param>
        /// <param name="nopShiprocketOrder"></param>
        /// <returns></returns>
        public virtual int SendOrderShiprocketErrorStoreOwnerNotification(Order order, int languageId, NopShiprocketOrder nopShiprocketOrder)
        {
            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore;

            languageId = EnsureLanguageIsActive(languageId, store.Id);

            var messageTemplates = GetActiveMessageTemplates(MessageTemplateSystemNames.OrderPlacedStoreOwnerNotification, store.Id);

            if (!messageTemplates.Any())
            {
                return(0);
            }

            //email account
            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplates.FirstOrDefault(), languageId);

            //tokens
            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);
            _messageTokenProvider.AddOrderTokens(tokens, order, languageId);
            _messageTokenProvider.AddCustomerTokens(tokens, _customerService.GetCustomerById(order.CustomerId));

            //event notification
            _eventPublisher.MessageTokensAdded(messageTemplates.FirstOrDefault(), tokens);

            var toEmail = emailAccount.Email;
            var toName  = emailAccount.DisplayName;

            return(SendErrorNotification(messageTemplates.FirstOrDefault(), emailAccount, languageId, tokens, toEmail, toName, null, null, null, null, null, null, null, nopShiprocketOrder));
        }
Esempio n. 14
0
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual int SendCampaign(Campaign campaign, EmailAccount emailAccount,
                                        IEnumerable <NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            int totalEmailsSent = 0;

            foreach (var subscription in subscriptions)
            {
                Customer customer = null;

                if (!String.IsNullOrEmpty(subscription.CustomerId))
                {
                    customer = _customerService.GetCustomerById(subscription.CustomerId);
                }

                if (customer == null)
                {
                    customer = _customerService.GetCustomerByEmail(subscription.Email);
                }

                //ignore deleted or inactive customers when sending newsletter campaigns
                if (customer != null && (!customer.Active || customer.Deleted))
                {
                    continue;
                }

                var tokens = new List <Token>();
                _messageTokenProvider.AddStoreTokens(tokens, _storeContext.CurrentStore, emailAccount);
                _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokens, subscription);
                if (customer != null)
                {
                    _messageTokenProvider.AddCustomerTokens(tokens, customer);
                    _messageTokenProvider.AddShoppingCartTokens(tokens, customer);
                    _messageTokenProvider.AddRecommendedProductsTokens(tokens, customer);
                    _messageTokenProvider.AddRecentlyViewedProductsTokens(tokens, customer);
                }

                string subject = _tokenizer.Replace(campaign.Subject, tokens, false);
                string body    = _tokenizer.Replace(campaign.Body, tokens, true);

                var email = new QueuedEmail
                {
                    Priority       = QueuedEmailPriority.Low,
                    From           = emailAccount.Email,
                    FromName       = emailAccount.DisplayName,
                    To             = subscription.Email,
                    Subject        = subject,
                    Body           = body,
                    CreatedOnUtc   = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };
                _queuedEmailService.InsertQueuedEmail(email);
                InsertCampaignHistory(new CampaignHistory()
                {
                    CampaignId = campaign.Id, CustomerId = subscription.CustomerId, Email = subscription.Email, CreatedDateUtc = DateTime.UtcNow, StoreId = campaign.StoreId
                });

                //activity log
                if (customer != null)
                {
                    _customerActivityService.InsertActivity("CustomerReminder.SendCampaign", campaign.Id, _localizationService.GetResource("ActivityLog.SendCampaign"), customer, campaign.Name);
                }
                else
                {
                    _customerActivityService.InsertActivity("CustomerReminder.SendCampaign", campaign.Id, _localizationService.GetResource("ActivityLog.SendCampaign"), campaign.Name + " - " + subscription.Email);
                }

                totalEmailsSent++;
            }
            return(totalEmailsSent);
        }
Esempio n. 15
0
        /// <summary>
        /// Executes a task
        /// </summary>
        public string Execute([FromQuery(Name = "roles")] int[] roles)
        {
            var store = _storeContext.CurrentStore;
            //load language by specified ID
            var languageId = 1;

            //var messageTemplate = _messageTemplateService.GetMessageTemplateByName(MessageTemplateSystemNames.CustomerForceChangePasswordMessage, 0);
            var messageTemplate = _messageTemplateService.GetMessageTemplateById(44);

            //no template found
            if (messageTemplate == null)
            {
                return("messageTemplate is null");
            }

            //ensure it's active
            var isActive = messageTemplate.IsActive;

            if (!isActive)
            {
                return("messageTemplate is not active");
            }


            var emailAccountId = messageTemplate.GetLocalized(mt => mt.EmailAccountId, languageId);

            //some 0 validation (for localizable "Email account" dropdownlist which saves 0 if "Standard" value is chosen)
            if (emailAccountId == 0)
            {
                emailAccountId = messageTemplate.EmailAccountId;
            }

            var emailAccount = _emailAccountService.GetEmailAccountById(emailAccountId);

            if (emailAccount == null)
            {
                emailAccount = _emailAccountService.GetEmailAccountById(_emailAccountSettings.DefaultEmailAccountId);
            }
            if (emailAccount == null)
            {
                emailAccount = _emailAccountService.GetAllEmailAccounts().FirstOrDefault();
            }


            //tokens
            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);

            //var customers = _customerService.GetAllCustomers(customerRoleIds: new int[] { 1, 2, 3 });
            var customers = _customerService.GetAllCustomers(customerRoleIds: roles);

            foreach (var customer in customers)
            {
                _messageTokenProvider.AddCustomerTokens(tokens, customer);

                //event notification
                _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

                var toEmail = customer.Email;
                var toName  = customer.GetFullName();


                if (string.IsNullOrEmpty(toEmail))
                {
                    continue;
                }

                //return SendNotification(messageTemplate, emailAccount, languageId, tokens, toEmail, toName);
                if (messageTemplate == null)
                {
                    throw new ArgumentNullException(nameof(messageTemplate));
                }

                if (emailAccount == null)
                {
                    throw new ArgumentNullException(nameof(emailAccount));
                }

                //retrieve localized message template data
                var bcc = messageTemplate.GetLocalized(mt => mt.BccEmailAddresses, languageId);

                var subject = messageTemplate.GetLocalized(mt => mt.Subject, languageId);
                var body    = messageTemplate.GetLocalized(mt => mt.Body, languageId);

                //Replace subject and body tokens
                var subjectReplaced = _tokenizer.Replace(subject, tokens, false);
                var bodyReplaced    = _tokenizer.Replace(body, tokens, true);

                //limit name length
                toName = CommonHelper.EnsureMaximumLength(toName, 300);

                var email = new QueuedEmail
                {
                    Priority = QueuedEmailPriority.High,
                    From     = emailAccount.Email,
                    FromName = emailAccount.DisplayName,
                    To       = toEmail,
                    ToName   = toName,
                    //ReplyTo = replyToEmailAddress,
                    //ReplyToName = replyToName,
                    CC      = string.Empty,
                    Bcc     = bcc,
                    Subject = subjectReplaced,
                    Body    = bodyReplaced,
                    //AttachmentFilePath = attachmentFilePath,
                    //AttachmentFileName = attachmentFileName,
                    AttachedDownloadId    = messageTemplate.AttachedDownloadId,
                    CreatedOnUtc          = DateTime.UtcNow,
                    EmailAccountId        = emailAccount.Id,
                    DontSendBeforeDateUtc = !messageTemplate.DelayBeforeSend.HasValue ? null
                        : (DateTime?)(DateTime.UtcNow + TimeSpan.FromHours(messageTemplate.DelayPeriod.ToHours(messageTemplate.DelayBeforeSend.Value)))
                };

                _queuedEmailService.InsertQueuedEmail(email);
            }


            return("Mass change Password email process completed");
            //var olderThanMinutes = _customerSettings.DeleteGuestTaskOlderThanMinutes;
            //// Default value in case 0 is returned.  0 would effectively disable this service and harm performance.
            //olderThanMinutes = olderThanMinutes == 0 ? 1440 : olderThanMinutes;

            //_customerService.DeleteGuestCustomers(null, DateTime.UtcNow.AddMinutes(-olderThanMinutes), true);
        }
Esempio n. 16
0
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual async Task <int> SendCampaign(Campaign campaign, EmailAccount emailAccount,
                                                     IEnumerable <NewsLetterSubscription> subscriptions)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            int totalEmailsSent = 0;
            var language        = await _languageService.GetLanguageById(campaign.LanguageId);

            if (language == null)
            {
                language = (await _languageService.GetAllLanguages()).FirstOrDefault();
            }

            foreach (var subscription in subscriptions)
            {
                Customer customer = null;

                if (!String.IsNullOrEmpty(subscription.CustomerId))
                {
                    customer = await _customerService.GetCustomerById(subscription.CustomerId);
                }

                if (customer == null)
                {
                    customer = await _customerService.GetCustomerByEmail(subscription.Email);
                }

                //ignore deleted or inactive customers when sending newsletter campaigns
                if (customer != null && (!customer.Active || customer.Deleted))
                {
                    continue;
                }

                var liquidObject = new LiquidObject();
                var store        = await _storeService.GetStoreById(campaign.StoreId);

                if (store == null)
                {
                    store = (await _storeService.GetAllStores()).FirstOrDefault();
                }

                await _messageTokenProvider.AddStoreTokens(liquidObject, store, language, emailAccount);

                await _messageTokenProvider.AddNewsLetterSubscriptionTokens(liquidObject, subscription, store);

                if (customer != null)
                {
                    await _messageTokenProvider.AddCustomerTokens(liquidObject, customer, store, language);

                    await _messageTokenProvider.AddShoppingCartTokens(liquidObject, customer, store, language);
                }

                var body    = LiquidExtensions.Render(liquidObject, campaign.Body);
                var subject = LiquidExtensions.Render(liquidObject, campaign.Subject);

                var email = new QueuedEmail {
                    Priority       = QueuedEmailPriority.Low,
                    From           = emailAccount.Email,
                    FromName       = emailAccount.DisplayName,
                    To             = subscription.Email,
                    Subject        = subject,
                    Body           = body,
                    CreatedOnUtc   = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };
                await _queuedEmailService.InsertQueuedEmail(email);
                await InsertCampaignHistory(new CampaignHistory()
                {
                    CampaignId = campaign.Id, CustomerId = subscription.CustomerId, Email = subscription.Email, CreatedDateUtc = DateTime.UtcNow, StoreId = campaign.StoreId
                });

                //activity log
                if (customer != null)
                {
                    await _customerActivityService.InsertActivity("CustomerReminder.SendCampaign", campaign.Id, _localizationService.GetResource("ActivityLog.SendCampaign"), customer, campaign.Name);
                }
                else
                {
                    await _customerActivityService.InsertActivity("CustomerReminder.SendCampaign", campaign.Id, _localizationService.GetResource("ActivityLog.SendCampaign"), campaign.Name + " - " + subscription.Email);
                }

                totalEmailsSent++;
            }
            return(totalEmailsSent);
        }
        public int SendFriendRequestNotification(Customer customer, int friendRequestCount, int languageId, int storeId)
        {
            var store = _storeService.GetStoreById(storeId);

            languageId = EnsureLanguageIsActive(languageId, store.Id);


            var messageTemplate = GetLocalizedActiveMessageTemplate("MobSocial.FriendRequestNotification", store.Id);

            if (messageTemplate == null)
            {
                return(0);
            }


            var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

            //tokens
            var tokens = new List <Token>();

            _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);
            _messageTokenProvider.AddCustomerTokens(tokens, customer);
            tokens.Add(new Token("FriendRequestCount", friendRequestCount.ToString()));


            //event notification
            _eventPublisher.MessageTokensAdded(messageTemplate, tokens);


            var toEmail = customer.Email;
            var toName  = customer.GetFullName().ToTitleCase();


            return(SendNotification(messageTemplate, emailAccount, languageId, tokens, toEmail, toName));
        }
Esempio n. 18
0
        /// <summary>
        /// Sends a campaign to specified emails
        /// </summary>
        /// <param name="campaign">Campaign</param>
        /// <param name="emailAccount">Email account</param>
        /// <param name="subscriptions">Subscriptions</param>
        /// <returns>Total emails sent</returns>
        public virtual int SendCampaign(Campaign campaign, EmailAccount emailAccount,
                                        IEnumerable <NewsLetterSubscription> subscriptions, int languageId, List <int> Categories, DateTime startDate, DateTime?endDate, int itemCount)
        {
            if (campaign == null)
            {
                throw new ArgumentNullException("campaign");
            }

            if (emailAccount == null)
            {
                throw new ArgumentNullException("emailAccount");
            }

            int  totalEmailsSent    = 0;
            bool hasProductsToken   = campaign.Body.IndexOf("%Store.RecentProducts%") > 0;
            bool hasBuyingRequests  = campaign.Body.IndexOf("%Store.RecentProductBuyingRequests%") > 0;
            var  productDates       = new NewsletterDates();
            var  buyingRequestDates = new NewsletterDates();
            var  tokens             = new List <Token>();

            if (hasProductsToken)
            {
                productDates = _newsletterDatesService.GetAllNewsletterDates().Where(x => x.LanguageId == languageId && x.IsProduct).FirstOrDefault();
                if (endDate == null)
                {
                    startDate = productDates.LastSubmit;
                }
                _messageTokenProvider.AddRecentProductsToken(tokens, languageId, Categories, startDate, endDate, itemCount);
            }
            if (hasBuyingRequests)
            {
                buyingRequestDates = _newsletterDatesService.GetAllNewsletterDates().Where(x => x.LanguageId == languageId && !x.IsProduct).FirstOrDefault();
                if (endDate == null)
                {
                    startDate = buyingRequestDates.LastSubmit;
                }
                _messageTokenProvider.AddRecentBuyingRequestsToken(tokens, languageId, Categories, startDate, endDate, itemCount);
            }

            foreach (var subscription in subscriptions.Where(x => x.LanguageId == languageId))
            {
                var tokensTemp = new List <Token>();
                tokensTemp.AddRange(tokens);
                _messageTokenProvider.AddStoreTokens(tokensTemp);
                _messageTokenProvider.AddNewsLetterSubscriptionTokens(tokensTemp, subscription);

                var customer = _customerService.GetCustomerByEmail(subscription.Email);
                if (customer != null)
                {
                    _messageTokenProvider.AddCustomerTokens(tokensTemp, customer);
                }

                string subject = _tokenizer.Replace(campaign.Subject, tokensTemp, false);
                string body    = _tokenizer.Replace(campaign.Body, tokensTemp, true);

                var email = new QueuedEmail()
                {
                    Priority       = 3,
                    From           = emailAccount.Email,
                    FromName       = emailAccount.DisplayName,
                    To             = subscription.Email,
                    Subject        = subject,
                    Body           = body,
                    CreatedOnUtc   = DateTime.UtcNow,
                    EmailAccountId = emailAccount.Id
                };
                _queuedEmailService.InsertQueuedEmail(email);
                totalEmailsSent++;
            }
            if (hasProductsToken)
            {
                productDates.LastSubmit = DateTime.UtcNow;
                _newsletterDatesService.UpdateNewsletterDates(productDates);
            }
            if (hasBuyingRequests)
            {
                buyingRequestDates.LastSubmit = DateTime.UtcNow;
                _newsletterDatesService.UpdateNewsletterDates(buyingRequestDates);
            }

            return(totalEmailsSent);
        }
        /// <summary>
        /// Sends 'New customer' notification message to a store owner
        /// </summary>
        /// <param name="customer">Customer instance</param>
        /// <param name="languageId">Message language identifier</param>
        /// <returns>Queued email identifier</returns>
        public virtual IList <int> SendCustomerRegisteredNotificationMessage(Customer customer, int languageId)
        {
            if (customer == null)
            {
                throw new ArgumentNullException(nameof(customer));
            }

            var store = _storeContext.CurrentStore;

            languageId = EnsureLanguageIsActive(languageId, store.Id);

            var messageTemplates = GetActiveMessageTemplates(MessageTemplateSystemNames.CustomerRegisteredNotification, store.Id);

            if (!messageTemplates.Any())
            {
                return(new List <int>());
            }

            //tokens
            var commonTokens = new List <Token>();

            _messageTokenProvider.AddCustomerTokens(commonTokens, customer);

            return(messageTemplates.Select(messageTemplate =>
            {
                //email account
                var emailAccount = GetEmailAccountOfMessageTemplate(messageTemplate, languageId);

                var tokens = new List <Token>(commonTokens);
                _messageTokenProvider.AddStoreTokens(tokens, store, emailAccount);

                //event notification
                _eventPublisher.MessageTokensAdded(messageTemplate, tokens);

                var toEmail = emailAccount.Email;
                var toName = emailAccount.DisplayName;

                return SendNotification(messageTemplate, emailAccount, languageId, tokens, toEmail, toName);
            }).ToList());
        }