コード例 #1
0
        public void Sending(MessageContext context) {
            var contentItem = _contentManager.Get(context.Recipient.Id);
            if ( contentItem == null )
                return;

            var recipient = contentItem.As<UserPart>();
            if ( recipient == null )
                return;

            if (context.Type == MessageTypes.Validation) {
                var registeredWebsite = _siteService.GetSiteSettings().As<RegistrationSettingsPart>().ValidateEmailRegisteredWebsite;
                var contactEmail = _siteService.GetSiteSettings().As<RegistrationSettingsPart>().ValidateEmailContactEMail;
                var userKey = _userkeyService.GetAccessKeyForUser(context.Recipient.Id);

                context.MailMessage.Subject = T("Verification E-Mail").Text;
                context.MailMessage.Body =
                    T("Thank you for registering with {0}.<br/><br/><br/><b>Final Step</b><br/>To verify that you own this e-mail address, please click the following link:<br/><a href=\"{1}\">{1}</a><br/><br/><b>Troubleshooting:</b><br/>If clicking on the link above does not work, try the following:<br/><br/>Select and copy the entire link.<br/>Open a browser window and paste the link in the address bar.<br/>Click <b>Go</b> or, on your keyboard, press <b>Enter</b> or <b>Return</b>.<br/><br/>Your access key for uploading packages is: {2}", registeredWebsite, context.Properties["ChallengeUrl"], userKey.AccessKey).Text;

                if (!String.IsNullOrWhiteSpace(contactEmail)) {
                    context.MailMessage.Body += T("<br/><br/>If you continue to have access problems or want to report other issues, please <a href=\"mailto:{0}\">Contact Us</a>.", contactEmail).Text;
                }

                FormatEmailBody(context);
                context.MessagePrepared = true;
            }

        }
コード例 #2
0
        public void Sending(MessageContext context)
        {
            if (context.MessagePrepared)
                return;

            var contentItem = _contentManager.Get(context.Recipient.Id);
            if ( contentItem == null )
                return;

            var recipient = contentItem.As<ContactFormPart>();
            if ( recipient == null )
                return;

            /*
             * {"Company", contact.Company},
                {"Current Website", contact.CurrentWebsite},
                {"Email", contact.Email},
                {"Message", contact.Message},
                {"Name",contact.Name},
                {"Phone",contact.Phone},
                {"Topic",contact.Topic}
             */

            switch (context.Type) {
                case MessageTypes.ContactRequest:
                    context.MailMessage.Subject = T("[New Contact Request]: {0}", context.Properties["Topic"]).Text;
                    context.MailMessage.Body =
                        T("<p>The visitor <b>{0}</b> with email <b>{1}</b> has requested contact.</p><ul><li>Company: {2}</li><li>Current Website: {3}</li><li>Phone: {4}</li><li>Message: {5}</li></ul>",
                            context.Properties["Name"], context.Properties["Email"], context.Properties["Company"],context.Properties["Current Website"], context.Properties["Phone"], context.Properties["Message"]).Text;
                    FormatEmailBody(context);
                    context.MessagePrepared = true;
                    break;
            }
        }
コード例 #3
0
		public void Sending(MessageContext context)
		{
			if ( context.Type == "ContactUs" ) {
				context.MailMessage.Subject = "Contact us form";
				context.MailMessage.Body = string.Format("Message from: {0} - {1}\n{2}", context.Properties["Name"], context.Properties["Email"], context.Properties["Message"]);
			}

		}
コード例 #4
0
 private UserPart GetRecipient(MessageContext context) {
     // we expect a single account to be created
     var contentItem = _contentManager.Get(context.Recipients.Single().Id);
     if (contentItem == null) {
         return null;
     }
     return contentItem.As<UserPart>();
 }
コード例 #5
0
        public void Sending(MessageContext context) {
            var contentItem = _contentManager.Get(context.Recipient.Id);
            if ( contentItem == null )
                return;

            var recipient = contentItem.As<IUser>();
            if ( recipient == null )
                return;

            context.MailMessage.To.Add(recipient.Email);
        }
コード例 #6
0
 public void Sending(MessageContext context)
 {
     if (context.MessagePrepared)
         return;
     switch (context.Type)
     {
         case DEFAULT_XODB_EMAIL_TYPE:
             context.MailMessage.Subject = context.Properties["Subject"];
             context.MailMessage.Body = context.Properties["Body"];
             context.MessagePrepared = true;
             break;
     }
 }
コード例 #7
0
        public void Sending(MessageContext context)
        {
            if (context.MessagePrepared)
                return;

            var contentItem = _contentManager.Get(context.Recipient.Id);
            if ( contentItem == null )
                return;

            var recipient = contentItem.As<UserPart>();
            if ( recipient == null )
                return;

            switch (context.Type) {
                case MessageTypes.Moderation:
                    context.MailMessage.Subject = T("New account").Text;
                    context.MailMessage.Body =
                        T("The user <b>{0}</b> with email <b>{1}</b> has requested a new account. This user won't be able to log while his account has not been approved.",
                            context.Properties["UserName"], context.Properties["Email"]).Text;
                    FormatEmailBody(context);
                    context.MessagePrepared = true;
                    break;

                case MessageTypes.Validation:
                    var registeredWebsite = _siteService.GetSiteSettings().As<RegistrationSettingsPart>().ValidateEmailRegisteredWebsite;
                    var contactEmail = _siteService.GetSiteSettings().As<RegistrationSettingsPart>().ValidateEmailContactEMail;
                    context.MailMessage.Subject = T("Verification E-Mail").Text;
                    context.MailMessage.Body =
                        T("Thank you for registering with {0}.<br/><br/><br/><b>Final Step</b><br/>To verify that you own this e-mail address, please click the following link:<br/><a href=\"{1}\">{1}</a><br/><br/><b>Troubleshooting:</b><br/>If clicking on the link above does not work, try the following:<br/><br/>Select and copy the entire link.<br/>Open a browser window and paste the link in the address bar.<br/>Click <b>Go</b> or, on your keyboard, press <b>Enter</b> or <b>Return</b>.",
                            registeredWebsite, context.Properties["ChallengeUrl"]).Text;

                    if (!String.IsNullOrWhiteSpace(contactEmail)) {
                        context.MailMessage.Body +=
                            T("<br/><br/>If you continue to have access problems or want to report other issues, please <a href=\"mailto:{0}\">Contact Us</a>.",
                                contactEmail).Text;
                    }
                    FormatEmailBody(context);
                    context.MessagePrepared = true;
                    break;

                case MessageTypes.LostPassword:
                    context.MailMessage.Subject = T("Lost password").Text;
                    context.MailMessage.Body =
                        T("Dear {0}, please <a href=\"{1}\">click here</a> to change your password.", recipient.UserName,
                          context.Properties["LostPasswordUrl"]).Text;
                    FormatEmailBody(context);
                    context.MessagePrepared = true;
                    break;
            }
        }
コード例 #8
0
        public void Sending(MessageContext context)
        {
            if (context.MessagePrepared)
                return;

            switch (context.Type)
            {
                case MessageTypes.SendFormResult:
                    var form = _contentManager.Get<OFormPart>(context.Recipients.First().Id);
                    if (form == null)
                        return;

                    foreach (var email in form.EmailSendTo.Split(new []{';', ' ', ','}, StringSplitOptions.RemoveEmptyEntries))
                    {
                        var mailAddress = new MailAddress(email);
                        context.MailMessage.To.Add(mailAddress);
                    }

                    context.MailMessage.Subject = form.EmailSubject ?? "no subject";
                    var template = form.EmailTemplate ?? "no template";
                    foreach (var key in context.Properties.Keys)
                    {
                        template = template.Replace("{" + key + "}", context.Properties[key]);
                    }

                    template += @"
            Form submitted on " + context.Properties[OFormGlobals.CreatedDateKey] + " from ip " + context.Properties[OFormGlobals.IpKey];

                    context.MailMessage.Body = template.Replace("\r\n", "\n").Replace("\n", "<br />");

                    // add message attachments, if any
                    var resultId = Convert.ToInt32(context.Properties["oforms.formResult.Id"]);
                    var result = this._resultRepo.Get(resultId);
                    if (result != null)
                    {
                        foreach (var file in result.Files)
                        {
                            var ms = new MemoryStream(file.Bytes);
                            var attachment = new Attachment(ms,
                                String.Format("{1}_{0}", file.OriginalName, file.FieldName),
                                file.ContentType);
                            context.MailMessage.Attachments.Add(attachment);
                        }
                    }

                    context.MessagePrepared = true;
                    break;
            }
        }
        public void Sending(MessageContext context) {
            if (context.MessagePrepared || context.Type != TemplatedMessageActions.MessageType)
                return;

            var templateId = int.Parse(context.Properties["TemplateId"]);
            var template = _messageTemplateService.GetTemplate(templateId);
            var body = _messageTemplateService.ParseTemplate(template, new ParseTemplateContext {
                ViewBag = context.Properties
            });

            context.MailMessage.Subject = _tokenizer.Replace(template.Subject, context.Properties, ReplaceOptions.Default);
            context.MailMessage.Body = body;
            context.MessagePrepared = true;
            context.Properties["BaseUrl"] = VirtualPathUtility.RemoveTrailingSlash(_services.WorkContext.CurrentSite.BaseUrl);
        }
コード例 #10
0
        public void Send(IEnumerable<ContentItemRecord> recipients, string type, string service, Dictionary<string, string> properties = null) {
            if ( !HasChannels() )
                return;

            Logger.Information("Sending message {0}", type);
            try {
                var context = new MessageContext {
                    Recipients = recipients,
                    Type = type,
                    Service = service
                };

                PrepareAndSend(type, properties, context);
            }
            catch ( Exception e ) {
                Logger.Error(e, "An error occured while sending the message {0}", type);
            }
        }
コード例 #11
0
        public void Sending(MessageContext context) {
            if (context.Type != GalleryMessageTypes.ContactOwners) {
                return;
            }
            string packageId = context.Properties["PackageId"];
            string reportBody = context.Properties["ReportBody"];
            string reporterUserName = context.Properties["ReporterUserName"];
            string reporterEmail = context.Properties["ReporterEmail"];
            LocalizedString subject = T("Message for owners of package '{0}'", packageId);
            LocalizedString body = T("The user <strong>{1}</strong> ({2}) has submitted the following message to the owners of Package '{0}'." +
                "<br /><br />{3}<br /><br />" +
                "- The Orchard Gallery Team",
                packageId, reporterUserName, reporterEmail, reportBody);

            context.MailMessage.Subject = subject.Text;
            context.MailMessage.Body = body.Text;
            context.MessagePrepared = true;
        }
コード例 #12
0
        public void Sending(MessageContext context)
        {
            if (context.MessagePrepared)
                return;

            if ((context.Recipients == null || !context.Recipients.Any()) &&
               (context.Addresses == null || !context.Addresses.Any())) {
                return;
            }

            switch (context.Type) {
                case "RegistrationFormEmail":
                    context.MailMessage.Subject = context.Properties["Subject"];
                    context.MailMessage.Body = context.Properties["Body"];
                    context.MessagePrepared = true;
                    break;
            } 
        }
コード例 #13
0
        public void Sending(MessageContext context) {
            if (context.Recipients != null) {
                foreach (var rec in context.Recipients) {
                    var contentItem = _contentManager.Get(rec.Id);
                    if (contentItem == null)
                        return;

                    var recipient = contentItem.As<IUser>();
                    if (recipient == null)
                        return;

                    context.MailMessage.To.Add(recipient.Email);
                }
            }

            foreach (var address in context.Addresses) {
                context.MailMessage.To.Add(address);
            }
        }
コード例 #14
0
        public void Sending(MessageContext context) {
            if (context.Type != GalleryMessageTypes.ReportAbuse) {
                return;
            }
            string packageId = context.Properties["PackageId"];
            string packageVersion = context.Properties["PackageVersion"];
            string reportBody = context.Properties["ReportBody"];
            string reporterUserName = context.Properties["ReporterUserName"];
            string reporterEmail = context.Properties["ReporterEmail"];
            LocalizedString subject = T("Abuse Report for Package '{0}' Version '{1}'", packageId, packageVersion);
            LocalizedString body = T("The user <strong>{2}</strong> ({3}) has reported abuse on Package '{0}', version '{1}'." +
                " {2} left the following information in the report:<br /><br />{4}<br /><br />" +
                "- The Orchard Gallery Team",
                packageId, packageVersion, reporterUserName, reporterEmail, reportBody);

            context.MailMessage.Subject = subject.Text;
            context.MailMessage.Body = body.Text;
            context.MessagePrepared = true;
        }
コード例 #15
0
        public void SendMessage(MessageContext context) {
            if ( !context.Service.Equals(EmailService, StringComparison.InvariantCultureIgnoreCase) )
                return;

            var smtpSettings = _orchardServices.WorkContext.CurrentSite.As<SmtpSettingsPart>();

            // can't process emails if the Smtp settings have not yet been set
            if ( smtpSettings == null || !smtpSettings.IsValid() ) {
                return;
            }

            using (var smtpClient = new SmtpClient()) {
                smtpClient.UseDefaultCredentials = !smtpSettings.RequireCredentials;
                if (!smtpClient.UseDefaultCredentials && !String.IsNullOrWhiteSpace(smtpSettings.UserName)) {
                    smtpClient.Credentials = new NetworkCredential(smtpSettings.UserName, smtpSettings.Password);
                }

                if (context.MailMessage.To.Count == 0) {
                    Logger.Error("Recipient is missing an email address");
                    return;
                }

                if (smtpSettings.Host != null)
                    smtpClient.Host = smtpSettings.Host;

                smtpClient.Port = smtpSettings.Port;
                smtpClient.EnableSsl = smtpSettings.EnableSsl;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

                context.MailMessage.From = new MailAddress(smtpSettings.Address);
                context.MailMessage.IsBodyHtml = !String.IsNullOrWhiteSpace(context.MailMessage.Body) && context.MailMessage.Body.Contains("<") && context.MailMessage.Body.Contains(">");

                try {
                    smtpClient.Send(context.MailMessage);
                    Logger.Debug("Message sent to {0}: {1}", context.MailMessage.To[0].Address, context.Type);
                }
                catch (Exception e) {
                    Logger.Error(e, "An unexpected error while sending a message to {0}: {1}", context.MailMessage.To[0].Address, context.Type);
                }
            }
        }
コード例 #16
0
        private void PrepareAndSend(string type, Dictionary<string, string> properties, MessageContext context) {
            try {
                if (properties != null) {
                    foreach (var key in properties.Keys)
                        context.Properties.Add(key, properties[key]);
                }

                _messageEventHandler.Sending(context);

                foreach (var channel in _channels) {
                    channel.SendMessage(context);
                }

                _messageEventHandler.Sent(context);
            }
            finally {
                context.MailMessage.Dispose();
            }

            Logger.Information("Message {0} sent", type);
        }
コード例 #17
0
        public void Sending(MessageContext context) {
            if (context.Type != GalleryMessageTypes.PackageIdExpirationWarning) {
                return;
            }

            string userName = context.Properties["UserName"];
            string siteName = context.Properties["SiteName"];
            string packageId = context.Properties["PackageId"];
            string expirationDate = context.Properties["ExpirationDate"];

            LocalizedString subject = T("Package ID Expiration Warning");
            LocalizedString body = T("Dear {0},<br />" +
                "You registered the Package ID {1} on {2}. This registration will expire on {3}. " +
                "If you intend to use this ID you will need to upload a package using the ID before the expiration date. " +
                "Otherwise the registration for ID {1} will be deleted and become available to the community.<br /><br />" +
                "- The {2} Team",
                userName, packageId, siteName, expirationDate);

            context.MailMessage.Subject = subject.Text;
            context.MailMessage.Body = body.Text;
            context.MessagePrepared = true;
        }
コード例 #18
0
        public void Send(IEnumerable<string> recipientAddresses, string type, string service, Dictionary<string, string> properties = null) {
            if (!HasChannels())
                return;

            Logger.Information("Sending message {0}", type);
            try {

                var context = new MessageContext {
                    Type = type,
                    Service = service,
                    Addresses = recipientAddresses
                };

                PrepareAndSend(type, properties, context);
            }
            catch (Exception ex) {
                if (ex.IsFatal()) {
                    throw;
                } 
                Logger.Error(ex, "An error occured while sending the message {0}", type);
            }
        }
コード例 #19
0
        public void Send(ContentItemRecord recipient, string type, string service, Dictionary<string, string> properties = null) {
            if ( !HasChannels() )
                return;

            Logger.Information("Sending message {0}", type);
            try {

                var context = new MessageContext {
                    Recipient = recipient,
                    Type = type,
                    Service = service
                };

                try {

                    if (properties != null) {
                        foreach (var key in properties.Keys)
                            context.Properties.Add(key, properties[key]);
                    }

                    _messageEventHandler.Sending(context);

                    foreach (var channel in _channels) {
                        channel.SendMessage(context);
                    }

                    _messageEventHandler.Sent(context);
                }
                finally {
                    context.MailMessage.Dispose();
                }

                Logger.Information("Message {0} sent", type);
            }
            catch ( Exception e ) {
                Logger.Error(e, "An error occured while sending the message {0}", type);
            }
        }
コード例 #20
0
        public void Sending(MessageContext context) {
            if (context.Recipients != null) {
                foreach (var rec in context.Recipients) {
                    var contentItem = _contentManager.Get(rec.Id);
                    if (contentItem == null)
                        return;

                    var recipient = contentItem.As<IUser>();
                    if (recipient == null)
                        return;

                    context.MailMessage.To.Add(recipient.Email);
                }
            }

            foreach (var address in context.Addresses) {
                try {
                    context.MailMessage.To.Add(address);
                }
                catch (Exception e) {
                    Logger.Error(e, "Unexpected error while trying to send email.");
                }
            }
        }
コード例 #21
0
ファイル: MailActions.cs プロジェクト: kanujhun/orchard
 public void Sent(MessageContext context) {
 }
コード例 #22
0
ファイル: MailActions.cs プロジェクト: kanujhun/orchard
 private static void FormatEmailBody(MessageContext context) {
     context.MailMessage.Body = "<p style=\"font-family:Arial, Helvetica; font-size:10pt;\">" + context.MailMessage.Body + "</p>";
 }
コード例 #23
0
 public void SendMessage(MessageContext message) {
     Messages.Add(message);
 }
コード例 #24
0
        public void Sending(MessageContext context) {
            if (context.MessagePrepared)
                return;

            var contentItem = _contentManager.Get(context.Recipient.Id);
            if (contentItem == null)
                return;

            var recipient = contentItem.As<IUser>();
            if (recipient == null)
                return;

            switch (context.Type) {
                case MailActions.MessageType:
                    context.MailMessage.Subject = context.Properties["Subject"];
                    context.MailMessage.Body = context.Properties["Body"];
                    FormatEmailBody(context);
                    context.MessagePrepared = true;
                    break;
            }
        }
コード例 #25
0
        public bool SendEmailNotificationToSubscribers(PostPart postPart)
        {
            var threadPart = postPart.ThreadPart;
            var subscriptionsToThread = _threadSubscriptionRepository.Table.Where(e => e.ThreadId == threadPart.Id && e.EmailUpdates == true).ToList();
            //if there are subscribed users
            if (subscriptionsToThread.Count > 0)
            {
                //it is possible that the subscribed user no longer exists (i.e. has been deleted from the system)
                var subscribedUserIds = subscriptionsToThread.Select( t=>t.UserId ).ToList();
                var userParts = _userRepository.Table.Where(user => subscribedUserIds.Contains(user.Id)).ToList();
                if (userParts.Count > 0)
                {
                    var usersCultures = _userPreferredCultureService.GetUsersCultures(userParts.Select( user=>user.Id).ToList());
                    foreach (var culture in usersCultures.Keys)
                    {
                        var userList = userParts.Where( user=> usersCultures[culture].Contains( user.Id)).ToList();

                        //it would be possible to use the BCC to send to all subscribed users provided that the list is 'reasonable' in length 
                        //i.e. 100 or less otherwise the mail server may truncate or refuse to send.
                        //that approach however won't work with the orchard email channel because it requires a MailMessage.To recipient and misses the 
                        //case that an email is sent BCC only.
                        foreach (var user in userList)
                        {
                            if (!String.IsNullOrWhiteSpace(user.Email))
                            {
                                var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
                                string baseUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);


                                var postUrl = baseUrl + urlHelper.Action("ViewPostInThread", "Thread", new { postId=postPart.Id});
                               
                                
                                var translationEmail = _subscriptionEmailTemplateService.GetEmailTemplateTranslation(culture, postPart.ThreadPart.Title, postPart.Text, postPart.Format, postUrl, _orchardServices.WorkContext.CurrentSite.BaseUrl);
                                MessageContext messageContext = new MessageContext();
                                messageContext.MailMessage.Subject = translationEmail.Title;
                                messageContext.MailMessage.Body = translationEmail.BodyPlainText;
                                messageContext.MailMessage.To.Add(user.Email);
                                AlternateView altView = AlternateView.CreateAlternateViewFromString(translationEmail.BodyHtml, System.Text.Encoding.UTF8, "text/html");
                                messageContext.MailMessage.AlternateViews.Add(altView);
                                messageContext.MailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                                messageContext.Service = EmailMessagingChannel.EmailService;
                                _emailMessageingChannel.SendMessage(messageContext);
                            }
                        }

                    }
                }
            }

            return true;
        }
コード例 #26
0
        /// <summary>
        /// Set up the Body and Subject of the email
        /// </summary>
        /// <param name="context"></param>
        public void Sending(MessageContext context) 
        {
            switch(context.Type)
            {
                case "ORDER_RECEIVED":
                    context.MailMessage.Body = context.Properties["Body"];
                    context.MailMessage.Subject = context.Properties["Subject"];
                    break;
                case "WELCOME":
                    context.MailMessage.Subject = context.Properties["Subject"];
                    context.MailMessage.Body = MergeBody(context.Properties);
                    break;
                case "SUBSCRIBE":
                    try
                    {
                        string apiKey = context.Properties["MailChimpApiKey"]; // "9fc63c6d93d5d5fdaa936e349006e1c2-us6";
                        string listName = context.Properties["MailChimpListName"]; // "Cascade Print Room Subscriber Mailing List";
                        string groupName = context.Properties["MailChimpGroupName"]; // "Snail Mail";
                        string groupValue = context.Properties["MailChimpGroupValue"]; // "Snail mail (please provide an address above)";

                        // add subscriber to our MailChimp list
                        var mc = new MailChimp.MCApi(apiKey, true);
                        var result = mc.Ping();
                        if (result != "Everything's Chimpy!")
                            throw new Exception("invalid api key");

                        // retrieve list id
                        var lists = mc.Lists();

                        if (lists == null || lists.Data == null || !lists.Data.Any())
                            throw new Exception("no lists");

                        var list = lists.Data.FirstOrDefault(l => l.Name == listName);
                        if (list == null)
                            throw new Exception(string.Format("unable to find a list called '{0}'", listName));

                        // build groups
                        var groupings = new List<MailChimp.Types.List.Grouping>();

                        if (context.Properties["ReceivePost"] == "True")
                        {
                            groupings.Add(new MailChimp.Types.List.Grouping(groupName,
                                                                            new string[] { groupValue })
                                         );
                        }


                        // options
                        //var options = new MailChimp.Types.List.SubscribeOptions { DoubleOptIn = false, EmailType = MailChimp.Types.List.EmailType.Html, UpdateExisting = true, ReplaceInterests = true };

                        // build merge vars
                        const string spaces = "  ";
                        var mergeVars = new MailChimp.Types.List.Merges(context.Addresses.First(),
                                                                        MailChimp.Types.List.EmailType.Html,
                                                                        groupings.ToArray())
                            {
                                {"FNAME", context.Properties["FirstName"]},
                                {"LNAME", context.Properties["LastName"]},
                                {"ADDRESS", context.Properties["Address"]
                                               + spaces + context.Properties["City"]
                                               + spaces + context.Properties["State"]
                                               + spaces + context.Properties["Postcode"]
                                               + spaces + context.Properties["CountryCode"]
                                }
                            };
                     

                        // subscribe
                        mc.ListSubscribe(list.ListID, context.Addresses.First(), mergeVars);

                    }
                    catch (Exception ex)
                    {
                        Logger.Error("MailChimp failed: {0}", ex.Message);
                    }
                    break;
            }
        }