示例#1
0
文件: Program.cs 项目: vip32/postal
        private static void Main()
        {
            // create the email template
            var template = new EmailTemplate("Test");
            dynamic dtemplate = template;
            dtemplate.To = "*****@*****.**";
            dtemplate.Message = "Hello, non-asp.net world! ";
            dtemplate.Test = "test property";
            dtemplate.SubjectSuffix = DateTime.Now.ToShortTimeString();
            dtemplate.Values = new[] {"one", "two", "three"};
            template.Attach(@"c:\tmp\test2.log");
            template.Attach(@"c:\tmp\cat.jpg", "CatImageId"); // TODO: put in progam folder

            // serialize and deserialize the email template
            var serializerSettings = new JsonSerializerSettings
            {
                Converters = new List<JsonConverter>
                {
                    new AttachmentReadConverter(true)
                }
            };
            var serializedTemplate = JsonConvert.SerializeObject(template, Formatting.Indented, serializerSettings);
            Console.WriteLine(serializedTemplate);
            Console.WriteLine("serialized size: {0}", serializedTemplate.Length);
            var deserializedTemplate = JsonConvert.DeserializeObject<EmailTemplate>(serializedTemplate, serializerSettings);

            // send the email template
            var engines = new ViewEngineCollection
            {
                new ResourceRazorViewEngine(typeof (Program).Assembly, @"ResourceSample.Resources.Views")
            };
            var service = new SmtpMessagingService(engines);
            service.Send(deserializedTemplate);
        }
示例#2
0
        public ActionResult SimpleHtml()
        {
            dynamic email = new EmailTemplate("SimpleHtml");
            email.Date = DateTime.UtcNow.ToString();

            return new TemplateViewResult(email);
        }
    public void Suspend_User(object s, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["uid"]))
        {
            int UserID = int.Parse(Request.QueryString["uid"]);

            //Cannot suspend the Administrator account.
            if (UserID != 1)
            {
                string Type = Request.Form["Type"];
                string Note = Request.Form["Note"];

                Blogic.SuspendUser(UserID, Type, Note);

                ProviderUserDetails user = new ProviderUserDetails();

                user.FillUp(UserID);

                EmailTemplate SendeMail = new EmailTemplate();

                //Flag = 1 = Suspension email notice.
                SendeMail.SendAccountSuspensionReinstateEmail(user.Email, user.Username, Type, 1);

                SendeMail = null;
                user = null;

                Response.Redirect("confirmusersuspenddeleteedit.aspx?mode=Suspend&uid=" + UserID);
            }
        }
    }
示例#4
0
 ///<summary>Inserts one EmailTemplate into the database.  Returns the new priKey.</summary>
 internal static long Insert(EmailTemplate emailTemplate)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         emailTemplate.EmailTemplateNum=DbHelper.GetNextOracleKey("emailtemplate","EmailTemplateNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(emailTemplate,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     emailTemplate.EmailTemplateNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(emailTemplate,false);
     }
 }
示例#5
0
    public void SendingRecipe(Object s, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["id"])
            && !string.IsNullOrEmpty(Request.QueryString["n"])
            && !string.IsNullOrEmpty(Request.QueryString["c"]))
        {

            EmailTemplate SendeMail = new EmailTemplate();

            SendeMail.ItemID = (int)Util.Val(Request.QueryString["id"]);
            SendeMail.ItemName = Request.QueryString["n"].ToString();
            SendeMail.Category = Request.QueryString["c"].ToString();

            SendeMail.SenderName = Util.FormatTextForInput(Request.Form["txtFromName"]);
            SendeMail.SenderEmail = Util.FormatTextForInput(Request.Form["txtFromEmail"]);
            SendeMail.LyricEmail = Util.FormatTextForInput(Request.Form["txtToEmail"]);
            SendeMail.LyricName = Util.FormatTextForInput(Request.Form["toname"]);

            SendeMail.SendEmailRecipeToAFriend();

            Panel1.Visible = false;

            lblsentmsg.Text = "<div style='text-align: center; border: solid 1px #800000; padding: 8px; margin-left: 25px; margin-right: 25px;'><span class='content12'>Thông điệp của bạn đã được gửi tới (<b>" + SendeMail.LyricEmail + "</b>).</span></div>";

            SendeMail = null;
        }
    }
示例#6
0
        public ActionResult MultiPart()
        {
            dynamic email = new EmailTemplate("MultiPart");
            email.Date = DateTime.UtcNow.ToString();

            return new TemplateViewResult(email);
        }
 protected void BtnCreate_Click( object sender, EventArgs e )
 {
     if ( Page.IsValid ) {
     EmailTemplate emailTemplate = new EmailTemplate( StoreId, TxtName.Text );
     emailTemplate.Save();
     base.Redirect( WebUtils.GetPageUrl( Constants.Pages.EditEmailTemplate ) + "?id=" + emailTemplate.Id + "&storeId=" + emailTemplate.StoreId );
       }
 }
 private EmailTemplate mapToDomain(EmailTemplateViewModel input, EmailTemplate emailTemplate)
 {
     var emailTemplateModel = input.EmailTemplate;
     emailTemplate.Name= emailTemplateModel.Name;
     emailTemplate.Description= emailTemplateModel.Description;
     emailTemplate.Template= emailTemplateModel.Template;
     return emailTemplate;
 }
示例#9
0
        public ActionResult SendSimple()
        {
            dynamic email = new EmailTemplate("Simple");
            email.Date = DateTime.UtcNow.ToString();
            email.Send();

            return RedirectToAction("Sent", "Home");
        }
        internal ResourceTemplateHelper(EmailTemplate emailTemplate, TemplateContext context)
        {
            Contract.Requires(emailTemplate != null);
            Contract.Requires(context != null);

            _emailTemplate = emailTemplate;
            _context = context;
        }
示例#11
0
 /// <summary>
 /// Sends email using a pre-defined email template
 /// If any of emailFromAddress/emailToAddress/emailCcAddress is String.Empty then EmailInfo will use corresponding address 
 /// from Email template
 /// If emailToAddress OR emailCcAddress is not String.Empty the string will be appended to corresponding address of Email 
 /// Template and saved in Email Info
 /// </summary>
 /// <param name="emailTemplateId">Email Template Id</param>
 /// <param name="emailFromAddress">From</param>
 /// <param name="emailToAddress">To: Comma separated string of email addresses</param>
 /// <param name="emailCcAddress">Cc: Comma separated string of email addresses</param>
 /// <param name="subjectPlaceholderValues">Place holder values for Subject template</param>
 /// <param name="bodyPlaceholderValues">Place holder values for Body template</param>
 /// <returns></returns>
 public static bool SendEmail(EmailTemplate emailTemplateId, string emailFromAddress, string emailToAddress,
                              string emailCcAddress, Dictionary<string, string> subjectPlaceholderValues,
                              Dictionary<string, string> bodyPlaceholderValues)
 {
     /*  IEmailBDC emailBDC = (IEmailBDC) BDCFactory.Instance.Create(BDCType.Email);
     return emailBDC.SendEmail(emailTemplateId, emailFromAddress, emailToAddress, emailCcAddress,
                               subjectPlaceholderValues, bodyPlaceholderValues);*/
     return true;
 }
 public EmailTemplateDto Map(EmailTemplate entity)
 {
     return new EmailTemplateDto
                {
                    Id = entity.Id,
                    Body = entity.Body,
                    Name = entity.Name,
                    Subject = entity.Subject
                };
 }
        public string Serialise(EmailTemplate template)
        {
            DataContractSerializer serialiser = new DataContractSerializer(typeof(EmailTemplate));

            StringBuilder sb = new StringBuilder();
            XmlWriter xw = XmlWriter.Create(sb);
            serialiser.WriteObject(xw, template);
            xw.Flush();
            xw.Close();

            return sb.ToString();
        }
		///<summary>Converts a DataTable to a list of objects.</summary>
		public static List<EmailTemplate> TableToList(DataTable table){
			List<EmailTemplate> retVal=new List<EmailTemplate>();
			EmailTemplate emailTemplate;
			for(int i=0;i<table.Rows.Count;i++) {
				emailTemplate=new EmailTemplate();
				emailTemplate.EmailTemplateNum= PIn.Long  (table.Rows[i]["EmailTemplateNum"].ToString());
				emailTemplate.Subject         = PIn.String(table.Rows[i]["Subject"].ToString());
				emailTemplate.BodyText        = PIn.String(table.Rows[i]["BodyText"].ToString());
				retVal.Add(emailTemplate);
			}
			return retVal;
		}
 public ActionResult EmailTemplate(EmailTemplate model)
 {
     var id = this.EmailTemplateService.Save(model);
     if (id > 0)
     {
         var data = this.EmailTemplateService.GetByID(id);
         return Json(data, JsonRequestBehavior.AllowGet);
     }
     else
     {
         return Content("");
     }
 }
示例#16
0
        public void Attach_adds_attachment()
        {
            dynamic email = new EmailTemplate("Test");
            var fileStream = new FileStream(@"c:\tmp\test2.log", FileMode.Open);
            fileStream.Position = 0;
            var memoryStream = new MemoryStream();
            fileStream.CopyTo(memoryStream);
            //var attachment = new Attachment(new MemoryStream(), "name");
            var attachment = new Attachment(memoryStream, "name");
            email.Attach(attachment);
            ((EmailTemplate)email).Attachments.ShouldContain(attachment);

            Console.WriteLine(JsonConvert.SerializeObject(email, Formatting.Indented,
                new MemoryStreamJsonConverter()));
        }
示例#17
0
        //commented out as need to alter method or MOQ request current
        //[TestMethod]
        public void TestEmailTemplate()
        {
            var template = new EmailTemplate() { Body = "Body", Title = "Title" };

            var text = template.TransformText();

            var pm = new PreMailer.Net.PreMailer(text);

            var path = GetEmailFolderPath() + "app.css";

            var css = File.ReadAllText(path);

            var il = pm.MoveCssInline(css: css);

            var res = il.Html;
        }
示例#18
0
        public void Save(EmailTemplate emailTemplate)
        {
            this._db.OpenConnection();
            MySqlCommand command = this._db.CreateCommand();

            command.CommandText = "UPDATE email_template SET displayname=?displayname, inleiding=?inleiding, informatie=?informatie, afsluiting=?afsluiting, afzenders=?afzenders WHERE id = ?id";

            command.Parameters.Add(new MySqlParameter("?id", MySqlDbType.Int32)).Value = emailTemplate.Id;
            command.Parameters.Add(new MySqlParameter("?displayname", MySqlDbType.String)).Value = emailTemplate.Displayname;
            command.Parameters.Add(new MySqlParameter("?inleiding", MySqlDbType.Text)).Value = emailTemplate.Inleiding;
            command.Parameters.Add(new MySqlParameter("?informatie", MySqlDbType.Text)).Value = emailTemplate.Informatie;
            command.Parameters.Add(new MySqlParameter("?afsluiting", MySqlDbType.Text)).Value = emailTemplate.Afsluiting;
            command.Parameters.Add(new MySqlParameter("?afzenders", MySqlDbType.String)).Value = emailTemplate.Afzenders;

            this._db.ExecuteCommand(command);
            this._db.CloseConnection();
        }
    /// <summary>
    /// Fills list of available fields.
    /// </summary>
    /// <param name="emailTemplateObj">EmailTemplate object</param>
    protected void FillFieldsList(EmailTemplate emailTemplateObj)
    {
        ListItem newItem = null;

        // Insert double opt-in activation link
        if ((emailTemplateObj != null) && (emailTemplateObj.TemplateType == EmailTemplateType.DoubleOptIn))
        {
            newItem = new ListItem(GetString("NewsletterTemplate.MacroActivationLink"), IssueHelper.MacroActivationLink);
            lstInsertField.Items.Add(newItem);
        }
        newItem = new ListItem(GetString("general.email"), IssueHelper.MacroEmail);
        lstInsertField.Items.Add(newItem);
        newItem = new ListItem(GetString("NewsletterTemplate.MacroFirstName"), IssueHelper.MacroFirstName);
        lstInsertField.Items.Add(newItem);
        newItem = new ListItem(GetString("NewsletterTemplate.MacroLastName"), IssueHelper.MacroLastName);
        lstInsertField.Items.Add(newItem);
        newItem = new ListItem(GetString("NewsletterTemplate.MacroUnsubscribeLink"), IssueHelper.MacroUnsubscribeLink);
        lstInsertField.Items.Add(newItem);
    }
示例#20
0
 public static void EditNewEmailTemplate(PanelPreferences preferences, EmailTemplate emailTemplate, string eid)
 {
     var communicationViewUrl = new Uri(preferences.PanelAdminUrl + "EmailWindow.aspx");
     string communicationViewFormParams = GetEmailEditViewFormParams(emailTemplate, eid);
     var bytes = Encoding.ASCII.GetBytes(communicationViewFormParams);
     var communicationsRequest = AutomationHelper.CreatePost(communicationViewUrl, preferences.CookieJar);
     communicationsRequest.Referer = preferences.PanelAdminUrl + "EmailWindow.aspx";
     communicationsRequest.ContentLength = bytes.Length;
     using (Stream os = communicationsRequest.GetRequestStream())
     {
         os.Write(bytes, 0, bytes.Length);
     }
     var response = (HttpWebResponse)communicationsRequest.GetResponse();
     string pageSource = String.Empty;
     using (var reader = new StreamReader(response.GetResponseStream()))
     {
         pageSource = reader.ReadToEnd();
     }
     response.Close();
 }
示例#21
0
        public IActionResult Put(EmailTemplate entityModel)
        {
            var emailTemplate = _emailTemplateService.FirstOrDefault(x => x.Id == entityModel.Id);

            //save it and respond
            emailTemplate.Subject             = entityModel.Subject;
            emailTemplate.Name                = entityModel.Name;
            emailTemplate.Template            = entityModel.Template;
            emailTemplate.AdministrationEmail = entityModel.AdministrationEmail;
            emailTemplate.IsMaster            = entityModel.IsMaster; //a system template can't be used as master
            if (entityModel.EmailAccountId > 0)
            {
                emailTemplate.EmailAccountId = entityModel.EmailAccountId;
            }

            _emailTemplateService.Update(emailTemplate);

            VerboseReporter.ReportSuccess("Sửa EmailTemplate thành công", "post");

            return(RespondSuccess(emailTemplate));
        }
示例#22
0
 internal ScenarioOptions(SendConfirmEmailMessageCommand command)
 {
     Command = command;
     Person  = new Person
     {
         RevisionId = 6,
         Emails     = new[]
         {
             new EmailAddress
             {
                 Value = command.EmailAddress,
             },
         },
     };
     EmailMessage = new EmailMessage
     {
         ToPerson = Person,
         Number   = 7,
     };
     EmailTemplate = new EmailTemplate();
 }
示例#23
0
 public virtual Task SendTemplateEmail(Dictionary <string, string> substitutions,
                                       string subject,
                                       EmailTemplate emailTemplate,
                                       string fromEmail,
                                       string fromName,
                                       string toEmail,
                                       string toName)
 {
     if (toEmail == null)
     {
         throw new ArgumentNullException(nameof(toEmail), $"{toName} does not have an email assigned");
     }
     return(SendTemplateEmail(substitutions,
                              subject,
                              emailTemplate,
                              fromEmail,
                              fromName,
                              new List <EmailAddress> {
         new EmailAddress(toEmail, toName)
     }));
 }
        public void Send(EmailTemplate template, params string[] recipients)
        {
            if (template == null)
            {
                throw new ArgumentNullException(nameof(template));
            }
            if (recipients == null)
            {
                throw new ArgumentNullException(nameof(recipients));
            }
            if (recipients.Length == 0)
            {
                throw new ArgumentException(@"Value cannot be an empty collection.", nameof(recipients));
            }

            var request = new SendEmailRequest(template, recipients, _from);

            Task response = _api.RequestAsync("messages/send", request);

            response.Wait();
        }
示例#25
0
        /// <summary>
        /// Handler for the SendNonWinnerEmailCommand
        /// </summary>
        /// <param name="command">The SendNonWinnerEmailCommand</param>
        public void HandleCommand(SendNonWinnerEmailCommand command)
        {
            List <string> nonWinners = eventRepository.GetAllNonWinnersForEvent(command.EventId);

            //Query for the email template
            EmailTemplate nonWinnerEmail = emailRepository.GetEmailTemplate(new EmailTemplate(Enumeration.TryFindById <EmailTemplateEnum>(3).DisplayValue));

            if (nonWinners != null && nonWinners.Any())
            {
                foreach (string email in nonWinners)
                {
                    nonWinnerEmail.EmailSubject = nonWinnerEmail.EmailSubject.Replace("@@EventName@@", command.EventName);

                    emailRepository.SendEmail(new Email(
                                                  Me2YouConstants.EmailProfile,
                                                  email,
                                                  nonWinnerEmail.EmailSubject,
                                                  nonWinnerEmail.EmailBody));
                }
            }
        }
示例#26
0
        private static async Task <Response> SendGridMailForTemplate(EmailTemplate emailTemplate, string body = null, string destinationEmail = null, string destinationName = null, string subject = null)
        {
            var bd = body != null ? body : emailTemplate.EmailTemplateEmailBody.ToString();

            return
                (await
                 SendGridMail(
                     new SendGridMessage()
            {
#if DEBUG
                From = new EmailAddress("*****@*****.**", "fake argigero"),
#else
                From = new EmailAddress(emailTemplate.EmailTemplateSenderEmail, emailTemplate.EmailTemplateSenderName),
#endif

                Subject = subject ?? emailTemplate.EmailTemplateSubject,
                PlainTextContent = StripHTML(bd),
                HtmlContent = string.IsNullOrEmpty(bd) ? string.Empty : bd,
            }, destinationEmail ?? emailTemplate.EmailTemplateRecipientEmail
                     , destinationName));
        }
示例#27
0
        public void ShouldQueueEmail2Parm()
        {
            DateTime      now           = DateTime.Now;
            string        expectedEmail = "*****@*****.**";
            EmailTemplate emailTemplate = new EmailTemplate()
            {
                Id              = Guid.Parse("93895b38-cc48-47a3-b592-c02691521b28"),
                CreatedBy       = "Mocked Created By",
                CreatedDateTime = now,
                UpdatedBy       = "Mocked Updated By",
                UpdatedDateTime = now,
                Subject         = "Mock Subject",
                Body            = "Mock Body",
                From            = "*****@*****.**",
            };
            Guid expectedEmailId   = Guid.Parse("389425bc-0380-467f-b003-e03cfa871f83");
            var  mockLogger        = new Mock <ILogger <EmailQueueService> >();
            var  mockJobclient     = new Mock <IBackgroundJobClient>();
            var  mockEmailDelegate = new Mock <IEmailDelegate>();

            mockEmailDelegate.Setup(s => s.GetEmailTemplate(It.IsAny <string>())).Returns(emailTemplate);
            mockEmailDelegate.Setup(s => s.InsertEmail(It.IsAny <Email>(), true)).Callback <Email, bool>((email, b) => email.Id = expectedEmailId);
            var mockMessagingVerificationDelegate = new Mock <IMessagingVerificationDelegate>();
            var mockWebHosting = new Mock <IWebHostEnvironment>();
            IEmailQueueService emailService = new EmailQueueService(
                mockLogger.Object,
                mockJobclient.Object,
                mockEmailDelegate.Object,
                mockMessagingVerificationDelegate.Object,
                mockWebHosting.Object);

            emailService.QueueNewEmail(expectedEmail, string.Empty, true);
            mockJobclient.Verify(x => x.Create(
                                     It.Is <Job>(job => job.Method.Name == "SendEmail" && (Guid)job.Args[0] == expectedEmailId),
                                     It.IsAny <EnqueuedState>()));
            mockEmailDelegate.Verify(x => x.InsertEmail(It.Is <Email>(email => email.Id == expectedEmailId &&
                                                                      email.To == expectedEmail &&
                                                                      email.Subject == emailTemplate.Subject &&
                                                                      email.Body == emailTemplate.Body), true));
        }
示例#28
0
        public void Startup()
        {
            this.template = new EmailTemplate
            {
                Id         = 1,
                Code       = "test",
                Title      = "title",
                Subject    = "#$AppName#",
                IsSystem   = true,
                From       = "#$UserEmail#",
                Notes      = "Just a note",
                Message    = "#$UserName#",
                Parameters = new List <TemplateParameter>()
            };

            var param = new TemplateParameter {
                Id = 10, Title = "Custom", Notes = "Template note", Template = this.template
            };

            this.template.Parameters.Add(param);

            var config = new BBWTConfig {
                App = new AppConfig {
                    Name = "Test Application"
                }
            };
            var user = new User {
                Name = "*****@*****.**", FirstName = "John", Surname = "Green"
            };

            var templateService   = new Mock <IEmailTemplateService>();
            var configService     = new Mock <IConfigService>();
            var membershipService = new Mock <IMembershipService>();

            templateService.Setup(s => s.GetTemplateByCode("test")).Returns(this.template);
            membershipService.Setup(s => s.GetCurrentUser()).Returns(user);
            configService.Setup(s => s.Settings).Returns(config);

            this.composer = new EmailComposer(templateService.Object, configService.Object, membershipService.Object);
        }
示例#29
0
        /// <summary>
        /// Return email template
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        public static EmailTemplate GetEmailTemplate(string Code)
        {
            //Accessing DB Layer
            DbCommand dbCommand = db.GetStoredProcCommand("prSelEmailTemplate");

            //Adding Input parameters
            db.AddInParameter(dbCommand, "Code", DbType.String, Code);

            EmailTemplate objEmailTemplate = new EmailTemplate();

            IDataReader dr = null;

            try
            {
                // Execute command
                dr = db.ExecuteReader(dbCommand);

                //Set Output
                if (dr.Read())
                {
                    objEmailTemplate.Id       = Convert.ToInt32(dr["Id"]);
                    objEmailTemplate.Text     = dr["Text"].ToString();
                    objEmailTemplate.RespCode = 0;
                }
                else
                {
                    objEmailTemplate.RespCode = 3;
                }
            }
            catch (Exception ex)
            {
                objEmailTemplate.RespCode = 1;
                objEmailTemplate.RespDesc = ex.ToString();
            }
            finally
            {
                dr.Close();
            }
            return(objEmailTemplate);
        }
        public void SetUp()
        {
            var generateResetPasswordTokenResult = new GenerateResetPasswordTokenResult
            {
                Email    = Test,
                Token    = Test,
                Username = Test
            };
            var emailTemplate = new EmailTemplate
            {
                TemplateName      = Test,
                Subject           = Test,
                Content           = Test,
                AllowedParameters = new[] { "{{username}}", "{{callbackUrl}}" }
            };

            request = new SendResetPasswordByAdminRequest {
                Login = Test
            };

            userTokenGenerator     = new Mock <IUserTokenGenerator>();
            cryptoService          = new Mock <ICryptoService>();
            emailSender            = new Mock <IEmailSender>();
            emailTemplateGenerator = new Mock <IEmailTemplateGenerator>();
            configuration          = new Mock <IConfiguration>();

            userTokenGenerator.Setup(c => c.GenerateResetPasswordToken(It.IsAny <string>()))
            .ReturnsAsync(generateResetPasswordTokenResult);
            cryptoService.Setup(c => c.Encrypt(It.IsAny <string>()))
            .Returns(Test);
            configuration.Setup(c => c.GetSection(It.IsAny <string>()))
            .Returns(new Mock <IConfigurationSection>().Object);
            emailTemplateGenerator.Setup(etg => etg.FindEmailTemplate(It.IsAny <string>()))
            .ReturnsAsync(emailTemplate);
            emailSender.Setup(es => es.Send(It.IsAny <EmailMessage>()))
            .ReturnsAsync(true);

            sendResetPasswordByAdminCommand = new SendResetPasswordByAdminCommand(userTokenGenerator.Object,
                                                                                  cryptoService.Object, emailSender.Object, emailTemplateGenerator.Object, configuration.Object);
        }
示例#31
0
        private void SendEmails(EmailTemplate emailId, List <int> userIds, Dictionary <string, string> customKeys, List <int> coursesInAssignment, int assignmentId)
        {
            Email template = db.Emails.FirstOrDefault(e => e.emailId == (int)emailId);

            foreach (int userId in userIds)
            {
                //if user has completed this assigned activity then skip
                List <int?>        coursesCompleted  = db.Assignment_CoursesCompletedGet(assignmentId, userId).ToList();
                IEnumerable <int?> coursesIncomplete = coursesInAssignment.Cast <int?>().Except(coursesCompleted);
                if (coursesIncomplete.Count() == 0)
                {
                    continue;
                }

                //this user has not completed the assigned set... spam him/her
                User   userInfo  = db.Users.FirstOrDefault(u => u.userId == userId);
                string userEmail = userInfo.email;
                string body      = template.body;
                string subject   = template.subject;

                //handle name out of loop
                body = Utilities.ReplaceStringCaseInsensitive(body, "{FirstName}", userInfo.firstName);
                body = Utilities.ReplaceStringCaseInsensitive(body, "{LastName}", userInfo.lastName);

                foreach (KeyValuePair <string, string> code in customKeys)
                {
                    body    = Utilities.ReplaceStringCaseInsensitive(body, code.Key, code.Value);
                    subject = Utilities.ReplaceStringCaseInsensitive(subject, code.Key, code.Value);
                }

                body = "<span style=\"font-family: Arial;font-size: 10pt;\">" + body + "</span>";

                WriteMsg("Sending email " + emailId + " to " + userEmail);

                if (req.Url.Port == 443 || (req.Url.Port == 80 && req.Url.Host != "localhost"))
                {
                    Utilities.SendEmail(ConfigurationManager.AppSettings.Get("DoNotReplyEmail"), userEmail, subject, body);
                }
            }
        }
        private void SendConfirmationEmail(List <MyMergeData> mergeData)
        {
            var emailOptions = MyContent.EmailOptions;
            var template     = new EmailTemplate(emailOptions.TemplateID);
            var email        = new EMail(template);

            email.Save();

            var name         = string.Empty;
            var emailAddress = string.Empty;

            var myData = mergeData[0];

            if (myData != null)
            {
                name         = string.Concat(myData.DonorFirstName, " ", myData.DonorLastName).Trim();
                emailAddress = myData.DonorEmail;

                if (!string.IsNullOrWhiteSpace(emailAddress))
                {
                    MergeFieldsData[] provider = { new MergeFieldsData(mergeData.ToArray()) };
                    var html = emailOptions.HTML;

                    email.ContentHTML     = Expand(emailOptions.HTML, mergeData.ToArray());
                    email.FromAddress     = emailOptions.FromAddress;
                    email.FromDisplayName = emailOptions.FromName;
                    email.Subject         = emailOptions.Subject;
                    email.ReplyAddress    = emailOptions.ReplyAddress;

                    try
                    {
                        email.Send(emailAddress, name, API.Users.CurrentUser.RaisersEdgeID, API.Users.CurrentUser.UserID, provider, this.Page);
                    }
                    catch (Exception ex)
                    {
                        Common.LogErrorToDB(ex, false);
                    }
                }
            }
        }
 public ReturnType UpdateEmailTemplate(string emailtemplateCode, EmailTemplate emailtemplate)
 {
     try
     {
         using (AladingEntities alading = new AladingEntities(AppSettings.GetConnectionString()))
         {
             /*var result = alading.EmailTemplate.Where(p => p.EmailTemplateID == emailtemplateID).ToList();*/
             var result = alading.EmailTemplate.Where(p => p.EmailTemplateCode == emailtemplateCode).ToList();
             if (result.Count == 0)
             {
                 return ReturnType.NotExisted;
             }
           
             EmailTemplate ob = result.First();
             ob.EmailTemplateCode = emailtemplate.EmailTemplateCode;
             ob.Name = emailtemplate.Name;
             ob.Type = emailtemplate.Type;
             ob.Creator = emailtemplate.Creator;
             ob.Content = emailtemplate.Content;
             ob.CreationTime = emailtemplate.CreationTime;
             
             if (alading.SaveChanges() == 1)
             {
                 return ReturnType.Success;
             }  
             else
             {
                 return ReturnType.OthersError;
             }
         }
     }
     catch (SqlException sex)
     {
         return ReturnType.ConnFailed;
     }
     catch (System.Exception ex)
     {
         return ReturnType.OthersError;
     }
 }
示例#34
0
        public When_EmailService_Is_Called_To_Send_Email()
        {
            var configuration = new MatchingConfiguration
            {
                SendEmailEnabled = true,
                GovNotifyApiKey  = "TestApiKey"
            };

            _notificationsApi = Substitute.For <IAsyncNotificationClient>();

            var logger = Substitute.For <ILogger <EmailService> >();
            var config = new MapperConfiguration(c => c.AddMaps(typeof(EmailHistoryMapper).Assembly));
            var mapper = new Mapper(config);

            var emailTemplate = new EmailTemplate
            {
                Id           = 1,
                TemplateId   = "1599768C-7D3D-43AB-8548-82A4E5349468",
                TemplateName = "TemplateName"
            };

            _emailTemplateRepository = Substitute.For <IRepository <EmailTemplate> >();
            var emailHistoryRepository = Substitute.For <IRepository <EmailHistory> >();

            _emailTemplateRepository.GetSingleOrDefaultAsync(Arg.Any <Expression <Func <EmailTemplate, bool> > >()).Returns(emailTemplate);

            var functionLogRepository = Substitute.For <IRepository <FunctionLog> >();

            var emailService = new EmailService(configuration, _notificationsApi, _emailTemplateRepository, emailHistoryRepository, functionLogRepository, mapper, logger);

            _toAddress = "*****@*****.**";
            var tokens = new Dictionary <string, string>
            {
                { "contactname", "name" }
            };

            const string templateName = "TestTemplate";

            emailService.SendEmailAsync(templateName, _toAddress, null, null, tokens, "System").GetAwaiter().GetResult();
        }
示例#35
0
        public static string Mail(string emailTo, EmailTemplate Template)
        {
            string Res = string.Empty;

            try
            {
                MailMessage mail = new MailMessage();
                if (emailTo.Contains(','))
                {
                    var emailList = emailTo.Split(',');
                    foreach (var item in emailList)
                    {
                        mail.To.Add(item);
                    }
                }
                else
                {
                    mail.To.Add(emailTo);
                }
                mail.From       = new MailAddress("*****@*****.**");
                mail.Subject    = Template.Header = "Please provide Subject here";        // Set Mail's Subject here
                mail.Body       = Template.TemplateBody = "Please provide Body here";     // Set Mail's Body here
                mail.IsBodyHtml = true;
                mail.Priority   = MailPriority.High;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "mail.esolzdev.com";
                smtp.Port = 25;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "Pyc8a1!6");
                smtp.EnableSsl             = false;
                smtp.Send(mail);
                Res = "Success! Mail has been sent";
            }
            catch (Exception ex)
            {
                Res = "Failed!" + ex.Message;
            }
            return(Res);
        }
示例#36
0
        private async Task <Result> SendMessage(EmailTemplate template, string bodyMessage, IEnumerable <string> mailingList)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(emailSettings.Sender, emailSettings.Username));
            message.To.AddRange(mailingList.Select(m => new MailboxAddress(string.Empty, m)));
            message.Subject = template.Subject;
            message.Body    = new TextPart(MimeKit.Text.TextFormat.Html)
            {
                Text = bodyMessage
            };
            message.Importance = template.Importance ? MessageImportance.High : MessageImportance.Normal;

            try
            {
                using (var smtpClient = new SmtpClient())
                {
                    smtpClient.AuthenticationMechanisms.Clear();
                    smtpClient.AuthenticationMechanisms.Add("NTLM");
                    smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    await smtpClient.ConnectAsync(emailSettings.Host, Convert.ToInt32(emailSettings.Port), SecureSocketOptions.Auto);

                    await smtpClient.AuthenticateAsync(new NetworkCredential(emailSettings.Username, emailSettings.Password));

                    await smtpClient.SendAsync(message);

                    await smtpClient.DisconnectAsync(true);
                }

                logger.Information("The email was successfully sent", message);
                return(Result.Ok());
            }
            catch (Exception e)
            {
                var error = $"An error occurred while sending the message: \"{message}\". Error: {e.Message}";
                return(Result.Failure(error));
            }
        }
示例#37
0
        public async Task SendLineItemStatusChangeEmail(LineItemStatusChange lineItemStatusChange, List <HSLineItem> lineItems, string firstName, string lastName, string email, EmailDisplayText lineItemEmailDisplayText)
        {
            var productsList = lineItems.Select(SendgridMappers.MapLineItemToProduct).ToList();

            var templateData = new EmailTemplate <LineItemStatusChangeData>()
            {
                Data = new LineItemStatusChangeData
                {
                    FirstName = firstName,
                    LastName  = lastName,
                    Products  = productsList,
                },
                Message = new EmailDisplayText()
                {
                    EmailSubject = lineItemEmailDisplayText?.EmailSubject,
                    DynamicText  = lineItemEmailDisplayText?.DynamicText,
                    DynamicText2 = lineItemEmailDisplayText?.DynamicText2
                }
            };

            await SendSingleTemplateEmail(_settings?.SendgridSettings?.FromEmail, email, _settings?.SendgridSettings?.LineItemStatusChangeTemplateID, templateData);
        }
示例#38
0
        public async Task <IActionResult> AddEmailTemplate([FromBody] EmailTemplateViewModel emailTemplate)
        {
            if (ModelState.IsValid)
            {
                var group = await this._unitOfWork.UserGroups.GetGroupByNameAsync(emailTemplate.GroupName);

                if (await IsGroupAdmin(group.Name))
                {
                    EmailTemplate newEmailTemplate = Mapper.Map <EmailTemplate>(emailTemplate);
                    newEmailTemplate.Group = group;
                    this._unitOfWork.EmailTemplates.Add(newEmailTemplate);
                    await this._unitOfWork.SaveChangesAsync();

                    return(new OkResult());
                }
                else
                {
                    return(new ChallengeResult());
                }
            }
            return(BadRequest(ModelState));
        }
示例#39
0
        public void ReplacesRazorInBothSubjectAndBody()
        {
            var emailTemplate = new EmailTemplate
            {
                Subject = "@Model.Subject Hello",
                Body    = "@if (Model.IsTrue) { <p>@Model.TrueMessage</p> } else { <p>@Model.FalseMessage</p> }"
            };

            var model = new
            {
                Subject      = "Integration Test",
                TrueMessage  = "It is true",
                FalseMessage = "A lie was told",
                IsTrue       = true
            };

            EmailMessage formatMessage = _emailTemplateFormatter.FormatMessage(emailTemplate, model, "*****@*****.**", "*****@*****.**", "From Me", emailTemplate.Id);

            Assert.AreEqual(model.Subject + " Hello", formatMessage.Subject);
            Assert.IsTrue(formatMessage.Body.Contains(model.TrueMessage));
            Assert.IsFalse(formatMessage.Body.Contains(model.FalseMessage));
        }
        public ActionResult Create(Shipment shipment)
        {
            shipment.ReferenceNumber      = ShipmentModel.GenerateReferenceNumber(shipment);
            shipment.ActualCollectionTime = shipment.PlannedCollectionTime;
            shipment.ActualTimeOfArrival  = shipment.PlannedETA;
            shipment.CreateDate           = shipment.ModifiedDate = DateTime.Now;
            if (ModelState.IsValid)
            {
                shipment.CreatedBy = User.Identity.Name;

                if (shipment.ReferralEnquiryID > 0)
                {
                    var enquiry = db.Enquiries.Find(shipment.ReferralEnquiryID);
                    if (enquiry == null)
                    {
                        return(RedirectToAction("Error"));
                    }
                    enquiry.Status          = Enquiry.State.CLOSED;
                    db.Entry(enquiry).State = EntityState.Modified;
                }

                db.Shipments.Add(shipment);
                db.SaveChanges();

                if (shipment.InsuranceRequired)
                {
                    shipment.Customer = db.Customers.Find(shipment.CustomerID);
                    EmailTemplate.Send(
                        "*****@*****.**",
                        "*****@*****.**",
                        "Shipment Insurance Request",
                        EmailTemplate.PerpareInsuranceRequestEmail(shipment, @"~\views\EmailTemplate\InsuranceRequestEmail.html.cshtml"),
                        true
                        );
                }
                return(RedirectToAction("Index"));
            }
            return(this.Create(shipment.CustomerID));
        }
 protected void btnAdd_Click(object sender, EventArgs e)
 {
     var  emailTemplate = new EmailTemplate();
     emailTemplate.CreatedOn = DateTime.Now;
     if (!FileUpload1.HasFile)
     {
         emailTemplate.EmailText = txtMailTemplate.InnerText;
     }
     else
     {
         emailTemplate.EmailText = UploadHtmlFile();
     }
     emailTemplate.IsDelete = false;
     emailTemplate.Name = txtName.Text;
     emailTemplate.SheetId = Convert.ToInt32(ddlSheet.SelectedValue);
     emailTemplate.Subject = txtSubjectt.Text;
     _dbScheduler.EmailTemplates.InsertOnSubmit(emailTemplate);
     _dbScheduler.SubmitChanges();
     txtMailTemplate.InnerText = "";
     txtName.Text = "";
     txtSubjectt.Text = "";
 }
示例#42
0
        public Email(EmailTemplate emailTemplate)
        {
            EmailTemplate = emailTemplate;
            State         = EmailState.Draft;

            foreach (var emailTemplatePart in emailTemplate.Parts)
            {
                switch (emailTemplatePart)
                {
                case HtmlEmailTemplatePart htmlEmailTemplatePart:
                    _parts.Add(new HtmlEmailPart(htmlEmailTemplatePart.Html));
                    break;

                case VariableEmailTemplatePart variableEmailTemplatePart:
                    _parts.Add(new VariableEmailPart(variableEmailTemplatePart.VariableType, variableEmailTemplatePart.Value));
                    break;

                default:
                    throw new EmailMakerException("Unsupported email template part: " + emailTemplatePart.GetType());
                }
            }
        }
        public EmailTemplate Parse(string readAllText)
        {
            XDocument xdoc = XDocument.Parse(readAllText);

                var xml = xdoc.Element(XName.Get("emailTemplate", ns));
                var template = new EmailTemplate()
                                   {
                                       Name = xml.Element(XName.Get("name", ns)).Value,
                                       From = xml.Element(XName.Get("from", ns)).Value,
                                       Subject = xml.Element(XName.Get("subject", ns)).Value,
                                       Text = xml.Element(XName.Get("text", ns)) != null
                                       ? xml.Element(XName.Get("text", ns)).Value
                                       : null,
                                       Html = xml.Element(XName.Get("html", ns)) != null
                                       ? xml.Element(XName.Get("html", ns)).Value
                                       : null,
                                       Culture = xml.Element(XName.Get("culture", ns)) != null
                                       ? xml.Element(XName.Get("culture", ns)).Value
                                       : null
                                   };
                return template;
        }
        public void Context()
        {
            _persistEmailTemplate();

            var queryHandler = new GetAllEmailTemplateQueryHandler(UnitOfWork);

            _result = queryHandler.Execute <EmailTemplateDetailsDto>(new GetAllEmailTemplateQuery {
                UserId = _user.Id
            });

            void _persistEmailTemplate()
            {
                _user = UserBuilder.New.Build();
                UnitOfWork.Save(_user);
                _emailTemplate = EmailTemplateBuilder.New
                                 .WithInitialHtml("html")
                                 .WithName("template name")
                                 .WithUserId(_user.Id)
                                 .Build();
                UnitOfWork.Save(_emailTemplate);
            }
        }
        /// <summary>
        /// Sets the serial key for this digital good
        /// </summary>
        /// <param name="serialKeyData">Serial key to set</param>
        /// <param name="sendFulfillmentEmail">If <b>true</b> fulfillment email is sent</param>
        public void SetSerialKey(string serialKeyData, bool sendFulfillmentEmail)
        {
            if (IsSerialKeyAcquired())
            {
                if (this.SerialKeyData == serialKeyData)
                {
                    return;
                }
            }

            this.SerialKeyData = serialKeyData;

            if (sendFulfillmentEmail && !string.IsNullOrEmpty(serialKeyData))
            {
                //initiate fulfillment email
                EmailTemplate template = EmailTemplateDataSource.Load(DigitalGood.FulfillmentEmailId);
                if (template != null)
                {
                    SendEmail(template);
                }
            }
        }
        public IActionResult OnGet()
        {
            var claimsIdentity = (ClaimsIdentity)User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            var    user = _unitofwork.ApplicationUser.GetFirstOrDefault(i => i.Id == claim.Value);
            string s    = string.Join("  |  ", RecoveryCodes);


            EmailTemplate emailTemplate = _db.EmailTemplates.Where(e => e.Id == Convert.ToInt32(EnEmailTemplate.TwoFAmail)).FirstOrDefault();

            emailTemplate.Content = emailTemplate.Content.Replace("###Name###", user.Name);
            emailTemplate.Content = emailTemplate.Content.Replace("###Code###", s);
            _emailSender.SendEmailAsync(user.Email, emailTemplate.Subject, emailTemplate.Content);

            if (RecoveryCodes == null || RecoveryCodes.Length == 0)
            {
                return(RedirectToPage("./TwoFactorAuthentication"));
            }

            return(Page());
        }
        public async Task SaveAsync(EmailTemplate template)
        {
            var dbTemplate = await FindByNameAsync(template.TemplateName);

            using var trans = await db.Database.BeginTransactionAsync();

            if (dbTemplate != null)
            {
                template.Id = dbTemplate.Id;
                db.EmailTemplates.Remove(dbTemplate);
                await db.SaveChangesAsync();
            }
            else
            {
                template.Id = Guid.NewGuid().ToString();
            }
            await db.EmailTemplates.AddAsync(template);

            await db.SaveChangesAsync();

            await trans.CommitAsync();
        }
示例#48
0
        public static bool AcceptRequisition(int employeeID, int requisitionID, String remarks)
        {
            bool result = false;

            LussisEntities context     = new LussisEntities();
            Employee       approver    = context.Employees.Where(emp => emp.EmpNo == employeeID).FirstOrDefault();
            Requisition    requisition = context.Requisitions.Where(req => req.ReqNo == requisitionID).FirstOrDefault();

            // Process only if all values are present in the database
            if (approver != null && requisition != null)
            {
                requisition.Remarks      = remarks;
                requisition.ApprovedBy   = approver.EmpNo;
                requisition.DateReviewed = DateTime.Now.Date;
                requisition.Status       = "Approved";

                context.SaveChanges();

                // Send Email
                EmailBackend.sendEmailStep(
                    requisition.EmployeeWhoIssued.Email,
                    EmailTemplate.GenerateRequisitionStatusChangedEmailSubject(
                        requisition.ReqNo.ToString(),
                        requisition.Status),
                    EmailTemplate.GenerateRequisitonStatusChangedEmail(
                        requisition.EmployeeWhoIssued.EmpName,
                        requisition.ReqNo.ToString(),
                        approver.EmpName,
                        requisition.Status,
                        requisition.Remarks)
                    );

                // Mark as sucessful
                result = true;
            }

            // Return operation result
            return(result);
        }
示例#49
0
        private EmailMessage Format(List <EmailJob> jobs, EmailTemplate template, App app, User user,
                                    List <EmailFormattingError> errors, bool noCache)
        {
            var context = CreateContext(jobs.Select(x => x.Notification), app, user);

            var subject = string.Empty;

            if (!string.IsNullOrWhiteSpace(template.Subject))
            {
                subject = FormatSubject(template.Subject, context, errors) !;
            }

            string?bodyText = null;

            if (!string.IsNullOrWhiteSpace(template.BodyText))
            {
                bodyText = FormatText(template.BodyText, context, jobs, errors) !;
            }

            string?bodyHtml = null;

            if (!string.IsNullOrWhiteSpace(template.BodyHtml))
            {
                bodyHtml = FormatBodyHtml(template.BodyHtml, context, jobs, user.EmailAddress !, errors, noCache) !;
            }

            var message = new EmailMessage
            {
                BodyHtml  = bodyHtml,
                BodyText  = bodyText,
                FromEmail = template.FromEmail.OrDefault(jobs[0].FromEmail !),
                FromName  = template.FromEmail.OrDefault(jobs[0].FromName !),
                Subject   = subject,
                ToEmail   = user.EmailAddress !,
                ToName    = user.FullName,
            };

            return(message);
        }
        public async void SendRecoupmentProcessedEmail(
            EmailRequestWithUrl <RecoupmentProcessingNotificationViewModel> emailRequest,
            EmailTemplate templateType,
            string subject,
            bool appendFooter = true)
        {
            var body = _emailer.RenderTemplate(templateType, emailRequest) + (appendFooter ? _emailer.RenderTemplate("GeneralMailFooter") : string.Empty);

            using (var mailMessage = new MailMessage())
            {
                mailMessage.Body       = body;
                mailMessage.IsBodyHtml = true;
                mailMessage.Subject    = subject;
                if (emailRequest.From != null)
                {
                    mailMessage.From = emailRequest.From;
                }
                emailRequest.To.ToList().ForEach(mailMessage.To.Add);
                emailRequest.CC.ToList().ForEach(mailMessage.CC.Add);
                await _emailer.SendEmailAsync(mailMessage);
            }
        }
示例#51
0
        public async Task SendForgotPwd(ForgotPasswordRes req)
        {
            var email = new EmailTemplate
            {
                To = To,
                //To = "*****@*****.**",
                Bcc             = Bcc,
                Subject         = "EMECI - Recordatorio de contraseña",
                Title           = "Protege tu salud y la de tu familia a través de EMECI",
                TypeEmailToSend = EmailTemplate.TypeEmail.forgotPwd,
                ForgotPwd       = req
            };

            try
            {
                await email.SendAsync();
            }
            catch (Exception ex)
            {
                Log.Write($"EmailService, SendForgotPwd=> {ex.Message}");
            }
        }
示例#52
0
        private async Task <string?> FormatHtml(EmailTemplate template, TemplateContext context, IEnumerable <UserNotification> notifications, bool noCache)
        {
            var markup = template.BodyHtml;

            if (string.IsNullOrWhiteSpace(markup))
            {
                return(markup);
            }

            var result = RenderTemplate(markup, context, noCache);

            var html = await MjmlToHtmlAsync(result);

            if (string.IsNullOrWhiteSpace(html))
            {
                return(html);
            }

            ValidateResult(markup, html, notifications);

            return(html);
        }
示例#53
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            EmailTemplateService emailTemplateService = new EmailTemplateService();
            EmailTemplate emailTemplate;

            int emailTemplateId = int.Parse(hfEmailTemplateId.Value);

            if ( emailTemplateId == 0 )
            {
                emailTemplate = new EmailTemplate();
                emailTemplateService.Add( emailTemplate, CurrentPersonId );
            }
            else
            {
                emailTemplate = emailTemplateService.Get( emailTemplateId );
            }

            emailTemplate.Category = tbCategory.Text;
            emailTemplate.Title = tbTitle.Text;
            emailTemplate.From = tbFrom.Text;
            emailTemplate.To = tbTo.Text;
            emailTemplate.Cc = tbCc.Text;
            emailTemplate.Bcc = tbBcc.Text;
            emailTemplate.Subject = tbSubject.Text;
            emailTemplate.Body = tbBody.Text;

            if ( !emailTemplate.IsValid )
            {
                // Controls will render the error messages
                return;
            }

            emailTemplateService.Save( emailTemplate, CurrentPersonId );
            BindFilter();
            BindGrid();
            pnlDetails.Visible = false;
            pnlList.Visible = true;
        }
		///<summary>Inserts one EmailTemplate into the database.  Provides option to use the existing priKey.</summary>
		public static long Insert(EmailTemplate emailTemplate,bool useExistingPK){
			if(!useExistingPK && PrefC.RandomKeys) {
				emailTemplate.EmailTemplateNum=ReplicationServers.GetKey("emailtemplate","EmailTemplateNum");
			}
			string command="INSERT INTO emailtemplate (";
			if(useExistingPK || PrefC.RandomKeys) {
				command+="EmailTemplateNum,";
			}
			command+="Subject,BodyText) VALUES(";
			if(useExistingPK || PrefC.RandomKeys) {
				command+=POut.Long(emailTemplate.EmailTemplateNum)+",";
			}
			command+=
				 "'"+POut.String(emailTemplate.Subject)+"',"
				+"'"+POut.String(emailTemplate.BodyText)+"')";
			if(useExistingPK || PrefC.RandomKeys) {
				Db.NonQ(command);
			}
			else {
				emailTemplate.EmailTemplateNum=Db.NonQ(command,true);
			}
			return emailTemplate.EmailTemplateNum;
		}
        public void TemplateProcessor_TokensAreReplaced()
        {
            EmailTemplate template = new EmailTemplate()
                                         {
                                             Name = "template name",
                                             Subject = "subject {token1}",
                                             Text = "text {token2}",
                                             Html = "html {token3}"
                                         };
            TemplateProcessor processor = new TemplateProcessor();

            var package = processor.CreatePackageFromTemplate(template,
                                    new NameValueCollection()
                                        {
                                            {"token1", "replacementvalue1"},
                                            {"token2", "replacementvalue2"},
                                            {"token3", "replacementvalue3"}
                                        });

            Assert.That(package.Subject, Is.StringMatching("subject replacementvalue1"));
            Assert.That(package.Text, Is.StringMatching("text replacementvalue2"));
            Assert.That(package.Html, Is.StringMatching("html replacementvalue3"));
        }
示例#56
0
 public static string AddNewEmailTemplate(PanelPreferences preferences, EmailTemplate emailTemplate)
 {
     var communicationViewUrl = new Uri(preferences.PanelAdminUrl + "CommunicationsManagementView.aspx");
     string communicationViewFormParams = GetCommunicationViewFormParams(emailTemplate);
     var bytes = Encoding.ASCII.GetBytes(communicationViewFormParams);
     var communicationsRequest = AutomationHelper.CreatePost(communicationViewUrl, preferences.CookieJar);
     communicationsRequest.Referer = preferences.PanelAdminUrl + "CommunicationsManagementView.aspx";
     communicationsRequest.ContentLength = bytes.Length;
     using (Stream os = communicationsRequest.GetRequestStream())
     {
         os.Write(bytes, 0, bytes.Length);
     }
     var response = (HttpWebResponse)communicationsRequest.GetResponse();
     string pageSource = String.Empty;
     using (var reader = new StreamReader(response.GetResponseStream()))
     {
         pageSource = reader.ReadToEnd();
     }
     string cookies = response.Headers["Set-Cookie"];
     preferences.CookieJar.VcAuthentication = AutomationHelper.GetVcAuthentication(cookies);
     preferences.CookieJar.UniqueRequestId = AutomationHelper.GetReqId(cookies);
     response.Close();
     return pageSource;
 }
    //Handle button click event
    public void SendActivation_Click(Object sender, CommandEventArgs e)
    {
        if (e.CommandName == "SendActivation")
        {
            foreach (RepeaterItem ri in UserUnActivatedAccount.Items)
            {
                CheckBox chkID = (CheckBox)ri.FindControl("chkID");
                Label User_name = (Label)ri.FindControl("User_name");
                Label User_email = (Label)ri.FindControl("User_email");
                Label User_guid = (Label)ri.FindControl("User_guid");
                if (chkID != null)
                {
                    if (chkID.Checked)
                    {
                        string UserName = User_name.Text.Trim();
                        string UserEmail = User_email.Text.Trim();
                        string UserGuid = User_guid.Text.Trim();

                        //Unfortunately, sending multiple emails to different recipients does not work in this code.
                        //If you can figure out other solution, just drop me an email.
                        //Instantiate emailtemplate object
                        EmailTemplate SendeMail = new EmailTemplate();

                        SendeMail.LyricEmail = UserEmail;

                        //Send the activation link
                        SendeMail.SendActivationLink(UserName, UserGuid);

                        SendeMail = null;

                        Response.Redirect("confirmsendactivation.aspx");
                    }
                }
            }
        }
    }
    public void SendingRecipe(Object s, EventArgs e)
    {
        //Instantiate emailtemplate object
        EmailTemplate SendeMail = new EmailTemplate();

        SendeMail.ItemID = (int)Util.Val(Request.QueryString["id"]);
        SendeMail.ItemName = Request.QueryString["n"].ToString();

        //Filters harmful scripts from input string.
        SendeMail.SenderName = Util.FormatTextForInput(Request.Form["txtFromName"]);
        SendeMail.SenderEmail = Util.FormatTextForInput(Request.Form["txtFromEmail"]);
        SendeMail.RecipientEmail = Util.FormatTextForInput(Request.Form["txtToEmail"]);
        SendeMail.RecipientName = Util.FormatTextForInput(Request.Form["toname"]);

        SendeMail.SendEmailRecipeToAFriend();

        Panel1.Visible = false;

        lblsentmsg.Text = "Your message has been sent to " + SendeMail.RecipientEmail + ".";

        //Release allocated memory
        SendeMail = null;
        Util = null;
    }
示例#59
0
 public StandardEmail(EmailTemplate template)
 {
     Properties = new Dictionary<string, string>();
     TemplatePath = GetTemplatePath(Enum.GetName(typeof (EmailTemplate), template));
 }
示例#60
0
 private static string GetEmailEditViewFormParams(EmailTemplate emailTemplate, string eid)
 {
     string callBackMethod = "ServerSideLoadEmailById";
     string Cart_Callback_Method_Param = eid;
     string formParameters = String.Format("Cart_Callback_Method={0}&Cart_Callback_Method_Param={1}", callBackMethod, Cart_Callback_Method_Param);
     return formParameters;
 }