/*internal static void SendPasswordResetEmail(string email, string passwordResetToken)
        {
            string resetLink = "<a href='" + WebSettings.WebsiteDomain +
                   "Account/ResetPassword?user="******"&ver=" + passwordResetToken + "'>Reset Password</a>";
            try
            {
                MailDefinition mail = new MailDefinition();
                mail.BodyFileName = WebSettings.PasswordResetEmailTemplate;
                mail.Subject = WebSettings.PasswordResetEmailSubject;
                mail.From = WebSettings.SmtpEmailUsername;
                mail.IsBodyHtml = true;

                Dictionary<string, string> replacemets = new Dictionary<string, string>();
                replacemets.Add("#RESETLINK#", ValueToString(resetLink));

                MailMessage message = mail.CreateMailMessage(email, replacemets, new System.Web.UI.Control());

                EmailHandler handler = new EmailHandler(message);
                Thread sendEmail = new Thread(new ThreadStart(handler.SendEmail));
                sendEmail.Start();
            }
            catch (Exception)
            {
                throw;
            }
        }*/
        internal static void SendEnquiryEmail(EnquiryModel model)
        {
            try
            {
                MailDefinition mail = new MailDefinition();

                mail.From = WebSettings.EmailUsername;
                mail.Subject = WebSettings.EnquiryEmailSubject;
                mail.BodyFileName = WebSettings.EnquiryEmailTemplate;
                mail.IsBodyHtml = true;

                //ListDictionary replacements = ResetLinkToDictionary(order);
                Dictionary<string, string> replacements = new Dictionary<string, string>();
                EmailSender sender = new EmailSender();

                replacements = sender.EnquiryToDictionary(model);

                MailMessage message = mail.CreateMailMessage(WebSettings.AdminEmail, replacements, new System.Web.UI.Control());

                EmailHandler handler = new EmailHandler(message);
                Thread thread = new Thread(new ThreadStart(handler.SendEmail));
                thread.Start();
                // LoggerService.Info(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], "Enquiry email sent to " + WebSettings.AdminEmail);

            }
            catch (Exception)
            {
                // LoggerService.Error(e.Message, "Stack Trace: " + e.StackTrace, "");
                throw;
            }
        }
        protected void lbSend_Click(object sender, EventArgs e)
        {
            SmtpClient client = new SmtpClient(); //host and port picked from web.config
            client.EnableSsl = true;
            MailDefinition message = new MailDefinition();

            message.BodyFileName = @"~\EmailTemplate\MiriMargolinContact.htm";
            message.IsBodyHtml = true;
            message.From = "*****@*****.**";
            message.Subject = "MiriMargolin - Contact Us Form";
            ListDictionary replacements = new ListDictionary();
            replacements.Add("<% Name %>", this.txtName.Text);
            replacements.Add("<% PhoneOrEmail %>", this.txtPhoneOrEmail.Text);
            replacements.Add("<% Message %>", this.txtMessage.Text);
            MailMessage msgHtml = message.CreateMailMessage(RECIPIENTS, replacements, new LiteralControl());
            try
            {
                client.Send(msgHtml);
                this.lblMsg.Text = "Your message has been sent and will be address shortly";
                this.lbSend.Enabled = false;
            }
            catch (Exception)
            {
                this.lblMsg.Text = "There was a problem to send an email.";
            }
        }
Exemple #3
0
        private void sendEmailToAdmin()
        {
            //Sending out emails to Admin

            MailDefinition md_2 = new MailDefinition();
            md_2.From = ConfigurationManager.AppSettings["MailFrom"];
            md_2.IsBodyHtml = true;
            md_2.Subject = ConfigurationManager.AppSettings["emailSubject"];

            ListDictionary replacements = new ListDictionary();

            replacements.Add("<%client_name%>", (string)(Session["client_name"]));
            replacements.Add("<%client_church_name%>", (string)(Session["client_church_name"]));
            replacements.Add("<%client_address%>", (string)(Session["client_address"]));
            replacements.Add("<%client_city%>", (string)(Session["client_city"]));
            replacements.Add("<%client_state%>", (string)(Session["client_state"]));
            replacements.Add("<%client_Zip%>", (string)(Session["client_Zip"]));
            replacements.Add("<%client_phone%>", (string)(Session["client_phone"]));
            replacements.Add("<%client_email%>", (string)(Session["client_email"]));
            replacements.Add("<%Payment_Amount%>", (string)(Session["Payment_Amount"]));
            replacements.Add("<%client_roommate1%>", (string)(Session["client_roommate1"]));
            replacements.Add(" <%client_registrationType%>", (string)(Session["client_registrationType"]));

            string body = String.Empty;

            using (StreamReader sr_2 = new StreamReader(Server.MapPath(ConfigurationManager.AppSettings["emailPath"] + "registration.txt")))
            {
                body = sr_2.ReadToEnd();
            }

            MailMessage msg_2 = md_2.CreateMailMessage(ConfigurationManager.AppSettings["management_Email"], replacements, body, new System.Web.UI.Control());

            SmtpClient client = new SmtpClient();
            client.Send(msg_2);
        }
Exemple #4
0
 public static void Send(String to, String body, String Subject, IDictionary replacements = null)
 {
     init();
     char[] c = { ',', ';', ':' };
     String[] To = to.Split(c);
     for (int i = 0; i < To.Length; i++)
     {
         MailDefinition m = new MailDefinition();
         if (!replacements.Contains("\n"))
         {
             replacements.Add("\n", "<br/>");
         }
         m.IsBodyHtml = true;
         m.Subject = Subject;
         m.From = "*****@*****.**";
         try
         {
             mails.AddLast(m.CreateMailMessage(To[i], replacements, body, new System.Web.UI.Control()));
         }
         catch (Exception)//TODO
         { };
     }
     if (!isSending)
     {
         next(null, null);
     }
 }
Exemple #5
0
        private void SendManagementEmails()
        {
            //Sending out emails

            MailDefinition md = new MailDefinition();
            md.From = ConfigurationManager.AppSettings["MailFrom"];
            md.IsBodyHtml = true;
            md.Subject = ConfigurationManager.AppSettings["emailSubjectContact"];

            ListDictionary replacements = new ListDictionary();

            replacements.Add("<%client_name%>", (string)(Session["client_name"]));
            replacements.Add("<%client_phone%>", (string)(Session["client_phone"]));
            replacements.Add("<%client_email%>", (string)(Session["client_email"]));
            replacements.Add("<%client_message%>", (string)(Session["client_message"]));

            string body = String.Empty;

            using (StreamReader sr = new StreamReader(Server.MapPath(ConfigurationManager.AppSettings["emailPath"] + "contact.txt")))
            {
                body = sr.ReadToEnd();
            }

            MailMessage msg = md.CreateMailMessage(ConfigurationManager.AppSettings["mecene_Email"], replacements, body, new System.Web.UI.Control());

            SmtpClient sc = new SmtpClient();
            sc.Send(msg);
        }
Exemple #6
0
        private static MailMessage CreateMailMessage(string email, string userName, string password, MailDefinition mailDefinition, string defaultBody, Control owner)
        {
            ListDictionary replacements = new ListDictionary();

            if (mailDefinition.IsBodyHtml)
            {
                userName = HttpUtility.HtmlEncode(userName);
                password = HttpUtility.HtmlEncode(password);
            }
            replacements.Add(@"<%\s*UserName\s*%>", userName);
            replacements.Add(@"<%\s*Password\s*%>", password);
            if (string.IsNullOrEmpty(mailDefinition.BodyFileName) && (defaultBody != null))
            {
                return(mailDefinition.CreateMailMessage(email, replacements, defaultBody, owner));
            }
            return(mailDefinition.CreateMailMessage(email, replacements, owner));
        }
Exemple #7
0
        public static void SendRegistration(string message, string hostAddress, string link, string toEmailAdress)
        {
            message = message.Replace("href=\"/", string.Format("href=\"{0}", hostAddress));
            message = message.Replace("src=\"/", string.Format("src=\"{0}", hostAddress));
            message = message.Replace("<html>", string.Format("<html>Ser meddelandet konstigt ut? Öppna följande adress i en webbläsare: {0}<br/><br/>", link));

            var mailDefinition = new MailDefinition
                              {
                                  From = ConfigurationManager.AppSettings["MailSender"],
                                  Subject = ConfigurationManager.AppSettings["MailSubject"],
                                  IsBodyHtml = true
                              };
            // Send to the registrator
            SmtpClient.Send(mailDefinition.CreateMailMessage(toEmailAdress, null, message, new Control()));
            // Send to KMS
            SmtpClient.Send(mailDefinition.CreateMailMessage(ConfigurationManager.AppSettings["MailList"], null, message, new Control()));
        }
        public void Run()
        {
            mLog.Info("Email ForecastCutOffDate has started.");
            try
            {
                var forecastCutOffDate = GetForecastCutOffDate();
                var users = GetUsersForForecastCutOffDate(forecastCutOffDate);

                if (users.Any())
                {
                    var emailsTo = users.Where(x => x.EmailAddress != null).Select(x => x.EmailAddress).Distinct().ToArray();

                    //FROM
                    string emailAdminAccount = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailAdminAccount);

                    //Subject
                    string subject = string.Format("Reminder: Forecasts Due in CMS by {0}", forecastCutOffDate);

                    SmtpClient client = new SmtpClient();
                    client.Host = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailMailHost);

                    MailDefinition md = new MailDefinition();
                    md.Subject = subject;
                    md.From = emailAdminAccount;
                    var emails = string.Join(",", emailsTo).TrimEnd(',');

                    MailMessage message = md.CreateMailMessage(emails, null, new System.Web.UI.Control());
                    message.IsBodyHtml = true;

                    message.Body = String.Format("You have an open Project assigned to you in CMS. Please ensure you have entered your Forecasts by {0}.{1}{1}Regards, The Finance Team",
                        forecastCutOffDate, Environment.NewLine);

                    //SEND!
                    string testEmail = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailDefaultTest);

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

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

                    mLog.Verbose("{0}", message.Body);
                    client.Send(message);
                }

            }
            catch (Exception ex)
            {

                mLog.Error("", ex, "Error occured in ForecastCutOffDate");
            }
            finally
            {
                mLog.Info("ForecastCutOffDate has finished.");
            }
        }
Exemple #9
0
        public void Send(string from, IEnumerable<string> tos, IEnumerable<string> ccs, IEnumerable<string> bccs, LoginUser user, string loginurl, string templatepath, DateTime? dateTime)
        {
            var client = new SmtpClient();

            var mailDefinition = new MailDefinition();
            mailDefinition.Priority = MailPriority.High;
            mailDefinition.From = "*****@*****.**";
            mailDefinition.IsBodyHtml = true;
            mailDefinition.Subject = "[ATM]Notifikasi Pendaftaran";
            mailDefinition.BodyFileName = templatepath;

            var ldReplacement = new ListDictionary();
            if (dateTime.HasValue)
                ldReplacement.Add("<%RegistrationDateTime%>", string.Format("{0:dd/MM/yyyy}", dateTime.Value));
            else
                ldReplacement.Add("<%RegistrationDateTime%>", string.Format("{0:dd/MM/yyyy}", user.CreatedDt));

            ldReplacement.Add("<%FullName%>", user.FullName.Trim().ToUpper());
            ldReplacement.Add("<%UserName%>", user.UserName.Trim().ToUpper());
            ldReplacement.Add("<%Password%>", user.Password);
            ldReplacement.Add("<%LoginUrl%>", loginurl);
            var mail = new MailMessage();
            mail = mailDefinition.CreateMailMessage(user.Email, ldReplacement, new Control());
            mail.From = new MailAddress(from, "No Reply");

            if (null != ccs)
                foreach (var cc in ccs.ToList().SelectMany(Spliter))
                {
                    mail.CC.Add(new MailAddress(cc, ""));
                }

            if (null != bccs)
                foreach (var bcc in bccs.ToList().SelectMany(Spliter))
                {
                    mail.Bcc.Add(new MailAddress(bcc, ""));
                }

            mail.Subject = "[ATM]Notifikasi Pendaftaran";
            mail.IsBodyHtml = true;
            AlternateView htmlView = null;
            htmlView = AlternateView.CreateAlternateViewFromString(mail.Body, null, "text/html");
            mail.AlternateViews.Add(htmlView);

            if (null != tos)
                foreach (var recipient in tos.ToList().SelectMany(Spliter))
                {
                    mail.To.Add(new MailAddress(recipient));
                    try
                    {
                        client.Send(mail);
                    }
                    catch (Exception ex)
                    {
                    }
                }
        }
Exemple #10
0
        internal void SendSharePurchaseInvoice(ShareModel addedShare)
        {
            MailDefinition mail = new MailDefinition();
            mail.BodyFileName = "~/Content/EmailTemplate/Invoice.html";
            mail.Subject = "ETC Canada - Confirmation of Share Purchase " + DateTime.Today.ToShortDateString();
            ListDictionary replacements = ShareToDictionary(addedShare);
            System.Net.Mail.MailMessage message = mail.CreateMailMessage(addedShare.Email, replacements, new System.Web.UI.Control());
            List<string> adminUserEmails = GetAllAdminUsersEmailAddress();
            adminUserEmails.ForEach(x => message.CC.Add(x));
            message.IsBodyHtml = true;

            EmailHandler handler = new EmailHandler(message);
            Thread thread = new Thread(new ThreadStart(handler.SendEmail));
            thread.Start();
        }
Exemple #11
0
        private static MailMessage CreateMailMessage(string email, string userName, string password,
                                                     MailDefinition mailDefinition, string defaultBody,
                                                     Control owner)
        {
            ListDictionary replacements = new ListDictionary();

            // Need to html encode the username and password if the body is HTML
            if (mailDefinition.IsBodyHtml)
            {
                userName = HttpUtility.HtmlEncode(userName);
                password = HttpUtility.HtmlEncode(password);
            }
            replacements.Add(_userNameReplacementKey, userName);
            replacements.Add(_passwordReplacementKey, password);

            if (String.IsNullOrEmpty(mailDefinition.BodyFileName) && defaultBody != null)
            {
                return(mailDefinition.CreateMailMessage(email, replacements, defaultBody, owner));
            }
            else
            {
                return(mailDefinition.CreateMailMessage(email, replacements, owner));
            }
        }
Exemple #12
0
        public bool SendMail(string fromAdd, string  toAdd, string subject, string body, 
            ListDictionary replacements, bool isBodyHtml = true)
        {
            MailDefinition md = new MailDefinition();
            md.From = fromAdd;
            md.IsBodyHtml = isBodyHtml;
            md.Subject = subject;

            using (var message =
                        md.CreateMailMessage(toAdd, replacements, body, new System.Web.UI.Control()))
            {
                this.SMTPClient.Send(message);
            }
            return true;
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            string userName = Membership.GetUserNameByEmail(this.txtEmail.Text);

            if (!string.IsNullOrEmpty(userName))
            {
                MembershipUser membershipUser = Membership.GetUser(userName);
                bool isLockedOut = membershipUser.IsLockedOut;
                if (isLockedOut)
                {
                    membershipUser.UnlockUser();
                }
                Random r = new Random();
                string newPassword = string.Format("{0}{1}", userName, r.Next(1, 10));
                membershipUser.ChangePassword(membershipUser.ResetPassword(), newPassword);
                SmtpClient client = new SmtpClient(); //host and port picked from web.config
                client.EnableSsl = true;
                MailDefinition message = new MailDefinition();
                message.BodyFileName = @"~\EmailTemplate\RecoverPassword.htm";
                message.IsBodyHtml = true;
                message.From = "*****@*****.**";
                message.Subject = "StrongerOrg - Password recovery";
                ListDictionary replacements = new ListDictionary();
                replacements.Add("<% UserName %>", userName);
                replacements.Add("<% NewPassword %>", newPassword);
                MailMessage msgHtml = message.CreateMailMessage(this.txtEmail.Text, replacements, new LiteralControl());
                try
                {
                    client.Send(msgHtml);
                    this.lblMsg.Text = "Your new password has been sent to your email";
                    this.btnSend.Enabled = false;
                }

                catch (Exception ex)
                {
                    this.lblMsg.Text = "There was a problem to send an email.";
                    throw ex; //or return the error by some other means, say on a label

                }
            }
            else
            {
                this.lblMsg.Text = "No email found, please try different email";
            }
        }
Exemple #14
0
        public static void SendWelcomeMessage(UserViewModel userProfile)
        {
            var mailDefinition = new MailDefinition
                {
                    From = "*****@*****.**",
                    Subject = "Welcome to Navasthala",
                    IsBodyHtml = true
                };
            var replacements = new ListDictionary
                {
                    {"<%LastName%>", userProfile.LastName},
                    {"<%UserName%>", userProfile.UserName}
                };

            var path = AppDomain.CurrentDomain.BaseDirectory + @"\Mail\WelcomeMail.html";
            var body = System.IO.File.ReadAllText(path);
            var mail = mailDefinition.CreateMailMessage(userProfile.Email,replacements,body,new Control());
            GetSmtpServer().Send(mail);
        }
Exemple #15
0
        public static void SendPasswordResetMail(string token, UserViewModel userProfile)
        {
            var mailDefinition = new MailDefinition
            {
                From = "*****@*****.**",
                Subject = "Password reset mail",
                IsBodyHtml = true
            };
            var replacements = new ListDictionary
                {
                    {"<%LastName%>", userProfile.LastName},
                    {"<%Token%>", token}
                };

            var path = AppDomain.CurrentDomain.BaseDirectory + @"\Mail\PasswordResetMail.html";
            var body = System.IO.File.ReadAllText(path);
            var mail = mailDefinition.CreateMailMessage(userProfile.Email, replacements, body, new Control());
            GetSmtpServer().Send(mail);
        }
        public void NewPostEmail(IEnumerable<Subscription> Subs, Post ThePost, Thread thread, string PostURL)
        {
            ListDictionary replacements = new ListDictionary();
            string AutoFromEmail = SiteConfig.AutomatedFromEmail.Value;

            MailDefinition md = new MailDefinition();

            md.BodyFileName = EmailTemplates.GenerateEmailPath(EmailTemplates.NewThreadReply);
            md.IsBodyHtml = true;
            md.From = AutoFromEmail;
            md.Subject = "Reply to Thread '" + thread.Title + "' - " + SiteConfig.BoardName.Value;

            replacements.Add("{REPLY_USERNAME}", ThePost.User.Username);
            replacements.Add("{REPLY_TEXT}", ThePost.Text);
            replacements.Add("{THREAD_TITLE}", thread.Title);
            replacements.Add("{POST_URL}", PostURL);
            replacements.Add("{BOARD_URL}", SiteConfig.BoardURL.Value);
            replacements.Add("{BOARD_NAME}", SiteConfig.BoardName.Value);

            System.Web.UI.Control ctrl = new System.Web.UI.Control { ID = "Something" };

            MailMessage message = md.CreateMailMessage("*****@*****.**", replacements, ctrl);

            //Send the message
            SmtpClient client = Settings.GetSmtpClient();

            foreach (Subscription s in Subs)
            {
                if (s.UserID == ThePost.UserID) continue;
                User u = s.User;
                message.To.Clear();
                message.To.Add(u.Email);
                try
                {
                    System.Threading.ThreadPool.QueueUserWorkItem(state => client.Send(message));
                }
                catch
                {
                }
            }
        }
        private void SendMail()
        {
            string company = txtCompanyName.Text;
            string email = txtEmail.Text;

            MailDefinition md = new MailDefinition();
            md.BodyFileName = "~/MailTemplates/SeminarRegistration.htm";

            Dictionary<string, string> d = new Dictionary<string, string>();

            string jobAction = "";
            switch (ddlFirmAction.SelectedValue)
            {
                case "1":
                    jobAction = "Брендовая розница";
                    break;
                case "2":
                    jobAction = "Медийное агентство";
                    break;
                case "3":
                    jobAction = "Маркетинговое агентство";
                    break;
                case "4":
                    jobAction = "Туристическое агентство";
                    break;
                case "5":
                    jobAction = "Юридическая компания";
                    break;
                case "6":
                    jobAction = "Другие профессиональные услуги";
                    break;
            }
            d.Add("<%Email%>", email);
            d.Add("<%JobAction%>", jobAction);
            d.Add("<%CompanyName%>", company);
            d.Add("<%Name%>", txtFio.Text);
            d.Add("<%JobTitle%>", txtJobTitle.Text);
            d.Add("<%Site%>", txtSite.Text);

            md.IsBodyHtml = true;

            ContactFormsCache forms = new ContactFormsCache();
            string formName = "SeminarRegistration";

            ContactForm form = forms.GetByName(formName);

            if (form == null)
                throw new InvalidOperationException(string.Format("Can not find settings for form {0}", formName));

            string subject = form.Subject;
            string to = form.To;
            string cc = form.CC;

            md.Subject = string.Format(subject, company);

            if (!string.IsNullOrEmpty(cc))
            {
                md.CC = cc;
            }

            MailMessage message = md.CreateMailMessage(to, d, this);

            SmtpClient sc = new SmtpClient();

            sc.Send(message);
        }
Exemple #18
0
        /// <summary>
        /// Sends an Email Template
        /// </summary>
        /// <param name="From">From Email Address</param>
        /// <param name="To">To Email Address</param>
        /// <param name="Subject">Email Subject</param>
        /// <param name="TemplatePath">Template Physical Path</param>
        /// <param name="ItemsList">List of all key/value items to be replaced in the template</param>
        /// <returns>true if succeeded, false otherwise</returns>
        public static bool SendMailTemplate(string From, string To, string Subject, string TemplatePath, List<KeyValue> ItemsList, System.Web.UI.Control Owner)
        {
            bool result = false;
            try
            {
                if (!string.IsNullOrEmpty(From) && !string.IsNullOrEmpty(To) && ItemsList != null && ItemsList.Count > 0)
                {
                    MailDefinition definition = new MailDefinition();

                    definition.BodyFileName = TemplatePath;
                    definition.From = From;
                    definition.Subject = Subject;
                    definition.IsBodyHtml = false;

                    ListDictionary replacements = new ListDictionary();
                    foreach (KeyValue item in ItemsList)
                    {
                        replacements.Add(item.Key, item.Value);
                    }

                    SmtpClient mailOperator = new SmtpClient();
                    mailOperator.Send(definition.CreateMailMessage(To, replacements, Owner));

                    result = true;
                }
            }
            catch (Exception error)
            {
                throw error;
            }
            return result;
        }
Exemple #19
0
 /// <summary>
 /// Create a mailmessage from a file with an e-mail template.
 /// </summary>
 /// <param name="emailPathName">The email path, excluding 1) the application path prefix and 2) the culture code + '.html' postfix.</param>
 /// <param name="replacements">A key-value collection of all the tokens to be replace in the e=mail template.</param>
 /// <param name="toAddress">The e-mail addres the mailmessage is addressed to.</param>
 /// <returns></returns>
 private static MailMessage DetermineLocalizedMailMessage(string emailPathName, ListDictionary replacements, string toAddress)
 {
     MailDefinition mailDefinition = new MailDefinition();
     string filePath = string.Format("{0}\\{1}.html", HttpContext.Current.Request.PhysicalApplicationPath,
                                                         emailPathName);
     mailDefinition.BodyFileName = Common.Common.RetrievePhysicalFilename(filePath);
     LiteralControl dummy = new LiteralControl();
     MailMessage message = mailDefinition.CreateMailMessage(toAddress, replacements, dummy);
     message.From = new MailAddress(HreSettings.ReplyToAddress, HreSettings.ReplyToAddress);
     return message;
 }
        //private async Task SendConfirmationEmail(string clientEmail, string code, string clientName, long clientId)
        //{
        //    var confirmURL = Url.Action("ConfirmEmail", "Account", new ConfirmEmailViewModel { EmailConfirmationCode = code, UserId = clientId }, protocol: Request.Url.Scheme);

        //    MailDefinition mailDef = new MailDefinition();
        //    mailDef.From = "*****@*****.**";
        //    mailDef.Subject = "Welcome to DogeDaycare!";
        //    mailDef.IsBodyHtml = true;

        //    ListDictionary replacements = new ListDictionary();
        //    replacements.Add("{EmailTitle}", mailDef.Subject);
        //    replacements.Add("{CustomerName}", clientName);
        //    replacements.Add("{ConfirmationLink}", confirmURL);
        //    replacements.Add("{ContactUsEmail}", mailDef.From);

        //    var body = System.IO.File.ReadAllText(Server.MapPath("~/Controllers/EmailTemplates/Inline/EmailConfirmationTemplateInline.html"));

        //    MailMessage message = mailDef.CreateMailMessage(clientEmail, replacements, body, new System.Web.UI.Control());

        //    using (var client = _smtpEmailSender.BuildClient())
        //    {
        //        await client.SendMailAsync(message);
        //    }

        //    Logger.Info(string.Format("Sent confirmation code {0} to email {1}", code, clientEmail));
        //}

        private async Task SendPasswordResetEmail(string clientEmail, string code, string clientName, long id)
        {
            var confirmURL = Url.Action("PasswordReset", "Account", new PasswordResetCodeViewModel { UserId = id, PasswordResetToken = code }, Request.Url.Scheme);

            MailDefinition mailDef = new MailDefinition();
            mailDef.From = "*****@*****.**";
            mailDef.Subject = "Reset your DogeDaycare password";
            mailDef.IsBodyHtml = true;

            ListDictionary replacements = new ListDictionary();
            replacements.Add("{EmailTitle}", mailDef.Subject);
            replacements.Add("{CustomerName}", clientName);
            replacements.Add("{ConfirmationLink}", confirmURL);
            replacements.Add("{ContactUsEmail}", mailDef.From);

            var body = System.IO.File.ReadAllText(Server.MapPath("~/Controllers/EmailTemplates/Inline/PasswordResetTemplateInline.html"));

            MailMessage message = mailDef.CreateMailMessage(clientEmail, replacements, body, new System.Web.UI.Control());

            using (var client = _smtpEmailSender.BuildClient())
            {
                await client.SendMailAsync(message);
            }

            Logger.Info(string.Format("Sent password reset code {0} to email {1}", code, clientEmail));
        }
        public bool Send(CalibrationComponent component)
        {
            string emailSendEnabledSetting = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailSendEnabled);

            if (emailSendEnabledSetting.ToLower() != "true")
            {
                log.Info("WebConfig setting 'SendEmailEnabled' is set to False.  Exiting SendEmail() method.");
                return false;
            }

            StringBuilder emailTemplate = new StringBuilder();
            string filePath = EmailCommon.GetMailDefinitionFilePath("NewCalibrationComponentMailMessageDefinition.html");

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

            emailTemplate.Append(EmailCommon.ReadEmailTemplate(filePath));

            //full fetch
            component = GetComponentWithFullProperties(component);

            List<string> recipients = BuildCalibrationRecipientList();
            ListDictionary replacements = BuildEmailReplacements(component);

            MailDefinition md = new MailDefinition();
            MailMessage message = md.CreateMailMessage(string.Join(",", recipients.ToArray()), replacements, emailTemplate.ToString(), new System.Web.UI.Control());

            //FROM
            string emailAdminAccount = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailAdminAccount);
            message.From = new MailAddress(emailAdminAccount);
            message.IsBodyHtml = true;

            //SUBJECT
            message.Subject = string.Format("Calibration has been added to Instrument '{0}'.", component.Instrument.Name);

            SmtpClient client = new SmtpClient();

            client.Host = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailMailHost);

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

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

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

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

            return true;
        }
        private static void SendEmail(int id, int statusid, string email, string serial)
        {
            MailDefinition md = new MailDefinition();
            md.BodyFileName = "~/MailTemplates/MacAction_ChangeStatus.htm";

            Dictionary<string, string> d = new Dictionary<string, string>();
            string status = string.Empty;
            switch (statusid)
            {
                case 0:
                    status = "На стадии проверки";
                    break;

                case 1:
                    status = "Дополнительная гарантия подтверждена";
                    break;

                case 2:
                    status = "Заявка на дополнительную гарантию отклонена. Чтобы уточнить причину отказа, свяжитесь с оператором по телефону 0 800 302 777 0";
                    break;

                case 3:
                    status = "Ошибка ввода данных. Пожалуйста, введите серийный номер еще раз или свяжитесь с оператором по телефону 0 800 302 777 0";
                    break;
                default:
                    break;
            }
            d.Add("<%Serial%>", serial);
            d.Add("<%Status%>", status);

            md.IsBodyHtml = true;

            ContactFormsCache forms = new ContactFormsCache();
            string formName = "MacAction";

            ContactForm form = forms.GetByName(formName);

            if (form == null)
                throw new InvalidOperationException(string.Format("Can not find settings for form {0}", formName));

            string subject = form.Subject;
            string to = email;

            md.Subject = subject;

            MailMessage message = md.CreateMailMessage(to, d, new Label());

            SmtpClient sc = new SmtpClient();

            sc.Send(message);
        }
        internal static void RescheduleRequestNotifyModerator(string orgId,string playerName, string tournamentName, string matchupDate, string matchup, string reason, string comment)
        {
            DataTable moderatorsEmail = OrganisationManager.GetModeratorsEmail(orgId);
            SmtpClient client = new SmtpClient(); //host and port picked from web.config
            client.EnableSsl = true;
            ListDictionary replacements = new ListDictionary();
            replacements.Add("<% tournamentName %>", tournamentName);
            replacements.Add("<% matchupDate %>", matchupDate);
            replacements.Add("<% matchup %>", matchup);
            replacements.Add("<% reason %>", reason);
            replacements.Add("<% comment %>", comment);
            MailDefinition message = new MailDefinition();
            message.BodyFileName = @"~\EmailTemplate\RescheduleRequest.htm";
            MailMessage msgHtml = message.CreateMailMessage("*****@*****.**", replacements, new LiteralControl());
            msgHtml.To.Clear();
            foreach (DataRow row in moderatorsEmail.Rows)
            {
                msgHtml.To.Add(row["Email"].ToString());
            }

            msgHtml.Subject = playerName + " - Reschedule Request";
            msgHtml.IsBodyHtml = true;
            msgHtml.From = new MailAddress("*****@*****.**");
            try
            {
                client.Send(msgHtml);
            }
            catch { }
        }
		public void SendMail() {
			HttpContext context = HttpContext.Current;

			if (!string.IsNullOrEmpty(this.TemplateFile)) {
				string sFullFilePath = context.Server.MapPath(this.TemplateFile);
				if (File.Exists(sFullFilePath)) {
					using (StreamReader sr = new StreamReader(sFullFilePath)) {
						Body = sr.ReadToEnd();
					}
				}
			}

			EMailSettings mailSettings = new EMailSettings();
			mailSettings.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
			mailSettings.MailDomainName = String.Empty;
			mailSettings.MailUserName = String.Empty;
			mailSettings.MailPassword = String.Empty;
			mailSettings.ReturnAddress = String.Empty;

			//parse web.config as XML because of medium trust issues

			XmlDocument xDoc = new XmlDocument();
			xDoc.Load(context.Server.MapPath("~/Web.config"));

			XmlElement xmlMailSettings = xDoc.SelectSingleNode("//system.net/mailSettings/smtp") as XmlElement;

			if (xmlMailSettings != null) {
				if (xmlMailSettings.Attributes["from"] != null) {
					mailSettings.ReturnAddress = xmlMailSettings.Attributes["from"].Value;
				}
				if (xmlMailSettings.Attributes["deliveryMethod"] != null && xmlMailSettings.Attributes["deliveryMethod"].Value.ToLower() == "network") {
					mailSettings.DeliveryMethod = SmtpDeliveryMethod.Network;
					if (xmlMailSettings.HasChildNodes) {
						XmlNode xmlNetSettings = xmlMailSettings.SelectSingleNode("//system.net/mailSettings/smtp/network");
						if (xmlNetSettings != null && xmlNetSettings.Attributes["password"] != null) {
							mailSettings.MailUserName = xmlNetSettings.Attributes["userName"].Value;
							mailSettings.MailPassword = xmlNetSettings.Attributes["password"].Value;
							mailSettings.MailDomainName = xmlNetSettings.Attributes["host"].Value;
						}
					}
				}
			}

			if (string.IsNullOrEmpty(mailSettings.MailDomainName)) {
				mailSettings.MailDomainName = context.Request.ServerVariables["SERVER_NAME"];
			}

			if (string.IsNullOrEmpty(mailSettings.ReturnAddress)) {
				mailSettings.ReturnAddress = "no-reply@" + mailSettings.MailDomainName;
			}

			MailFrom = mailSettings.ReturnAddress;

			MailDefinition mailDefinition = new MailDefinition {
				BodyFileName = this.TemplateFile,
				From = MailFrom,
				Subject = MailSubject,
				IsBodyHtml = IsHTML
			};

			MailMessage mailMessage = null;

			if (!string.IsNullOrEmpty(Body)) {
				mailMessage = mailDefinition.CreateMailMessage(Recepient, ContentPlaceholders, Body, WebControl);
			} else {
				mailMessage = mailDefinition.CreateMailMessage(Recepient, ContentPlaceholders, WebControl);
			}

			mailMessage.Priority = MailPriority.Normal;
			mailMessage.Headers.Add("X-Originating-IP", context.Request.ServerVariables["REMOTE_ADDR"].ToString());
			mailMessage.Headers.Add("X-Application", "CarrotCake CMS " + CurrentDLLVersion);
			mailMessage.Headers.Add("User-Agent", "CarrotCake CMS " + CurrentDLLVersion);
			mailMessage.Headers.Add("Message-ID", "<" + Guid.NewGuid().ToString().ToLower() + "@" + mailSettings.MailDomainName + ">");

			SmtpClient client = new SmtpClient();
			mailMessage.From = new MailAddress(mailSettings.ReturnAddress);

			if (mailSettings.DeliveryMethod == SmtpDeliveryMethod.Network
					&& !string.IsNullOrEmpty(mailSettings.MailUserName)
					&& !string.IsNullOrEmpty(mailSettings.MailPassword)) {
				client.Host = mailSettings.MailDomainName;
				client.Credentials = new NetworkCredential(mailSettings.MailUserName, mailSettings.MailPassword);
			} else {
				client.Credentials = new NetworkCredential();
			}

			client.Send(mailMessage);
		}
        private string GetEmailBody()
        {
            ListDictionary replacements = new ListDictionary();
            using (TournaDataContext db = new TournaDataContext(ConfigurationManager.ConnectionStrings["StrongerOrgString"].ConnectionString))
            {
                var tournametInfo = (from t in db.Tournaments
                                     join g in db.Games on t.GameId equals g.Id
                                     where t.Id == new Guid(Request.QueryString["TournamentId"].ToString())
                                     select new
                                     {
                                         t.TournamentName,
                                         t.StartDate,
                                         t.TimeWindowStart,
                                         t.TimeWindowEnd,
                                         t.Locations,
                                         g.Title,
                                         g.ConsoleName,
                                         t.FirstPrize,
                                         t.SecondPrize,
                                         t.ThirdPrize,
                                         t.Abstract
                                     }).Single();

                replacements.Add("<% OrgId %>", this.Master.OrgBasicInfo.Id.ToString());
                replacements.Add("<% TournamentName %>", tournametInfo.TournamentName);
                replacements.Add("<% When %>", tournametInfo.StartDate.ToString("D"));
                replacements.Add("<% StartTime %>", tournametInfo.TimeWindowStart.TruncateSeconds());
                replacements.Add("<% EndTime %>", tournametInfo.TimeWindowEnd.TruncateSeconds());
                replacements.Add("<% Where %>", tournametInfo.Locations ?? string.Empty);
                replacements.Add("<% GameName %>", tournametInfo.Title ?? string.Empty);
                replacements.Add("<% FirstPrize %>", string.IsNullOrEmpty(tournametInfo.FirstPrize) ? "N/A" : tournametInfo.FirstPrize);
                replacements.Add("<% SecondPrize %>", string.IsNullOrEmpty(tournametInfo.SecondPrize) ? "N/A" : tournametInfo.SecondPrize);
                replacements.Add("<% ThirdPrize %>", string.IsNullOrEmpty(tournametInfo.ThirdPrize) ? "N/A" : tournametInfo.ThirdPrize);
                replacements.Add("<% TournamentId %>", Request.QueryString["TournamentId"].ToString());
                replacements.Add("<% Abstract %>", tournametInfo.Abstract ?? string.Empty);
                replacements.Add("<% ConsoleName %>", tournametInfo.ConsoleName ?? string.Empty);
            }

            MailDefinition message = new MailDefinition();
            message.BodyFileName = @"~\EmailTemplate\TournamentInvintation.htm";
            MailMessage msgHtml = message.CreateMailMessage("*****@*****.**", replacements, new LiteralControl());
            return msgHtml.Body;
        }
        /// <summary>
        /// Convert document to HTML mail message and send it to recipient
        /// </summary>
        /// <param name="smtp">Smtp server</param>
        /// <param name="emailFrom">Sender e-mail</param>
        /// <param name="password">Sender password</param>
        /// <param name="emailTo">Recipient e-mail</param>
        /// <param name="subject">E-mail subject</param>
        /// <param name="port">Port to use</param>
        /// <param name="useAuth">Specify authentication</param>
        /// <param name="inputFileName">Document file name</param>
        private static void Send(string smtp, string emailFrom, string password, string emailTo, string subject, int port, bool useAuth, string inputFileName)
        {
            // Create temporary folder for Aspose.Words to store images to during export.
            string tempDir = Path.Combine(Path.GetTempPath(), "AsposeMail");
            if (!Directory.Exists(tempDir))
                Directory.CreateDirectory(tempDir);

            // Open the document.
            Document doc = new Document(inputFileName);

            HtmlSaveOptions saveOptions = new HtmlSaveOptions();
            // Specify folder where images will be saved.
            saveOptions.ImagesFolder = tempDir;
            // We want the images in the HTML to be referenced in the e-mail as attachments so add the cid prefix to the image file name.
            // This replaces what would be the path to the image with the "cid" prefix.
            saveOptions.ImagesFolderAlias = "cid:";
            // Header footers don't normally export well in HTML format so remove them.
            saveOptions.ExportHeadersFootersMode = ExportHeadersFootersMode.None;

            // Save the document to stream in HTML format.
            MemoryStream htmlStream = new MemoryStream();
            doc.Save(htmlStream, saveOptions);

            // Read the HTML from the stream as plain text.
            string htmlText = Encoding.UTF8.GetString(htmlStream.ToArray());
            htmlStream.Close();

            // Save the HTML into the temporary folder.
            Stream htmlFile = new FileStream(Path.Combine(tempDir, "Message.html"), FileMode.Create);
            StreamWriter htmlWriter = new StreamWriter(htmlFile);
            htmlWriter.Write(htmlText);
            htmlWriter.Close();
            htmlFile.Close();

            // Create the mail definiton and specify the appropriate settings.
            MailDefinition mail = new MailDefinition();
            mail.IsBodyHtml = true;
            mail.BodyFileName = Path.Combine(tempDir, "Message.html");
            mail.From = emailFrom;
            mail.Subject = subject;

            // Get the names of the images in the temporary folder.
            string[] fileNames = Directory.GetFiles(tempDir);

            // Add each image as an embedded object to the message.
            for (int imgIndex = 0; imgIndex < fileNames.Length; imgIndex++)
            {
                string imgFullName = fileNames[imgIndex];
                string imgName = Path.GetFileName(fileNames[imgIndex]);
                // The ID of the embedded object is the name of the image preceeded with a foward slash.
                mail.EmbeddedObjects.Add(new EmbeddedMailObject(string.Format("/{0}", imgName), imgFullName));
            }

            MailMessage message = null;

            // Create the message.
            try
            {
                message = mail.CreateMailMessage(emailTo, new ListDictionary(), new System.Web.UI.Control());

                // Create the SMTP client to send the message with.
                SmtpClient sender = new SmtpClient(smtp);

                // Set the credentials.
                sender.Credentials = new NetworkCredential(emailFrom, password);
                // Set port.
                sender.Port = port;
                // Choose to enable authentication.
                sender.EnableSsl = useAuth;

                // Send the e-mail message.
                sender.Send(message);
            }

            catch (Exception e)
            {
                throw e;
            }

            finally
            {
                // This frees the Message.html file if an exception occurs.
                message.Dispose();
            }

            // Delete the temp folder.
            Directory.Delete(tempDir, true);
        }
        private void SendMail(iPadActionSerial item)
        {
            MailDefinition md = new MailDefinition();
            md.BodyFileName = "~/MailTemplates/request_iPadAction.htm";

            Dictionary<string, string> d = new Dictionary<string, string>();

            d.Add("<%Serial%>", item.Serial);
            d.Add("<%BuyDate%>", item.BuyDate.ToShortDateString());
            d.Add("<%Email%>", item.Email);
            d.Add("<%Seller%>", item.SellerName);

            md.IsBodyHtml = true;

            ContactFormsCache forms = new ContactFormsCache();
            string formName = string.Format("Request_{0}", Apple.Web.Controls.RequestStatusForm.StatusType.iPadAction);

            ContactForm form = forms.GetByName(formName);

            if (form == null)
                throw new InvalidOperationException(string.Format("Can not find settings for form {0}", formName));

            string subject = form.Subject;
            string to = form.To;
            string cc = form.CC;

            md.Subject = subject;

            if (!string.IsNullOrEmpty(cc))
            {
                md.CC = cc;
            }

            MailMessage message = md.CreateMailMessage(to, d, this);

            SmtpClient sc = new SmtpClient();

            sc.Send(message);
        }
Exemple #28
0
        public static bool SendErrorsWarningsEmail(List<EmailMessage> emailMessageTypes, string distributionListName)
        {
            string emailSendEnabledSetting = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailSendEnabled);

            if (emailSendEnabledSetting.ToLower() != "true")
            {
                mLog.Info("WebConfig setting 'SendEmailEnabled' is set to False.  Exiting SendErrorsWarningsEmail() method.");
                return false;
            }

            StringBuilder emailTemplate = new StringBuilder();
            string filePath = GetMailDefinitionFilePath("ImporterErrorsWarningsEmailDefinition.html");

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

            emailTemplate.Append(ReadEmailTemplate(filePath));

            MailDefinition md = new MailDefinition();

             //FROM
            string emailAdminAccount = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailAdminAccount);

            md.From = emailAdminAccount;

            //TO

            var emailTo = GetDistributionListEmailAdresses(distributionListName);

            if (emailTo == null || !emailTo.Any())
            {
                mLog.Error("", "No email recipients could be found with valid email addresses for Sent To field.");
                Console.WriteLine("No email recipients could be found with valid email addresses for Sent To field.");
                return false;
            }
            ListDictionary replacements = new ListDictionary();

            replacements.Add("<%Errors%>", (BuildPlainMessageList(emailMessageTypes.Where(x => x.EmailMessageType == EmailMessageType.Error).Select(x => x.Message).ToList())));
            replacements.Add("<%Warnings%>", (BuildPlainMessageList(emailMessageTypes.Where(x => x.EmailMessageType == EmailMessageType.Warning).Select(x => x.Message).ToList())));

            MailMessage message = md.CreateMailMessage(string.Join(",", emailTo.ToArray()), replacements, emailTemplate.ToString(), new System.Web.UI.Control());

            message.From = new MailAddress(emailAdminAccount);
            message.IsBodyHtml = true;

            //SUBJECT
            message.Subject = "CMS Actuals Importer Error/Warning";

            SmtpClient client = new SmtpClient();

            client.Host = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailMailHost);

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

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

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

                mLog.Verbose("{0}", message.Body);
                client.Send(message);
            }
            catch (Exception exception)
            {
                mLog.Error(exception.Message, exception, "Possible relay error");
                Console.WriteLine("{0} - {1}", "Possible relay error", exception.Message);
                if (exception.InnerException != null)
                {
                    mLog.Error(exception.InnerException.Message, exception.InnerException, "Possible relay error inner exception.");
                    Console.WriteLine(exception.InnerException.Message);
                }
            }

            return true;
        }
Exemple #29
0
        public bool SendEmail(string sentFrom, String[] sentTo, String[] ccList, string subject, ListDictionary replacements, string emailTemplateName)
        {
            string emailSendEnabledSetting = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailSendEnabled);

            if (emailSendEnabledSetting.ToLower() != "true")
            {
                mLog.Info("CMS setting 'SendEmailEnabled' is set to False.  Exiting SendEmail() method.");
                return false;
            }

            MailDefinition md = new MailDefinition();
            md.Subject = subject;
            md.From = sentFrom;

            StringBuilder emailTemplate = new StringBuilder();
            string filePath = GetMailDefinitionFilePath(emailTemplateName);

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

            emailTemplate.Append(ReadEmailTemplate(filePath));
            MailMessage message = md.CreateMailMessage(string.Join(",", sentTo), replacements, emailTemplate.ToString(), new System.Web.UI.Control());
            message.IsBodyHtml = true;

            //message.From = new MailAddress(sentFrom);
            ccList.ToList().ForEach(message.CC.Add);

            SmtpClient client = new SmtpClient();
            client.Host = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailMailHost);

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

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

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

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

            return true;
        }
        private void SendEmail(
            string toEmail,
            string fromEmail,
            string subject,
            string template,
            ListDictionary replacements,
            bool isHtml = true)
        {
            string boardUrl = SiteConfig.BoardURL.Value;
            if (boardUrl.EndsWith("/"))
                boardUrl = boardUrl.TrimEnd('/');

            replacements.Add("{BOARD_URL}", boardUrl);
            replacements.Add("{BOARD_NAME}", SiteConfig.BoardName.Value);

            MailDefinition md = new MailDefinition();

            string templatePath = EmailTemplates.GenerateEmailPath(template);
            md.BodyFileName = templatePath;
            md.IsBodyHtml = isHtml;
            md.From = fromEmail;
            md.Subject = subject;

            MailMessage message = md.CreateMailMessage(toEmail, replacements, new System.Web.UI.Control());

            SmtpClient client = Settings.GetSmtpClient();

            try
            {
                client.SendAsync(message, null);
            }
            catch
            {
            }
        }
Exemple #31
0
        /// <summary>
        /// Sends an mail. To be called from a new thread.
        /// </summary>
        /// <param name="mailSettings">The mail settings.</param>
        /// <param name="toAddress">To address.</param>
        /// <param name="toName">To name. Optional. Ignored if null or whitespace.</param>
        /// <param name="ccAddressCsv">The cc address CSV.</param>
        /// <param name="bccAddressCsv">The BCC address CSV.</param>
        /// <param name="subject">The subject.</param>
        /// <param name="body">The body.</param>
        /// <param name="isBodyHtml">if set to <c>true</c> [is body HTML].</param>
        /// <param name="attachmentDosPaths">The attachment dos paths.</param>
        /// <param name="priority">The priority.</param>
        /// <param name="replacements">The replacements.</param>
        /// <returns></returns>
        private static bool SendMailInternal(MailSettings mailSettings, string toAddress, string toName, string ccAddressCsv, string bccAddressCsv, string subject, string body, bool isBodyHtml, string attachmentDosPaths = null, MailPriority priority = MailPriority.Normal, IDictionary replacements = null)
        {
            // Send the email
            try
            {
                // Build From address
                MailAddress fromMailAdd = null;

                if (!string.IsNullOrWhiteSpace(mailSettings.FromName))
                {
                    fromMailAdd = new MailAddress(mailSettings.FromAddress, mailSettings.FromName);
                }
                else
                {
                    fromMailAdd = new MailAddress(mailSettings.FromAddress);
                }

                // Build To address
                MailAddress toMailAddress = null;

                if (!string.IsNullOrWhiteSpace(toName))
                {
                    toMailAddress = new MailAddress(toAddress, toName);
                }
                else
                {
                    toMailAddress = new MailAddress(toAddress);
                }

                var mailDef = new MailDefinition();
                mailDef.IsBodyHtml = isBodyHtml;
                mailDef.Priority = priority;
                mailDef.Subject = subject;
                mailDef.From = fromMailAdd.Address;
                // Need to set From here, otherwise CreateMailMessage will blow up if no smtp from setting in app.config or web.config. We'll update it further down.

                //Using mailMsg As New MailMessage()

                if (replacements == null)
                {
                    // Replacements mustn't be empty
                    replacements = new ListDictionary();
                }

                using (var mailMsg = mailDef.CreateMailMessage(toAddress, replacements, body, new System.Web.UI.LiteralControl()))
                {
                    {
                        mailMsg.From = fromMailAdd;
                        // Update From with MailAddress object so we also apply the sender's name
                        //.To.Add(toMailAddress)
                        mailMsg.To.Clear();
                        mailMsg.To.Add(toMailAddress);
                        // Update To with MailAddress object so we also apply the recipient's name
                        mailMsg.Subject = subject;
                        //.Body = body
                        mailMsg.IsBodyHtml = isBodyHtml;
                        mailMsg.Priority = priority;

                        if (!string.IsNullOrWhiteSpace(mailSettings.ReplyToAddress))
                        {
                            mailMsg.ReplyToList.Add(mailSettings.ReplyToAddress);
                        }

                        if (!string.IsNullOrWhiteSpace(ccAddressCsv))
                        {
                            mailMsg.CC.Add(ccAddressCsv);
                        }

                        if (!string.IsNullOrWhiteSpace(bccAddressCsv))
                        {
                            mailMsg.Bcc.Add(bccAddressCsv);
                        }

                        if (!string.IsNullOrEmpty(attachmentDosPaths))
                        {
                            string[] strAttach = attachmentDosPaths.Split(";".ToCharArray());

                            foreach (var strFile in strAttach)
                            {
                                Attachment attachment = new Attachment(strFile);
                                mailMsg.Attachments.Add(attachment);
                            }
                        }
                    }

                    using (SmtpClient smtp = new SmtpClient())
                    {
                        // If provided, override default host and port in web.config with values passed in.
                        if (mailSettings.Port > 0 && !string.IsNullOrWhiteSpace(mailSettings.Host))
                        {
                            smtp.Host = mailSettings.Host;
                            smtp.Port = mailSettings.Port;
                        }

                        if (!string.IsNullOrWhiteSpace(mailSettings.UserName) && !string.IsNullOrWhiteSpace(mailSettings.Password))
                        {
                            smtp.Credentials = new NetworkCredential(mailSettings.UserName, mailSettings.Password);
                        }
                        else
                        {
                            smtp.UseDefaultCredentials = true;
                        }

                        //if (!(mailSettings.DeliveryMethod == null))
                        if ((int)mailSettings.DeliveryMethod > 0)
                        {
                            smtp.DeliveryMethod = mailSettings.DeliveryMethod;
                        }

                        smtp.EnableSsl = mailSettings.EnableSsl;
                        smtp.Send(mailMsg);
                    }
                }

            }
            catch (Exception ex)
            {
                var methodDesc = typeof(Mailer).FullName + ".SendMailInternal()";
                //Every1.Core.Web.Utils.TraceWarn(methodDesc, ex.Message + ex.InnerException != null ? ex.InnerException.Message : string.Empty);
                //Every1.Core.ErrorLogger.LogError(methodDesc, ex);
                return false;
            }

            return true;
        }
        private void SendMail()
        {
            string company = txtCompanyName.Text;
            string contact = txtContactName.Text;
            string address = txtAddress.Text;
            string phone = txtPhone.Text;
            string email = txtEmail.Text;
            bool isPartner = rbIsPartner.Checked;
            bool isServicePartner = rbIsServicePartner.Checked;
            string status = this.Status.ToString();

            MailDefinition md = new MailDefinition();
            md.BodyFileName = "~/MailTemplates/StatusRequest.htm";

            Dictionary<string, string> d = new Dictionary<string, string>();

            d.Add("<%Status%>", status);
            d.Add("<%CompanyName%>", company);
            d.Add("<%ContactName%>", contact);
            d.Add("<%Address%>", address);
            d.Add("<%Phone%>", phone);
            d.Add("<%Email%>", email);
            d.Add("<%IsPartner%>", isPartner ? "yes" : "no");
            d.Add("<%IsServicePartner%>", isServicePartner ? "yes" : "no");

            md.IsBodyHtml = true;

            ContactFormsCache forms = new ContactFormsCache();
            string formName = string.Format("Request_{0}",Status);

            ContactForm form = forms.GetByName(formName);

            if (form == null)
                throw new InvalidOperationException(string.Format("Can not find settings for form {0}", formName));

            string subject = form.Subject;
            string to = form.To;
            string cc = form.CC;

            md.Subject = string.Format(subject, company);

            if (!string.IsNullOrEmpty(cc))
            {
                md.CC = cc;
            }

            MailMessage message = md.CreateMailMessage(to, d, this);

            SmtpClient sc = new SmtpClient();

            sc.Send(message);
        }