private void SendEmail(List<string> mailTos, string subject, string message)
        {
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                if (mailTos.Count() != 0)
                {
                    MailHelper mailHelper = new MailHelper();

                    mailHelper.SendMail(mailTos, subject, message);
                }
            }
        }
Exemplo n.º 2
0
        public int SendEmail()
        {
            int nEmailCount = 0;
            try
            {
                int nPostponeHours = Config.getInstance().Email_InvoiceNotify_PostponeHours;

                DateTime dt = DateTime.Now.AddHours(nPostponeHours);
                var objs = from o in dbContext.ABi_Email
                           where !o.IsSend && o.DateModified > dt
                           select o;

                if (objs != null && objs.Count() > 0)
                {
                    MailHelper mHelper = new MailHelper();
                    foreach (var obj in objs)
                    {
                        if (mHelper.EmainSend(obj.EmailList.Split(','), obj.EmailContent, obj.EmailSubject))
                        {
                            nEmailCount++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(String.Format("SendEmail"), ex);
                nEmailCount = -1;
            }
            return nEmailCount;
        }
Exemplo n.º 3
0
        public static void SendInvitationEmail(string username, string sendername, string email,Guid teamid)
        {
            try
            {
                Registration reg = new Registration();
                string tid = reg.MD5Hash(email);
                MailHelper mailhelper = new MailHelper();
                string mailpath = HttpContext.Current.Server.MapPath("~/Layouts/Mails/SendInvitation.htm");
                string html = File.ReadAllText(mailpath);
                string fromemail = ConfigurationManager.AppSettings["fromemail"];
                string usernameSend = ConfigurationManager.AppSettings["username"];
                string host = ConfigurationManager.AppSettings["host"];
                string port = ConfigurationManager.AppSettings["port"];
                string pass = ConfigurationManager.AppSettings["password"];
                string urllogin = "******";
                string registrationurl = "http://ssp.socioboard.com/Registration.aspx?tid="+teamid;
                string Body = mailhelper.InvitationMail(html, username, sendername, "", urllogin, registrationurl);
                string Subject = "You've been Invited to " + username + " SocialSuitePro Account";
                //   MailHelper.SendMailMessage(host, int.Parse(port.ToString()), fromemail, pass, email, string.Empty, string.Empty, Subject, Body);

                MailHelper.SendSendGridMail(host, Convert.ToInt32(port), fromemail, "", email, "", "", Subject, Body, usernameSend, pass);

            }
            catch (Exception ex)
            {

                logger.Error(ex.Message);
            }
        }
Exemplo n.º 4
0
        public bool SendMail()
        {
            _mailData = _mailTemplate.GetMailTemplate();

            using (var mailHelper = new MailHelper())
            {

                //Prepare the underline mailhelper data
                foreach (string toAddress in _mailData.To)
                {
                    if(!string.IsNullOrWhiteSpace(toAddress))
                        mailHelper.ToAddresses.Add(toAddress);
                }
                foreach (string bccAddress in _mailData.Bcc)
                {
                    if (!string.IsNullOrWhiteSpace(bccAddress))
                        mailHelper.BccAddresses.Add(bccAddress);
                }
                foreach (string ccAddress in _mailData.Cc)
                {
                    if (!string.IsNullOrWhiteSpace(ccAddress))
                        mailHelper.BccAddresses.Add(ccAddress);
                }

                mailHelper.Subject = _mailData.Subject;
                mailHelper.From = _mailData.From;
                mailHelper.Body = _mailData.Body;

                mailHelper.Send();
            }

            return true;
        }
Exemplo n.º 5
0
        public static void SendEMail(string username, string password, string emailid)
        {
            try
            {
                MailHelper mailhelper = new MailHelper();
                string mailpath = HttpContext.Current.Server.MapPath("~/Layouts/Mails/RegistrationMail.html");

                string html = File.ReadAllText(mailpath);

                html = html.Replace("%USERNAME%", username);
                html = html.Replace("%PASSWORD%", password);
                html = html.Replace("%EMAILID%", emailid);
                string fromemail = ConfigurationManager.AppSettings["fromemail"];
                string usernameSend = ConfigurationManager.AppSettings["username"];
                string host = ConfigurationManager.AppSettings["host"];
                string port = ConfigurationManager.AppSettings["port"];
                string pass = ConfigurationManager.AppSettings["password"];

                string Body = mailhelper.VerificationMail(html, emailid, "");

                string Subject = "You have Added to SocialSuitePro Account";
                //            MailHelper.SendMailMessage(host, int.Parse(port.ToString()),fromemail,pass,emailid,string.Empty,string.Empty,Subject,Body);

                MailHelper.SendSendGridMail(host, Convert.ToInt32(port), fromemail, "", emailid, "", "", Subject, Body, usernameSend, pass);

            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Handles OnDelete
 /// </summary>
 /// <param name="e">
 /// The <see cref="System.EventArgs"/> instance containing the event data.
 /// </param>
 protected override void OnDelete(EventArgs e)
 {
     WorkFlowDB.SetLastModified(this.ModuleID, MailHelper.GetCurrentUserEmailAddress());
     base.OnDelete(e);
 }
Exemplo n.º 7
0
 public HomeController(DataManager dataManager, ILogger <HomeController> logger, MailHelper mailHelper)
 {
     this.dataManager = dataManager;
     this.logger      = logger;
     this.mailHelper  = mailHelper;
 }
Exemplo n.º 8
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            m_to      = this.txtTo.Text.Trim();
            m_cc      = this.txtCC.Text.Trim();
            m_bcc     = this.txtBcc.Text.Trim();
            m_Subject = this.txtSubject.Text.Trim();
            m_Body    = this.rtbBody.Text;

            bool isAsync = this.chbAsync.Checked;
            bool isReuse = this.cbxReuse.Checked;

            this.rtbReply.AppendText(String.Format("==============={0},{1}{2}"
                                                   , (isAsync ? "异步发送" : "同步发送"), (isReuse ? "重用SmtpClient实例" : "新SmtpClient实例"), Environment.NewLine));

            watch.Reset();
            watch.Start();

            // DateTime.Now.ToLongTimeString()
            if (this.rdoOne.Checked)
            {
                #region 实验一:单条邮件同步和异步发送(可通过添加大附件来观察同步异步效果)
                MailHelper mail = new MailHelper(isAsync);

                #region 发送单封邮件 中 加入图片链接示例。
                // 发送单封邮件 中 加入图片链接示例。
                string picPath = Environment.CurrentDirectory + "\\附件\\PIC_Mail中文.png";

                mail.AddInlineAttachment(picPath, "MyPic");

                // 注意内联图片地址写法  cid:ContentId
                m_Body = m_Body + "<br/><img src=\"cid:MyPic\" /><a href=\"cid:MyPic\" target=\"_blank\">点击在新窗口打开图片</a>";

                #endregion

                if (isAsync)
                {
                    this.SendMessageAsync(mail, true, "实验一", "单条", true, isReuse);
                }
                else
                {
                    this.SendMessage(mail, true, "实验一", "单条", true, isReuse);
                }

                #endregion
            }
            else if (this.rdoTwo.Checked)
            {
                #region 实验二:批量邮件同步和异步发送(单个线程,单个SmtpClient实例,SendAsync())

                long       count = long.Parse(this.cbbNumber.Text);
                MailHelper mail  = new MailHelper(isAsync);

                if (isReuse)
                {
                    if (isAsync)
                    {
                        for (long i = 1; i <= count; i++)
                        {
                            this.SendMessageAsync(mail, false, "实验二", "第" + i + "条", true, true);
                        }
                        mail.SetBatchMailCount(count);
                    }
                    else
                    {
                        for (long i = 1; i <= count; i++)
                        {
                            this.SendMessage(mail, false, "实验二", "第" + i + "条", true, true);
                        }
                        mail.SetBatchMailCount(count);
                    }
                }
                else
                {
                    if (isAsync)
                    {
                        for (long i = 1; i <= count; i++)
                        {
                            this.SendMessageAsync(mail, true, "实验二", "第" + i + "条", true, false);
                        }
                    }
                    else
                    {
                        for (long i = 1; i <= count; i++)
                        {
                            this.SendMessage(mail, true, "实验二", "第" + i + "条", true, false);
                        }
                    }
                }

                #endregion
            }
            else if (this.rdoThree.Checked)
            {
                #region 实验三:批量邮件同步和异步发送 (平行类库Parallel(自动分区),每个分区一个MailHelper、SmtpClient实例,SendAsync())

                long count = long.Parse(this.cbbNumber.Text);
                if (count != 1)
                {
                    int  fenzu     = 0;
                    long sendCount = 0;

                    #region 由系统负荷自动分配最大并发度
                    // Environment.ProcessorCount; 并行度设置过大会导致资源争用问题,效率不高
                    // ParallelOptions parallelOptions = new ParallelOptions();
                    // parallelOptions.MaxDegreeOfParallelism = Environment.ProcessorCount;
                    #endregion

                    ParallelOptions parallelOptions = new ParallelOptions();
                    // 用一半的线程,因为内部发邮件需要线程池线程
                    parallelOptions.MaxDegreeOfParallelism = (int)Math.Ceiling((double)Environment.ProcessorCount / 2d);

                    Parallel.For <ParallelInitObj>(1, count + 1
                                                   , parallelOptions, () =>
                    {
                        Interlocked.Increment(ref fenzu);
                        Debug.WriteLine("开始一个分组,当前分组数为:" + fenzu.ToString());
                        ParallelInitObj initObj = new ParallelInitObj()
                        {
                            mail     = new MailHelper(isAsync),
                            SumCount = 0,
                        };
                        return(initObj);
                    }
                                                   , (i, loop, initObj) =>
                    {
                        ParallelInitObj curInitObj = initObj;
                        MailHelper mail            = curInitObj.mail;

                        Interlocked.Increment(ref sendCount);
                        string shiyan = String.Format("({0})实验三", Thread.CurrentThread.ManagedThreadId);

                        if (isReuse)
                        {
                            if (isAsync)
                            {
                                this.SendMessageAsync(mail, false, shiyan, "第" + Thread.VolatileRead(ref sendCount) + "条", true, true);
                                curInitObj.SumCount++;
                            }
                            else
                            {
                                this.SendMessage(mail, false, shiyan, "第" + Thread.VolatileRead(ref sendCount) + "条", true, true);
                                curInitObj.SumCount++;
                            }
                        }
                        else
                        {
                            if (isAsync)
                            {
                                this.SendMessageAsync(mail, true, shiyan, "第" + Thread.VolatileRead(ref sendCount) + "条", true, false);
                            }
                            else
                            {
                                this.SendMessage(mail, true, shiyan, "第" + Thread.VolatileRead(ref sendCount) + "条", true, false);
                            }
                        }
                        return(curInitObj);
                    }
                                                   , (initObj) =>
                    {
                        ParallelInitObj curInitObj = initObj;
                        if (isReuse)
                        {
                            curInitObj.mail.SetBatchMailCount(curInitObj.SumCount);
                        }
                        Interlocked.Decrement(ref fenzu);
                        Debug.WriteLine("结束一个分组,当前分组数为:" + fenzu.ToString());
                    });
                }
                else
                {
                    MessageBox.Show("分区发邮件不能为一封");
                }

                #endregion
            }
            else if (this.rdoFour.Checked)
            {
                #region 实验四:批量邮件同步和异步发送 (平行类库Parallel(手动分区),每个分区一个MailHelper、SmtpClient实例)

                long count = long.Parse(this.cbbNumber.Text);

                if (count != 0)
                {
                    int  fenzu     = 0;
                    long sendCount = 0;

                    #region 由系统负荷自动分配最大并发度
                    // OrderablePartitioner<Tuple<long, long>> orderPartition = Partitioner.Create(1, count + 1, Environment.ProcessorCount);
                    // ParallelOptions parallelOptions = new ParallelOptions();
                    // parallelOptions.MaxDegreeOfParallelism = (int)Math.Ceiling((double)Environment.ProcessorCount);
                    #endregion

                    OrderablePartitioner <Tuple <long, long> > orderPartition = Partitioner.Create(1, count + 1, (count / (int)Math.Ceiling((double)Environment.ProcessorCount / 2d)));

                    ParallelOptions parallelOptions = new ParallelOptions();
                    parallelOptions.MaxDegreeOfParallelism = (int)Math.Ceiling((double)Environment.ProcessorCount / 2d);

                    Parallel.ForEach <Tuple <long, long>, ParallelInitObj>(orderPartition,
                                                                           parallelOptions, () =>
                    {
                        Interlocked.Increment(ref fenzu);
                        Debug.WriteLine("开始一个分组,当前分组数为:" + fenzu.ToString());
                        ParallelInitObj initObj = new ParallelInitObj()
                        {
                            mail     = new MailHelper(),
                            SumCount = 0,
                        };
                        return(initObj);
                    }
                                                                           , (source, loop, loopIndex, initObj) =>
                    {
                        ParallelInitObj curInitObj = initObj;
                        MailHelper mail            = curInitObj.mail;

                        string shiyan = String.Format("({0})实验四", Thread.CurrentThread.ManagedThreadId);

                        for (long i = source.Item1; i < source.Item2; i++)
                        {
                            Interlocked.Increment(ref sendCount);
                            if (isReuse)
                            {
                                if (isAsync)
                                {
                                    this.SendMessageAsync(mail, false, shiyan, "第" + Thread.VolatileRead(ref sendCount) + "条", true, true);
                                    curInitObj.SumCount++;
                                }
                                else
                                {
                                    this.SendMessage(mail, false, shiyan, "第" + Thread.VolatileRead(ref sendCount) + "条", true, true);
                                    curInitObj.SumCount++;
                                }
                            }
                            else
                            {
                                if (isAsync)
                                {
                                    this.SendMessageAsync(mail, true, shiyan, "第" + Thread.VolatileRead(ref sendCount) + "条", true, false);
                                }
                                else
                                {
                                    this.SendMessage(mail, true, shiyan, "第" + Thread.VolatileRead(ref sendCount) + "条", true, false);
                                }
                            }
                        }
                        return(curInitObj);
                    }
                                                                           , (initObj) =>
                    {
                        ParallelInitObj curInitObj = initObj;
                        if (isReuse)
                        {
                            curInitObj.mail.SetBatchMailCount(curInitObj.SumCount);
                        }
                        Interlocked.Decrement(ref fenzu);
                        Debug.WriteLine("结束一个分组,当前分组数为:" + fenzu.ToString());
                    });
                }
                else
                {
                    MessageBox.Show("分区发邮件不能为一封");
                }

                #endregion
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// 同步发送邮件
        /// </summary>
        /// <param name="isSimple">是否只发送一条</param>
        /// <param name="autoReleaseSmtp">是否自动释放SmtpClient</param>
        /// <param name="isReuse">是否重用SmtpClient</param>
        private void SendMessage(MailHelper mail, bool isSimple, string shiyan, string msgCount, bool autoReleaseSmtp, bool isReuse)
        {
            AppendReplyMsg(String.Format("{0}:{1}\"同步\"邮件开始。{2}{3}", shiyan, msgCount, watch.ElapsedMilliseconds, Environment.NewLine));

            if (!isReuse || !mail.ExistsSmtpClient())
            {
                mail.SetSmtpClient(
                    new SmtpHelper(Config.TestEmailType, false, Config.TestUserName, Config.TestPassword).SmtpClient
                    , autoReleaseSmtp
                    );
            }

            mail.From            = Config.TestFromAddress;
            mail.FromDisplayName = Config.GetAddressName(Config.TestFromAddress);

            string to  = m_to;
            string cc  = m_cc;
            string bcc = m_bcc;

            if (to.Length > 0)
            {
                mail.AddReceive(EmailAddrType.To, to, Config.GetAddressName(to));
            }
            if (cc.Length > 0)
            {
                mail.AddReceive(EmailAddrType.CC, cc, Config.GetAddressName(cc));
            }
            if (bcc.Length > 0)
            {
                mail.AddReceive(EmailAddrType.Bcc, bcc, Config.GetAddressName(bcc));
            }

            mail.Subject = m_Subject;
            // Guid.NewGuid() 防止重复内容,被SMTP服务器拒绝接收邮件
            mail.Body       = m_Body + Guid.NewGuid();
            mail.IsBodyHtml = true;

            if (filePaths != null && filePaths.Count > 0)
            {
                foreach (string filePath in FilePaths)
                {
                    mail.AddAttachment(filePath);
                }
            }

            Dictionary <MailInfoType, string> dic = mail.CheckSendMail();

            if (dic.Count > 0 && MailInfoHelper.ExistsError(dic))
            {
                // 反馈“错误+提示”信息
                AppendReplyMsg(MailInfoHelper.GetMailInfoStr(dic));
            }
            else
            {
                string msg = String.Empty;
                if (dic.Count > 0)
                {
                    // 反馈“提示”信息
                    msg = MailInfoHelper.GetMailInfoStr(dic);
                }

                try
                {
                    if (isSimple)
                    {
                        mail.SendOneMail();
                    }
                    else
                    {
                        // 发送
                        mail.SendBatchMail();
                    }
                    AppendReplyMsg(String.Format("{0}:{1}\"同步\"邮件已发送完成。{2}{3}", shiyan, msgCount, watch.ElapsedMilliseconds, Environment.NewLine));
                }
                catch (Exception ex)
                {
                    // 反馈异常信息
                    msg = msg + (ex.InnerException == null ? ex.Message : ex.Message + ex.InnerException.Message) + Environment.NewLine;
                }
                finally
                {
                    // 输出到界面
                    if (msg.Length > 0)
                    {
                        AppendReplyMsg(msg + Environment.NewLine);
                    }
                }
            }

            mail.Reset();
        }
Exemplo n.º 10
0
        public static void SendEmailForOrderStatus(int storeID, int portalID, string recieverEmail, string billingshipping, string tablebody, string additionalFields, string templateName)
        {
            StoreSettingConfig         ssc               = new StoreSettingConfig();
            string                     logosrc           = ssc.GetStoreSettingsByKey(StoreSetting.StoreLogoURL, storeID, portalID, "en-US");
            string                     inquiry           = ssc.GetStoreSettingsByKey(StoreSetting.SendEcommerceEmailTo, storeID, portalID, "en-US");
            MessageTemplateDataContext dbMessageTemplate = new MessageTemplateDataContext(SystemSetting.SageFrameConnectionString);
            MessageTokenDataContext    messageTokenDB    = new MessageTokenDataContext(SystemSetting.SageFrameConnectionString);
            SageFrameConfig            pagebase          = new SageFrameConfig();
            var    template        = dbMessageTemplate.sp_MessageTemplateByMessageTemplateTypeID(SystemSetting.ORDER_STATUS_CHANGED, portalID).SingleOrDefault();
            string messageTemplate = template.Body.ToString();

            if (template != null)
            {
                string[] tokens = GetAllToken(messageTemplate);
                string[] fields = additionalFields.Split('#');

                string orderstatus      = fields[0];
                string storeName        = fields[1];
                string storeDescription = fields[2];
                string customerName     = fields[3];
                string orderID          = fields[4];
                string paymentMethod    = fields[5];
                string shipingMethod    = fields[6];
                string invoice          = fields[7];
                string fullname         = GetFullName(portalID, int.Parse(orderID));
                foreach (string token in tokens)
                {
                    switch (token)
                    {
                    case "%OrderStatus%":
                        messageTemplate = messageTemplate.Replace(token, orderstatus);
                        break;

                    case "%StoreName%":
                        messageTemplate = messageTemplate.Replace(token, storeName);
                        break;

                    case "%StoreDescription%":
                        messageTemplate = messageTemplate.Replace(token, storeDescription);
                        break;

                    case "%ShippingMethod%":
                        messageTemplate = messageTemplate.Replace(token, shipingMethod);
                        break;

                    case "%InvoiceNo%":
                        messageTemplate = messageTemplate.Replace(token, invoice);
                        break;

                    case "%OrderID%":
                        messageTemplate = messageTemplate.Replace(token, orderID);
                        break;

                    case "%BillingShipping%":
                        messageTemplate = messageTemplate.Replace(token, billingshipping);
                        break;

                    case "%PaymentMethodName%":
                        messageTemplate = messageTemplate.Replace(token, paymentMethod);
                        break;

                    case "%DateTimeWithTime%":
                        messageTemplate = messageTemplate.Replace(token, DateTime.Now.ToString("MM/dd/yyyy HH:mm"));
                        break;

                    case "%DateTime%":
                        messageTemplate = messageTemplate.Replace(token, DateTime.Now.ToString("MM/dd/yyyy"));
                        break;

                    case "%CustomerName%":
                        messageTemplate = messageTemplate.Replace(token, fullname);
                        break;

                    case "%LogoSource%":
                        string src = " http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/" + logosrc;
                        messageTemplate = messageTemplate.Replace(token, src);
                        break;

                    case "%ItemDetailsTable%":
                        messageTemplate = messageTemplate.Replace(token, tablebody);
                        break;

                    case "%UserFirstName%":
                        messageTemplate = messageTemplate.Replace(token, fullname);
                        break;

                    case "%UserLastName%":
                        messageTemplate = messageTemplate.Replace(token, "");
                        break;

                    case "%InquiryEmail%":
                        string x =
                            "<a  target=\"_blank\" style=\"text-decoration: none;color: #226ab7;font-style: italic;\" href=\"mailto:" +
                            inquiry + "\" >" + inquiry + "</a>"; messageTemplate = messageTemplate.Replace(token, x);
                        break;
                    }
                }
                // return messageTemplate;

                //  string replacedMessageTemplate = EmailTemplate.GetTemplateForOrderStatus(template.Body, billingShipping, itemTable, additionalFields);
                MailHelper.SendMailNoAttachment(template.MailFrom, recieverEmail, template.Subject, messageTemplate, string.Empty, string.Empty);
            }
        }
        public ActionResult ForgotPassword(string email)
        {
            var userStore = new UserStore<IdentityUser>();
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
            var user = manager.FindByEmail(email);

            if (user == null)
            {
                ViewBag.Message = "Email not found. Please double-check and try again.";
                return View();
            }
            CreateTokenProvider(manager, PASSWORD_RESET);

            var code = manager.GeneratePasswordResetToken(user.Id);
            var callbackUrl = Url.Action("ResetPassword", "Home",
                                         new { userId = user.Id, code = code },
                                         protocol: Request.Url.Scheme);

            string emailBody = "Please reset your password by clicking <a href=\""
                                     + callbackUrl + "\">here</a>";

            MailHelper mailer = new MailHelper();

            string Subject = "Confirm password reset";
            string response = mailer.EmailFromArvixe(
                                       new Message(user.Email, Subject, emailBody));

            if (response.IndexOf("Success") >= 0)
            {
                ViewBag.Message = "A confirm email has been sent. Please check your your email.";
                ViewBag.Email = user.Email;
            }
            else
            {
                ViewBag.Message = response;
            }
            return View();
        }
        public ActionResult CompleteInfo(ClientInterestViewModel client)
        {
            repo.saveClientInfo(client);

            var userStore = new UserStore<IdentityUser>();
            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);

            CreateTokenProvider(manager, EMAIL_CONFIRMATION);

              var user = manager.FindByName(client.userName);
            var code = manager.GenerateEmailConfirmationToken(user.Id);

            var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                            new { userId = user.Id, code = code },
                                                protocol: Request.Url.Scheme);

            string emailBody = "Please confirm your account by clicking this link: <a href=\""
                            + callbackUrl + "\">Confirm Registration</a>";

            MailHelper mailer = new MailHelper();

            string Subject = "Confirm registration";
            string response = mailer.EmailFromArvixe(
                                       new Message(client.email, Subject, emailBody));

            if (response.IndexOf("Success") >= 0)
            {
             //   ViewBag.Message = "A confirm email has been sent. Please check your email.";
                TempData["Message"] = "A confirm email has been sent. Please check your email.";
                return RedirectToAction("CompleteRegistration");
            }
            else {
                ViewBag.Message = response;
            }

            ClientInterestViewModel newClient = repo.getClientInterest(client.userId);
            return View(newClient);
               // return RedirectToAction("UserProfile", new { userName = client.userName});
        }
Exemplo n.º 13
0
        public static void SendMail()
        {
            string HTMLBody = File.ReadAllText(@"C:\Users\SHI YEJIA\Desktop\GameResult-20210429.html");

            MailHelper.SendMail("*****@*****.**", "Result", HTMLBody);
        }
Exemplo n.º 14
0
        public async Task <SendEmailResponse> SendEmailAsync(SendEmailDetails details)
        {
            // Get the SendGrid key
            var apiKey = Dna.FrameworkDI.Configuration["SendGridKey"];

            // Create a new SendGrid client
            var client = new SendGridClient(apiKey);

            // From
            var from = new EmailAddress(details.FromEmail, details.FromName);

            // To
            var to = new EmailAddress(details.ToEmail, details.ToName);

            // Subject
            var subject = details.Subject;

            // Content
            var content = details.Content;

            // Create Email class ready to send
            var msg = MailHelper.CreateSingleEmail(
                from, to, subject,
                // Plain content
                details.IsHTML ? null : details.Content,
                // HTML content
                details.IsHTML ? details.Content : null);

            // Finally, send the email...
            var response = await client.SendEmailAsync(msg);

            // If we succeeded...
            if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
            {
                // Return successful response
                return(new SendEmailResponse());
            }

            // Otherwise, it failed...

            try
            {
                // Get the result in the body
                var bodyResult = await response.Body.ReadAsStringAsync();

                // Deserialize the response
                var sendGridResponse = JsonConvert.DeserializeObject <SendGridResponse>(bodyResult);

                // Add any errors to the response
                var errorResponse = new SendEmailResponse
                {
                    Errors = sendGridResponse?.Errors.Select(f => f.Message).ToList()
                };

                // Make sure we have at least one error
                if (errorResponse.Errors == null || errorResponse.Errors.Count == 0)
                {
                    // Add an unknown error
                    errorResponse.Errors = new List <string>(new[] { "Unknown error from email sending service. Please contact support." });
                }

                // Return the response
                return(errorResponse);
            }
            catch (Exception ex)
            {
                // Break if we are debugging
                if (Debugger.IsAttached)
                {
                    var error = ex;
                    Debugger.Break();
                }

                // If something unexpected happened, return message
                return(new SendEmailResponse
                {
                    Errors = new List <string>(new[] { "Unknown error occurred" })
                });
            }
        }
Exemplo n.º 15
0
        public async Task <ActionResult> Register([FromServices] QRContext context, string emailUser, string password)
        {
            //TODO: make a better way to register users
            //TODO: use Google / Facebook authentication
            //TODO: email valid
            emailUser = emailUser?.ToLower();
            var hash = getHash(password);

            if (hash.Length > 500)
            {
                hash = hash.Substring(0, 500);
            }

            var user = context.SimpleUser.FirstOrDefault(it => it.Email.ToLower() == emailUser);

            if (user != null)
            {
                if (!user.ConfirmedByEmail)
                {
                    return(Content($"email {emailUser} does exists . Check your email"));
                }

                if (user.Password == hash)
                {
                    await SignUser(user);

                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(Content("incorrect password. Press back and try again"));
                }
            }
            user          = new SimpleUser();
            user.Email    = emailUser;
            user.Name     = emailUser;
            user.Password = hash;
            context.Add(user);
            await context.SaveChangesAsync();

            var strSalt = Environment.GetEnvironmentVariable("deploy");

            var    hashids = new Hashids(strSalt);
            var    id      = hashids.EncodeLong(user.Iduser);
            string url     = "http://fsq.apphb.com/Home/GeneratedEmail/" + id;
            var    apiKey  = Environment.GetEnvironmentVariable("SendGridKey");

            var client = new SendGridClient(apiKey);
            var from   = new EmailAddress("*****@*****.**", "Ignat Andrei - QR");
            List <EmailAddress> tos = new List <EmailAddress>
            {
                new EmailAddress(emailUser),
                new EmailAddress("*****@*****.**"),
                new EmailAddress("*****@*****.**")
            };

            var subject     = "Confirmati inregistrarea la QR Code Library ";
            var htmlContent = $"Va rog <strong>confirmati </strong> inscrierea la QR Code library apasand <a href='{url}'>{url}</a>. <br />Multumim!";
            var msg         = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, "", htmlContent, false);
            var response    = await client.SendEmailAsync(msg);

            return(Content("Va rugam verificat emailul( inclusiv spam/ junk) pentru a confirma adresa de email !"));
        }
Exemplo n.º 16
0
 public string test()
 {
     return(MailHelper.SentMail("*****@*****.**", "测试一个邮件\r\n这是一行内容!", "来自测试的邮件!").ToString());
 }
Exemplo n.º 17
0
        public ActionResult Register(RegisteredUser newUser)
        {
            //when user registers in checks model requirements to ensure valid input
            if (ModelState.IsValid)
            {
                CaptchaHelper captchaHelper   = new CaptchaHelper();
                string        captchaResponse = captchaHelper.CheckRecaptcha();
                ViewBag.CaptchaResponse = captchaResponse;

                // add user to database, lock account until email confirmation
                var userStore = new UserStore <IdentityUser>();
                UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore)
                {
                    //set account to lock after consecutive failed login attempts
                    UserLockoutEnabledByDefault          = true,
                    DefaultAccountLockoutTimeSpan        = new TimeSpan(0, 10, 0),
                    MaxFailedAccessAttemptsBeforeLockout = 3
                };

                var identityUser = new IdentityUser()
                {
                    UserName = newUser.UserName,
                    Email    = newUser.Email
                };
                IdentityResult result = manager.Create(identityUser, newUser.Password);

                if (result.Succeeded)
                {
                    samUserRegEntities context = new samUserRegEntities();
                    AspNetUser         user    = context.AspNetUsers
                                                 .Where(u => u.UserName == newUser.UserName).FirstOrDefault();
                    AspNetRole role = context.AspNetRoles
                                      .Where(r => r.Name == "registered").FirstOrDefault();

                    user.AspNetRoles.Add(role);
                    context.SaveChanges();

                    //creates token to be passed to mail helper to allow email confirmation
                    CreateToken ct = new CreateToken();
                    CreateTokenProvider(manager, EMAIL_CONFIRMATION);


                    var code        = manager.GenerateEmailConfirmationToken(identityUser.Id);
                    var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                                 new { userId = identityUser.Id, code = code },
                                                 protocol: Request.Url.Scheme);
                    //send callbackURL to email helper
                    MailHelper mailer = new MailHelper();
                    string     email  = "Please confirm your account by clicking this link: <a href=\""
                                        + callbackUrl + "\">Confirm Registration</a>";
                    string subject = "Please confirm your email";
                    //try
                    //{
                    mailer.EmailFromArvixe(email, identityUser.Email, subject);
                    ViewBag.FakeConfirmation =
                        "An account confirmation has been sent to your email, please confirm before attempting to login";
                    //}
                    //catch (System.Exception ex)
                    //{
                    //    ViewBag.FakeConfirmation = ex.Message;
                    //}
                }
            }
            return(View());
        }
Exemplo n.º 18
0
        public static void SendEmailForSharedWishList(int storeId, int portalId, string cultureName, string senderName, string senderEmail, string receiverEmailDs, string subject, string message, string bodyDetail)
        {
            StoreSettingConfig         ssc               = new StoreSettingConfig();
            string                     logosrc           = ssc.GetStoreSettingsByKey(StoreSetting.StoreLogoURL, storeId, portalId, cultureName);
            MessageTemplateDataContext dbMessageTemplate = new MessageTemplateDataContext(SystemSetting.SageFrameConnectionString);
            MessageTokenDataContext    messageTokenDB    = new MessageTokenDataContext(SystemSetting.SageFrameConnectionString);
            var    template        = dbMessageTemplate.sp_MessageTemplateByMessageTemplateTypeID(SystemSetting.SHARED_WISHED_LIST, portalId).SingleOrDefault();
            string messageTemplate = template.Body.ToString();
            string src             = HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/";

            if (template != null)
            {
                string[] tokens = GetAllToken(messageTemplate);
                foreach (string token in tokens)
                {
                    switch (token)
                    {
                    case "%DateTime%":
                        messageTemplate = messageTemplate.Replace(token, System.DateTime.Now.ToString("MM/dd/yyyy"));
                        break;

                    case "%Username%":
                        messageTemplate = messageTemplate.Replace(token, senderName);
                        break;

                    case "%UserEmail%":
                        messageTemplate = messageTemplate.Replace(token, senderEmail);
                        break;

                    case "%MessageDetails%":
                        messageTemplate = messageTemplate.Replace(token, message);
                        break;

                    case "%ItemDetailsTable%":
                        messageTemplate = messageTemplate.Replace(token, bodyDetail);
                        break;

                    case "%LogoSource%":
                        string imgSrc = "http://" + src + logosrc;
                        messageTemplate = messageTemplate.Replace(token, imgSrc);
                        break;

                    case "%ServerPath%":
                        messageTemplate = messageTemplate.Replace(token, "http://" + src);
                        break;

                    case "%DateYear%":
                        messageTemplate = messageTemplate.Replace(token, System.DateTime.Now.Year.ToString());
                        break;
                    }
                }
            }

            char[]   spliter     = { ',' };
            string[] receiverIDs = receiverEmailDs.Split(spliter);

            for (int i = 0; i < receiverIDs.Length; i++)
            {
                string          receiverEmailID = receiverIDs[i];
                string          emailSuperAdmin;
                string          emailSiteAdmin;
                SageFrameConfig pagebase = new SageFrameConfig();
                emailSuperAdmin = pagebase.GetSettingsByKey(SageFrameSettingKeys.SuperUserEmail);
                emailSiteAdmin  = pagebase.GetSettingsByKey(SageFrameSettingKeys.SiteAdminEmailAddress);
                MailHelper.SendMailNoAttachment(senderEmail, receiverEmailID, subject, messageTemplate, emailSiteAdmin, emailSuperAdmin);
            }
        }
Exemplo n.º 19
0
 public ContentResult sendmail(string email, string title, string content)
 {
     string MessageTo = email; //收件人邮箱地址
     string MessageSubject = title; //邮件主题
     string MessageBody = content + new Random().Next(1000, 999999).ToString(); //邮件内容
     //bool c = ecoBio.Wms.Common.MailHelper.Send(MessageTo, MessageSubject, MessageBody);
     bool c = true;
     MailHelper mh = new MailHelper();
     var img = Image64Base.GetImageStr("d:\\b.jpg");
     var html = "<html><head><title>title</title></head><body>这是内容<hr><br><img src=\"data:image/png;base64," + img + "\" /><br><img src=\"http://www.ecobiotech.com.cn/images/logo.gif\" /></body></html>";
     mh.Mail("*****@*****.**", "*****@*****.**", html, "title", "doumiao@ytk");
     //mh.Mail("*****@*****.**", "*****@*****.**", "<html><head><title>title</title></head><body>这是内容<hr><br><img src=\"data:image/png;base64," + img + "\" /></body></html>", "title", "doumiao@ytk");
        mh.Attachments("~\\Content\\my_pdf\\7459.pdf");
     string m = "成功";
     try
     {
         mh.Send();
     }
     catch (Exception ex)
     { m = ex.Message; }
     return Content(m);
 }
Exemplo n.º 20
0
        public ActionResult Create(SaleViewModel sale)
        {
            var getUserId = Convert.ToInt32(GeneralHelpers.GetUserId());

            if (!ModelState.IsValid)
            {
                ErrorNotification("Satış Eklenemedi!");
                return(RedirectToAction("Create"));
            }
            //satış yapılınca stok miktarından otomatik olarak düşer onay ya da onaylanmama durumuna göre stoklar güncellenir
            //Eğer satılacak ürün stokta varsa ve kalan stok miktarı satılandan büyükse hata döner işlemi yapmaz
            var product  = _productQueryableRepository.Table.AsNoTracking().FirstOrDefault(x => x.ProductId == sale.ProductId);
            var userMail = _userQueryableRepository.Table.AsNoTracking().FirstOrDefault(x => x.UserId == getUserId);

            if (product == null || product.RemainingStockAmount < sale.AmountOfSales)
            {
                ErrorNotification($"Satış Gerçekleşemedi Sattığınız Ürün Miktarı Satabileceğinizden Fazla Gözüküyor! <br /> Satabileceğiniz Ürün Stoğu Miktarı:<strong> {product.RemainingStockAmount.ToString()}</strong>");
                return(RedirectToAction("Create"));
            }
            _saleService.Add(new Sale
            {
                UserId          = getUserId,
                InvoiceImage    = sale.InvoiceImage,
                InvoiceDate     = sale.InvoiceDate,
                AddDate         = DateTime.Now,
                AmountOfSales   = sale.AmountOfSales,
                InvoiceImageExt = ".png",
                InvoiceNo       = sale.InvoiceNo,
                ProductId       = sale.ProductId,
                CustomerId      = sale.CustomerId,
                InvoiceTotal    = sale.InvoiceTotal
            });

            _productService.Update(new Product
            {
                ProductName         = product.ProductName,
                CriticalStockAmount = product.CriticalStockAmount,
                Point                = product.Point,
                PointToMoney         = product.PointToMoney,
                ProductCode          = product.ProductCode,
                ProductShortCode     = product.ProductShortCode,
                StockAmount          = product.StockAmount,
                UnitTypeId           = product.UnitTypeId,
                RemainingStockAmount = product.RemainingStockAmount - sale.AmountOfSales,
                ProductId            = sale.ProductId
            });
            var mailEnable = System.Configuration.ConfigurationManager.AppSettings["MailEnable"];

            if (mailEnable == "true")
            {
                var mail = MailHelper.SendMail(
                    $"{userMail.FirstName + " " + userMail.LastName} Tarafından {sale.InvoiceNo} Fatura Numarasıyla Yeni Bir Satış Gerçekleştirildi.<br/> Lütfen bayipuan.com üzerinde takip ediniz.",
                    $"*****@*****.**", "Yeni Bir Satış Yapıldı!", true);
                if (mail)
                {
                    SuccessNotification("Mail Gönderildi");
                }
                else
                {
                    ErrorNotification("Mail Gönderilemedi!");
                }
            }

            SuccessNotification("Kayıt Eklendi. Yönetici Onayından Sonra Puan Kazanacaksınız!");
            return(RedirectToAction("SaleIndex"));
        }
Exemplo n.º 21
0
        public void PushFileFTP(string localPath)
        {
            // Get the object used to communicate with the server.

            string distantPath = string.Format("ftp://{0}{1}",
                                                ConfigurationManager.AppSettings["ftpServer"],
                                                ConfigurationManager.AppSettings["ftpFilePath"].Replace("#Date#", DateTime.Now.ToString("yyyyMMdd")));
            Program.log("Distant Path : " + distantPath);
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(distantPath);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                // This example assumes the FTP site uses anonymous logon.
                request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ftpLogin"],
                                                            ConfigurationManager.AppSettings["ftpPass"]);

                // Copy the contents of the file to the request stream.

                StreamReader sourceStream = new StreamReader(localPath, true);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                fileContents = Encoding.UTF8.GetPreamble().Concat(fileContents).ToArray();
                //byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                request.ContentLength = fileContents.Length;

                Stream requestStream = request.GetRequestStream();
                //requestStream.
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                Program.log("response : " + response.StatusCode.ToString() + " " + response.StatusDescription);
                //Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

                response.Close();

                MailHelper mh = new MailHelper(MailType.BasicText);
                mh.MailSubject = "Morning Service Collecte Canal";
                mh.MailType = MailType.BasicText;
                mh.Recipients = new List<MailAddress>{new MailAddress("*****@*****.**")};
                mh.Sender = new MailAddress("*****@*****.**");
                mh.ReplyTo = new MailAddress("*****@*****.**");
                mh.SetContentDirect("Ok pour ce matin.");
                mh.Send();
            }
            catch (Exception e)
            {
                Program.log("Exception envoi FTP : " + e.Message + " /// " + e.StackTrace);
            }
        }
Exemplo n.º 22
0
        public ActionResult Edit(ApproveSaleViewModel sale)
        {
            var saleDefault = _queryableRepository.Table.Include("Product").Include("Customer").Include("User").FirstOrDefault(x => x.SaleId == sale.SaleId);

            if (!ModelState.IsValid)
            {
                ErrorNotification("Bir Hata Oluştu");
                return(RedirectToAction("DeleteEdit"));
            }
            var saleImage = _saleService.GetById(sale.SaleId);
            var userMail  = _userQueryableRepository.Table.AsNoTracking().FirstOrDefault(x => x.UserId == sale.UserId);

            try
            {
                if (sale.IsApproved == false)
                {
                    ErrorNotification("Satışı Onaylamadınız! Başka Bir İşlem Yapmak İster misiniz?");
                    return(Redirect(Request.UrlReferrer.ToString()));
                }
                // TODO: Add update logic here
                if (saleImage.InvoiceImage != null)
                {
                    _saleService.Update(new Sale
                    {
                        UserId          = sale.UserId,
                        InvoiceImage    = saleImage.InvoiceImage,
                        InvoiceDate     = sale.InvoiceDate,
                        AddDate         = saleImage.AddDate,
                        AmountOfSales   = sale.AmountOfSales,
                        InvoiceImageExt = ".png",
                        InvoiceNo       = sale.InvoiceNo,
                        ProductId       = sale.ProductId,
                        CustomerId      = sale.CustomerId,
                        SaleId          = sale.SaleId,
                        IsApproved      = sale.IsApproved,
                        ApprovedDate    = DateTime.Now,
                        InvoiceTotal    = sale.InvoiceTotal
                    });
                    _scoreService.Add(new Score
                    {
                        ScoreTotal = sale.AmountOfSales * saleDefault.Product.Point,
                        ScoreType  = ScoreType.UrunModulu,
                        UserId     = sale.UserId,
                        ScoreDate  = DateTime.Now
                    });
                    var mailEnable = System.Configuration.ConfigurationManager.AppSettings["MailEnable"];
                    if (mailEnable == "true")
                    {
                        var mail = MailHelper.SendMail(
                            $"Tebrikler {sale.InvoiceNo} Fatura Numaralı Satışınız Onaylandı.<br/> Lütfen bayipuan.com üzerinde takip ediniz.",
                            $"{userMail.Email}", "Satış Onaylanmadı!", true);
                        if (mail)
                        {
                            SuccessNotification("Mail Gönderildi");
                        }
                        else
                        {
                            ErrorNotification("Mail Gönderilemedi!");
                        }
                    }
                    SuccessNotification("Satış Onaylandı :)");
                    return(RedirectToAction("SaleIndex"));
                }
                _saleService.Update(new Sale
                {
                    UserId          = sale.UserId,
                    InvoiceImage    = sale.InvoiceImage,
                    InvoiceDate     = sale.InvoiceDate,
                    AddDate         = saleImage.AddDate,
                    AmountOfSales   = sale.AmountOfSales,
                    InvoiceImageExt = ".png",
                    InvoiceNo       = sale.InvoiceNo,
                    ProductId       = sale.ProductId,
                    CustomerId      = sale.CustomerId,
                    SaleId          = sale.SaleId,
                    IsApproved      = sale.IsApproved,
                    ApprovedDate    = DateTime.Now,
                    InvoiceTotal    = sale.InvoiceTotal
                });
                _scoreService.Add(new Score
                {
                    ScoreTotal = sale.AmountOfSales * saleDefault.Product.Point,
                    ScoreType  = ScoreType.UrunModulu,
                    UserId     = sale.UserId,
                    ScoreDate  = DateTime.Now
                });
                var mailEnablex = System.Configuration.ConfigurationManager.AppSettings["MailEnable"];
                if (mailEnablex == "true")
                {
                    var onayMail =
                        MailHelper.SendMail(
                            $"Tebrikler {sale.InvoiceNo} Fatura Numaralı Satışınız Onaylandı.<br/> Lütfen bayipuan.com üzerinde takip ediniz.",
                            $"{userMail.Email}", "Satış Onaylanmadı!", true);
                    if (onayMail)
                    {
                        SuccessNotification("Mail Gönderildi");
                    }
                    else
                    {
                        ErrorNotification("Mail Gönderilemedi!");
                    }
                }

                SuccessNotification("Satış Onaylandı :)");
                return(RedirectToAction("SaleIndex"));
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 23
0
        public static void CheckForNameChange(List <User> users, GraphServiceClient graphClient)
        {
            Queue <User> work = new Queue <User>();

            foreach (var user in users)
            {
                work.Enqueue(user);
            }

            int wait = 0;

            while (work.Count > 0)
            {
                wait++;
                Thread.Sleep(25);

                var temp = work.Dequeue();

                /*
                 * User teneoUser;
                 * try
                 * {
                 *  teneoUser = graphClient.Users[temp.Id].Request().GetAsync().Result;
                 * }
                 * catch { teneoUser = null; }*/
                if (temp.Mail != null)
                {
                    if (temp.Mail.Contains("teneo.com"))
                    {
                        Console.WriteLine(temp.DisplayName + " has been updated, sending mail.");
                        String html = System.IO.File.ReadAllText("C:/Rebrand/Misc/Notification.html");
                        html = html.Replace("TENEOAZUREFIRSTNAME", temp.GivenName);
                        // Send mail of MySite reflecting UPN change
                        Message notification = MailHelper.ComposeMail("Your Teneo Email Has Been Updated",
                                                                      html,
                                                                      new List <string>()
                        {
                            temp.Mail
                        });
                        graphClient.Me.SendMail(notification, false).Request().PostAsync();

                        // Changing OneDrive Permissions
                        //var result = UpdatePermissions("C:/Rebrand/Teneo_PEM.txt", graphClient, temp.Id);

                        //if (result != null) { OneDrive.Enqueue(result); }

                        // Send asynchronous call to permission rewrite for this user.
                    }
                    else
                    {
                        Console.WriteLine("\t" + temp.DisplayName + " has not changed yet. . . ");
                        // update user object
                        temp = graphClient.Users[temp.Id].Request().GetAsync().Result;
                        Console.WriteLine("\tupdated user object and re-queueing.");
                        work.Enqueue(temp);
                    }
                }

                /* List<String> moreToDo = new List<String>();
                 * if (wait == 25)
                 * {
                 *   for(int x = 0; x < OneDrive.Count;x++)
                 *   {
                 *       var moreWork = OneDrive.Dequeue();
                 *       var stillMore = UpdatePermissions("C:/Rebrand/Teneo_PEM.txt", graphClient, moreWork);
                 *
                 *       if (stillMore != null) { moreToDo.Add(stillMore); }
                 *   }
                 * }
                 *
                 * OneDrive = new Queue<string>(moreToDo);*/
            }
        }
Exemplo n.º 24
0
        public ActionResult DeleteEdit(NotApproveSaleViewModel sale)
        {
            if (!ModelState.IsValid)
            {
                ErrorNotification("Bir Hata Oluştu");
                return(RedirectToAction("DeleteEdit"));
            }
            var product   = _productQueryableRepository.Table.AsNoTracking().FirstOrDefault(x => x.ProductId == sale.ProductId);
            var saleImage = _saleService.GetById(sale.SaleId);
            var userMail  = _userQueryableRepository.Table.AsNoTracking().FirstOrDefault(x => x.UserId == sale.UserId);

            try
            {
                // TODO: Add update logic here
                if (saleImage.InvoiceImage != null)
                {
                    _saleService.Update(new Sale
                    {
                        UserId          = sale.UserId,
                        InvoiceImage    = saleImage.InvoiceImage,
                        InvoiceDate     = saleImage.InvoiceDate,
                        AddDate         = saleImage.AddDate,
                        AmountOfSales   = saleImage.AmountOfSales,
                        InvoiceImageExt = ".png",
                        InvoiceNo       = saleImage.InvoiceNo,
                        ProductId       = saleImage.ProductId,
                        CustomerId      = saleImage.CustomerId,
                        SaleId          = sale.SaleId,
                        IsApproved      = false,
                        ApprovedDate    = null,
                        NotApproved     = true,
                        NotApprovedDate = DateTime.Now,
                        Reason          = sale.Reason,
                        InvoiceTotal    = sale.InvoiceTotal
                    });
                    _productService.Update(new Product
                    {
                        ProductName = product.ProductName,

                        CriticalStockAmount = product.CriticalStockAmount,
                        Point                = product.Point,
                        PointToMoney         = product.PointToMoney,
                        ProductCode          = product.ProductCode,
                        ProductShortCode     = product.ProductShortCode,
                        StockAmount          = product.StockAmount,
                        UnitTypeId           = product.UnitTypeId,
                        RemainingStockAmount = product.RemainingStockAmount + sale.AmountOfSales,
                        ProductId            = sale.ProductId
                    });
                    var mailEnable = System.Configuration.ConfigurationManager.AppSettings["MailEnable"];
                    if (mailEnable == "true")
                    {
                        var mail = MailHelper.SendMail(
                            $"{sale.InvoiceNo} Fatura Numaralı Satışınız <strong>{sale.Reason}</strong> Gerekçesiyle Onaylanmadı.<br/> Lütfen bayipuan.com üzerinde takip ediniz.",
                            $"{userMail.Email}", "Satış Onaylanmadı!", true);
                        if (mail)
                        {
                            SuccessNotification("Mail Gönderildi");
                        }
                        else
                        {
                            ErrorNotification("Mail Gönderilemedi!");
                        }
                    }

                    ErrorNotification("Satış Reddedildi! Ürün Stoğu Güncellendi");
                    return(RedirectToAction("SaleIndex"));
                }
                _saleService.Update(new Sale
                {
                    UserId          = sale.UserId,
                    InvoiceImage    = null,
                    InvoiceDate     = saleImage.InvoiceDate,
                    AddDate         = saleImage.AddDate,
                    AmountOfSales   = saleImage.AmountOfSales,
                    InvoiceImageExt = ".png",
                    InvoiceNo       = saleImage.InvoiceNo,
                    ProductId       = saleImage.ProductId,
                    CustomerId      = saleImage.CustomerId,
                    SaleId          = sale.SaleId,
                    IsApproved      = false,
                    ApprovedDate    = null,
                    NotApproved     = true,
                    InvoiceTotal    = sale.InvoiceTotal,
                    NotApprovedDate = DateTime.Now,
                    Reason          = sale.Reason
                });
                _productService.Update(new Product
                {
                    ProductName         = product.ProductName,
                    CriticalStockAmount = product.CriticalStockAmount,
                    Point                = product.Point,
                    PointToMoney         = product.PointToMoney,
                    ProductCode          = product.ProductCode,
                    ProductShortCode     = product.ProductShortCode,
                    StockAmount          = product.StockAmount,
                    UnitTypeId           = product.UnitTypeId,
                    RemainingStockAmount = product.RemainingStockAmount + sale.AmountOfSales,
                    ProductId            = sale.ProductId
                });
                var mailEnablex = System.Configuration.ConfigurationManager.AppSettings["MailEnable"];
                if (mailEnablex == "true")
                {
                    var redmail =
                        MailHelper.SendMail(
                            $"{sale.InvoiceNo} Fatura Numaralı Satışınız <strong>{sale.Reason}</strong> Gerekçesiyle Onaylanmadı.<br/> Lütfen bayipuan.com üzerinde takip ediniz.",
                            $"{userMail.Email}", "Satış Onaylanmadı!", true);
                    if (redmail)
                    {
                        SuccessNotification("Mail Gönderildi");
                    }
                    else
                    {
                        ErrorNotification("Mail Gönderilemedi!");
                    }
                }

                ErrorNotification("Satış Reddedildi! Ürün Stoğu Güncellendi");
                return(RedirectToAction("SaleIndex"));
            }
            catch (Exception ex)
            {
                return(View(ex.ToString()));
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// 异步发送邮件
        /// </summary>
        /// <param name="isSimple">是否只发送一条</param>
        /// <param name="autoReleaseSmtp">是否自动释放SmtpClient</param>
        /// <param name="isReuse">是否重用SmtpClient</param>
        private void SendMessageAsync(MailHelper mail, bool isSimple, string shiyan, string msgCount, bool autoReleaseSmtp, bool isReuse)
        {
            AppendReplyMsg(String.Format("{0}:{1}\"异步\"邮件开始。{2}{3}", shiyan, msgCount, watch.ElapsedMilliseconds, Environment.NewLine));

            if (!isReuse || !mail.ExistsSmtpClient())
            {
                SmtpClient client = new SmtpHelper(Config.TestEmailType, false, Config.TestUserName, Config.TestPassword).SmtpClient;
                mail.AsycUserState    = String.Format("{0}:{1}\"异步\"邮件", shiyan, msgCount);
                client.SendCompleted += (send, args) =>
                {
                    AsyncCompletedEventArgs arg = args;

                    if (arg.Error == null)
                    {
                        // 需要注意的事使用 MailHelper 发送异步邮件,其UserState是 MailUserState 类型
                        AppendReplyMsg(((MailUserState)args.UserState).UserState.ToString() + "已发送完成." + watch.ElapsedMilliseconds + Environment.NewLine);
                    }
                    else
                    {
                        AppendReplyMsg(String.Format("{0} 异常:{1}{2}{3}"
                                                     , ((MailUserState)args.UserState).UserState.ToString() + "发送失败."
                                                     , (arg.Error.InnerException == null ? arg.Error.Message : arg.Error.Message + arg.Error.InnerException.Message)
                                                     , watch.ElapsedMilliseconds, Environment.NewLine));
                        // 标识异常已处理,否则若有异常,会抛出异常
                        ((MailUserState)args.UserState).IsErrorHandle = true;
                    }
                };
                mail.SetSmtpClient(client, autoReleaseSmtp);
            }
            else
            {
                mail.AsycUserState = String.Format("{0}:{1}\"异步\"邮件已发送完成。", shiyan, msgCount);
            }

            mail.From            = Config.TestFromAddress;
            mail.FromDisplayName = Config.GetAddressName(Config.TestFromAddress);

            string to  = m_to;
            string cc  = m_cc;
            string bcc = m_bcc;

            if (to.Length > 0)
            {
                mail.AddReceive(EmailAddrType.To, to, Config.GetAddressName(to));
            }
            if (cc.Length > 0)
            {
                mail.AddReceive(EmailAddrType.CC, cc, Config.GetAddressName(cc));
            }
            if (bcc.Length > 0)
            {
                mail.AddReceive(EmailAddrType.Bcc, bcc, Config.GetAddressName(bcc));
            }

            mail.Subject = m_Subject;
            // Guid.NewGuid() 防止重复内容,被SMTP服务器拒绝接收邮件
            mail.Body       = m_Body + Guid.NewGuid();
            mail.IsBodyHtml = true;

            if (filePaths != null && filePaths.Count > 0)
            {
                foreach (string filePath in FilePaths)
                {
                    mail.AddAttachment(filePath);
                }
            }

            Dictionary <MailInfoType, string> dic = mail.CheckSendMail();

            if (dic.Count > 0 && MailInfoHelper.ExistsError(dic))
            {
                // 反馈“错误+提示”信息
                AppendReplyMsg(MailInfoHelper.GetMailInfoStr(dic));
            }
            else
            {
                string msg = String.Empty;
                if (dic.Count > 0)
                {
                    // 反馈“提示”信息
                    msg = MailInfoHelper.GetMailInfoStr(dic);
                }

                try
                {
                    // 发送
                    if (isSimple)
                    {
                        mail.SendOneMail();
                    }
                    else
                    {
                        mail.SendBatchMail();
                    }
                }
                catch (Exception ex)
                {
                    // 反馈异常信息
                    AppendReplyMsg(String.Format("{0}\"异步\"异常:({1}){2}{3}", msgCount, watch.ElapsedMilliseconds, ex.Message, Environment.NewLine));
                }
                finally
                {
                    // 输出到界面
                    if (msg.Length > 0)
                    {
                        AppendReplyMsg(msg + Environment.NewLine);
                    }
                }
            }

            mail.Reset();
        }
Exemplo n.º 26
0
        public async Task <ActionResult> PlaceOrder(Cart cart, OrderDTO order, string paymentMethod)
        {
            if (cart.LineCollection.Count == 0)
            {
                TempData["EmptyMessage"] = "true";
                return(RedirectToAction("index", "cart"));
            }

            // Add paymentMethod
            var addMethodResult = _orderRepo.AddPaymentMethod(order, paymentMethod);

            // Add orderStatus
            var addOrderStatusResult = _orderRepo.UpdateStatus(order, OrderStatusNames.Pending);

            // Check model valid
            if (!ModelState.IsValid || addMethodResult == null || addOrderStatusResult == null)
            {
                var model = new CheckoutViewModel()
                {
                    Order        = order,
                    OrderDetails = GetOrderDetails(cart)
                };
                return(View("index", model));
            }

            // Add userId if authenticated
            if (User.Identity.IsAuthenticated)
            {
                order.UserId = User.Identity.GetUserId();
            }

            // Get order details and calulate summary
            var orderDetails = GetOrderDetails(cart, false);

            order.SubTotal = cart.Summary;



            // Save order to repository
            var result = _orderRepo.Save(order, orderDetails);

            if (result == null)
            {
                TempData["OrderSuccess"] = "false";
                return(RedirectToAction("index", "cart"));
            }

            // Send mail
            var callbackUrl = Url.Action("index", "tracking", new { id = result.Id }, protocol: Request.Url.Scheme);
            var body        = MailHelper.CreateSuccessPlacingOrderEmailBody(ControllerContext, callbackUrl, result.Id);
            var message     = new IdentityMessage
            {
                Subject     = $"Order {result.Id}",
                Destination = result.Email,
                Body        = body
            };
            var emailService = new EmailService();
            await emailService.SendAsync(message);

            TempData["OrderSuccess"] = "true";
            cart.LineCollection.Clear();

            return(RedirectToAction("index", "tracking", new { id = result.Id }));
        }
    static void Main()
    {
        try{
            String[] configs       = File.ReadAllText(Directory.GetCurrentDirectory() + @"/configs.csv").Split(',');
            var      email         = configs[0];
            var      password      = configs[1];
            var      finalLocation = configs[2];
            var      smtpUser      = configs[3];
            var      smtpPass      = configs[4];
            var      alertEmail    = configs[5];
            var      phone         = configs[6];

            var location = Directory.GetCurrentDirectory() + "/";

            //Json copy pasted from a "get all" request to MISO's api
            var json = "{\"QueryValues\":{\"rctype\":\"Load Pocket Report\"},\"NavigationItem\":{\"ParentPropertyValue\":\"Load Pocket Report\",\"ChildPropertySystemName\":null,\"DisplayResultInGrid\":false,\"GridMetadataColumns\":[],\"ResultSortField\":null,\"ResultSortDirection\":null,\"UseDynamicChoiceMode\":null,\"UseDynamicDateNavigation\":false,\"UseDynamicYearNavigation\":false,\"UseDynamicQuarterNavigation\":false,\"UseDynamicMonthNavigation\":false,\"UseDynamicDayNavigation\":false,\"ChildDocumentNavigationItems\":null,\"Title\":\"\",\"Summary\":\"<p><a title=\\\"MISO Load Pocket Report Readers Guide\\\" href=\\\"/api/documents/getbyguid/c35f6b50-fdc2-5742-bd3c-cf185c23ee57\\\">MISO Load Pocket Report Readers Guide</a></p>\",\"LoadedNavigableDocuments\":[{\"FileName\":\"Load_Pocket_20171121.zip\",\"Name\":\"Load Pocket 20171121\",\"Url\":\"/api/documents/getbymediaid/129294\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129294,\"Uploaded\":\"2018-02-26T19:42:50Z\",\"UploadedBy\":34,\"ObjectId\":137504,\"Created\":\"2018-02-26T19:43:06Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:10Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"221e5d05-c71b-5d66-996c-d9c22d10437c\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171122.zip\",\"Name\":\"Load Pocket 20171122\",\"Url\":\"/api/documents/getbymediaid/129295\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129295,\"Uploaded\":\"2018-02-26T19:42:56Z\",\"UploadedBy\":34,\"ObjectId\":137505,\"Created\":\"2018-02-26T19:43:12Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:15Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"e3aaf099-2679-5c51-a1d3-5d309a0447be\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171123.zip\",\"Name\":\"Load Pocket 20171123\",\"Url\":\"/api/documents/getbymediaid/129233\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129233,\"Uploaded\":\"2018-02-26T19:27:55Z\",\"UploadedBy\":34,\"ObjectId\":137443,\"Created\":\"2018-02-26T19:28:11Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:17Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"018ab122-2ac6-52cc-a241-9f033d9b5143\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171124.zip\",\"Name\":\"Load Pocket 20171124\",\"Url\":\"/api/documents/getbymediaid/129234\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129234,\"Uploaded\":\"2018-02-26T19:28:05Z\",\"UploadedBy\":34,\"ObjectId\":137444,\"Created\":\"2018-02-26T19:28:21Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:27Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"f026d520-5e27-51c1-9858-a08fea7fefdd\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171125.zip\",\"Name\":\"Load Pocket 20171125\",\"Url\":\"/api/documents/getbymediaid/129235\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129235,\"Uploaded\":\"2018-02-26T19:28:16Z\",\"UploadedBy\":34,\"ObjectId\":137445,\"Created\":\"2018-02-26T19:28:31Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:38Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"2f4ae535-4c20-57b1-9060-c63a5298229b\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171126.zip\",\"Name\":\"Load Pocket 20171126\",\"Url\":\"/api/documents/getbymediaid/129296\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129296,\"Uploaded\":\"2018-02-26T19:43:02Z\",\"UploadedBy\":34,\"ObjectId\":137506,\"Created\":\"2018-02-26T19:43:18Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:21Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"7763eb39-3bd5-53da-a29a-91be0327d7e2\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171127.zip\",\"Name\":\"Load Pocket 20171127\",\"Url\":\"/api/documents/getbymediaid/129297\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129297,\"Uploaded\":\"2018-02-26T19:43:08Z\",\"UploadedBy\":34,\"ObjectId\":137507,\"Created\":\"2018-02-26T19:43:24Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:27Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"eb27d73c-aa3a-5820-98c8-23fd308d5d18\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171128.zip\",\"Name\":\"Load Pocket 20171128\",\"Url\":\"/api/documents/getbymediaid/129236\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129236,\"Uploaded\":\"2018-02-26T19:28:26Z\",\"UploadedBy\":34,\"ObjectId\":137446,\"Created\":\"2018-02-26T19:28:42Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:47Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"1e6b4040-2c1b-538f-8091-82f51514dcd4\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171129.zip\",\"Name\":\"Load Pocket 20171129\",\"Url\":\"/api/documents/getbymediaid/129237\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129237,\"Uploaded\":\"2018-02-26T19:28:36Z\",\"UploadedBy\":34,\"ObjectId\":137447,\"Created\":\"2018-02-26T19:28:51Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:28:57Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"c9e3df76-6555-5ba6-8f1a-a1476c7a5a1f\",\"accesstype\":\"Visitors-RA\"}},{\"FileName\":\"Load_Pocket_20171130.zip\",\"Name\":\"Load Pocket 20171130\",\"Url\":\"/api/documents/getbymediaid/129298\",\"MimeType\":\"application/zip\",\"MimeTypeName\":\"Compressed archive\",\"MediaId\":129298,\"Uploaded\":\"2018-02-26T19:43:14Z\",\"UploadedBy\":34,\"ObjectId\":137508,\"Created\":\"2018-02-26T19:43:30Z\",\"CreatedBy\":34,\"Updated\":\"2018-02-26T19:43:33Z\",\"UpdatedBy\":34,\"IsFollowing\":false,\"CategoryId\":26,\"AuthorizedRoles\":[\"Visitors-RA\"],\"Metadata\":{\"guid\":\"48c75229-1268-5621-8353-57cc4e89cad6\",\"accesstype\":\"Visitors-RA\"}}],\"TotalAvailableResults\":98},\"Filters\":[{\"PropertyName\":\"rctype\",\"Value\":\"\"}],\"EnableFollowDocuments\":null,\"Top\":null,\"Skip\":10}";

            //Stops from running if files for the current date already exist
            if (FileCheck.Check(finalLocation))
            {
                return;
            }

            var webClient = new CookieAwareWebClient();


            var collection = new NameValueCollection();
            collection.Add("Email", email);
            collection.Add("Password", password);



            Console.Write("Attempting to log in to MISO website... \n");
            webClient.Login("https://www.misoenergy.org/Account/Login", collection);

            //Post JSON using cookie authenticated client and JSON from standard request
            Console.Write("Acquiring document list from MISO... \n");
            var response = webClient.PostPage("https://www.misoenergy.org/api/documents/getnavigabledocuments", json);

            //Parse the response JSON
            JObject parsedResponse = JObject.Parse(response);
            var     list           = parsedResponse["documents"].OrderByDescending(t => t["FileName"]).ToList();
            var     single         = list.FirstOrDefault();
            var     url            = "https://www.misoenergy.org" + single["Url"];
            var     filename       = single["FileName"].ToString();

            //Make sure that the load pocket file that is the "latest" is from the current date.
            if (filename != "Load_Pocket_" + DateTime.Now.ToString("yyyyMMdd") + ".zip")
            {
                throw new Exception("The current load pocket file is not from the current date.");
            }

            //Download zip file, store temporarily in location and the extract to finalLocation before deleting zip from location
            webClient.GetFileAndMove(url, filename, location, finalLocation);


            //Used to send alert on working instance
            if (FileCheck.Check(finalLocation))
            {
                Console.Write("Attempting to send email notifications... \n");
                MailHelper.SendAlert(smtpUser, smtpPass, alertEmail, phone);
            }

            Console.Write(filename + " was extracted to " + finalLocation + "");
        }
        catch (Exception ex)
        {
            Console.Write(ex);
        }
    }
Exemplo n.º 28
0
 public Startup(IConfiguration configuration, IHostingEnvironment env)
 {
     Configuration      = configuration;
     hostingEnvironment = env;
     MailHelper.Initialize(Configuration, env.IsDevelopment());
 }
Exemplo n.º 29
0
        /// <summary>
        /// Send a mail message.
        /// </summary>
        public async Task SendMessageAsync(
            IList <EmailRecipient> recipients,
            string subject,
            string body,
            EmailSender customSender = null,
            ThreadInfo threadInfo    = null)
        {
            if (_apiKey == null)
            {
                // E-mail is disabled.
                return;
            }

            var from = customSender != null
                                ? new EmailAddress(customSender.FromAddress, customSender.Name)
                                : new EmailAddress(DefaultFromAddress, "CS Classroom");
            var tos = recipients
                      .Select(r => new EmailAddress(r.EmailAddress, r.Name))
                      .ToList();

            SendGridMessage msg;

            if (tos.Count == 1)
            {
                msg = MailHelper.CreateSingleEmail
                      (
                    from,
                    tos[0],
                    subject,
                    plainTextContent: null,
                    htmlContent: body
                      );
            }
            else
            {
                msg = MailHelper.CreateSingleEmailToMultipleRecipients
                      (
                    from,
                    tos,
                    subject,
                    plainTextContent: null,
                    htmlContent: body
                      );
            }

            if (threadInfo != null)
            {
                msg.Headers = new Dictionary <string, string>();

                msg.Headers["Message-Id"] = $"<{threadInfo.MessageId}>";

                if (threadInfo.InReplyTo != null)
                {
                    msg.Headers["In-Reply-To"] = $"<{threadInfo.InReplyTo}>";
                }

                if (threadInfo.References != null)
                {
                    msg.Headers["References"] = string.Join
                                                (
                        " ",
                        threadInfo.References.Select(r => $"<{r}>")
                                                );
                }
            }

            var client = new SendGridClient(_apiKey);
            await client.SendEmailAsync(msg);
        }
Exemplo n.º 30
0
 public Startup(IConfiguration configuration, IWebHostEnvironment env)
 {
     _hostEnv      = env;
     Configuration = configuration;
     MailHelper.Initialize(Configuration, env.IsDevelopment());
 }
Exemplo n.º 31
0
        public Person Send(Person p, Enums.MailType type, string additionalinfo)
        {
            if (!IsApproved(p))
                return p;
            PersonPersons = new List<Person>(p.Persons.Select(x => new Person { Name = !string.IsNullOrEmpty(x.Nickname) ? x.Nickname : x.Person.Name, ExternalID = x.Person.ExternalID, ID = x.Person.ID })) { new Person { Name = p.Name, ExternalID = p.ExternalID, ID = p.ID } };
            var body = string.Empty;
            var subject = string.Empty;
            string name;
            //bool includeimages = false;
            var mailHelper = new MailHelper();
            switch (type)
            {
                case Enums.MailType.EventInvitation:
                    name =
                        (PersonPersons.SingleOrDefault(x => x.ID == EventTriggerPerson.ID) ??
                         new Person { Name = EventTriggerPerson.Name }).Name;
                    subject = "This is an invitation from " + name;

                    body = mailHelper.MailTemplate();
                    body = body.Replace("[sma:preheader]", CreatePreHeader("This is an invitation from " + name));
                    
                    body = body.Replace("[sma:invitation]", mailHelper.SmaInvitation(true));
                    body = body.Replace("[sma:eventname]", Event.Name);
                    body = body.Replace("[sma:event]", mailHelper.GetWhenWhereTable(Event, true));
                    body = body.Replace("[sma:optional]", Event.OptionalMessage);
                    if (p.Status == (byte) Enums.PersonStatus.Inaktiv)
                    {
                        body = body.Replace("[sma:firsttime]", mailHelper.GetFirstTimeInfo(EventTriggerPerson));
                        body = body.Replace("[sma:Wall]", mailHelper.SmaWall(Wallposts, p, false));
                        body = body.Replace("[sma:attending]", mailHelper.SmaAttending(EventPersons, p, false, PersonPersons, Event));
                        body = body.Replace("[sma:login]", mailHelper.SmaLink(p, Event, true));
                    }
                    else
                    {
                        body = body.Replace("[sma:firsttime]", string.Empty);
                        body = body.Replace("[sma:Wall]", mailHelper.SmaWall(Wallposts, p, false));
                        body = body.Replace("[sma:attending]", mailHelper.SmaAttending(EventPersons, p, false, PersonPersons, Event));
                        body = body.Replace("[sma:login]", mailHelper.SmaLink(p, Event, true));
                    }
                    

                    break;
                case Enums.MailType.AccountActivated:
                    subject = "Accout activation success, SignMiApp.com";
                    var b = "<h1>Your Activation Succeed!!</h1>";
                    b += "<h2>Welcome " + p.Name + "</h2>";
                    b += "<p><b>Yoyr credentials</b></p>";
                    b += "<p>Username: "******"</p>";
                    b += "<p>Password: "******"</p>";
                    b +=
                        "<br /><br /><p>Change yor password to something more easy to remember, click the cogwheel to change your password</p>";
                    body = mailHelper.MailTemplate();
                    body = body.Replace("[sma:preheader]", CreatePreHeader("Activation succeed, welcome "+p.Name));
                    body = body.Replace("[sma:invitation]", mailHelper.SmaInvitation(false));
                    body = body.Replace("[sma:eventname]", string.Empty);
                    body = body.Replace("[sma:event]", mailHelper.GetWhenWhereTable(Event, false));
                    body = body.Replace("[sma:optional]", b);
                    body = body.Replace("[sma:firsttime]", string.Empty);
                    body = body.Replace("[sma:Wall]", mailHelper.SmaWall(Wallposts, p,  false));
                    body = body.Replace("[sma:attending]", mailHelper.SmaAttending(EventPersons, p, false,  PersonPersons, Event));
                    body = body.Replace("[sma:login]", mailHelper.SmaLink(p, Event, true));

                    break;
                //case Enums.MailType.AccountStart:
                //    subject = "Accout activation one step away, SignMiApp.com";
                //    body += "<h1>Click the link below to activate your account!!</h1>";
                //    body += "<a href='http://www.signmiapp.com/signmiappservice/account/activateaccount/" + p.ExternalID + "'>Activate account</a>";
                //    body = MailTop() + body;

                //    break;
                case Enums.MailType.AccountReset:
                    subject = "Password reset success, SignMiApp.com";
                    var y = "<h1>Your new password!!</h1>";
                    y += "<p>" + p.Password + "</p>";
                    body = mailHelper.MailTemplate();
                    body = body.Replace("[sma:preheader]", CreatePreHeader("Your new password"));
                    body = body.Replace("[sma:invitation]", mailHelper.SmaInvitation(false));
                    body = body.Replace("[sma:eventname]", string.Empty);
                    body = body.Replace("[sma:event]", mailHelper.GetWhenWhereTable(Event, false));
                    body = body.Replace("[sma:optional]", y);
                    body = body.Replace("[sma:firsttime]", string.Empty);
                    body = body.Replace("[sma:Wall]", mailHelper.SmaWall(Wallposts, p, false));
                    body = body.Replace("[sma:attending]", mailHelper.SmaAttending(EventPersons, p, false, PersonPersons, Event));
                    body = body.Replace("[sma:login]", mailHelper.SmaLink(p, Event, true));
                    break;
                case Enums.MailType.PersonlInvitation:
                    subject = "Invitation from SignMiApp.com";
                    body += "<h1>Invitation from SignMiApp</h1>";
                    body += "<h2>Welcome " + p.Name + "</h2><p>You are welcome to use this service to create all types of events and happenings for you and your people.</p>";

                    break;
                case Enums.MailType.EventMessCreated:
                    name =
                            (PersonPersons.SingleOrDefault(x => x.ID == EventTriggerPerson.ID) ??
                             new Person { Name = EventTriggerPerson.Name }).Name;
                    subject = name + " has created a new wallpost for " + Event.Name;
                    body = mailHelper.MailTemplate();
                    body = body.Replace("[sma:preheader]", CreatePreHeader("New wallpost: "+ Event.Wallposts.OrderByDescending(x=>x.Date).First().Message));
                    body = body.Replace("[sma:invitation]", mailHelper.SmaInvitation(false));
                    body = body.Replace("[sma:eventname]", Event.Name);
                    body = body.Replace("[sma:event]", mailHelper.GetWhenWhereTable(Event, true));
                    body = body.Replace("[sma:optional]", string.Empty);
                    body = body.Replace("[sma:firsttime]", string.Empty);
                    body = body.Replace("[sma:Wall]", mailHelper.SmaWall(Wallposts, p, true));
                    body = body.Replace("[sma:attending]", mailHelper.SmaAttending(EventPersons, p, true, PersonPersons, Event));
                    body = body.Replace("[sma:login]", mailHelper.SmaLink(p, Event, true));
                    //body = MailTop() + body;
                    //includeimages = true;
                    break;
                case Enums.MailType.EventSignMiAppStatusChanged:
                    name =
                                (PersonPersons.SingleOrDefault(x => x.ID == EventTriggerPerson.ID) ??
                                 new Person { Name = EventTriggerPerson.Name }).Name;
                    Enums.Attending stat;
                    Enum.TryParse(additionalinfo, out stat);
                    subject = name + "'s new SignMiAppstatus is " + stat;
                    body = mailHelper.MailTemplate();
                    body = body.Replace("[sma:preheader]", CreatePreHeader(name + "'s new SignMiAppstatus is " + stat));
                    body = body.Replace("[sma:invitation]", mailHelper.SmaInvitation(false));
                    body = body.Replace("[sma:eventname]", Event.Name);
                    body = body.Replace("[sma:event]", mailHelper.GetWhenWhereTable(Event, true));
                    body = body.Replace("[sma:optional]", string.Empty);
                    body = body.Replace("[sma:firsttime]", string.Empty);
                    body = body.Replace("[sma:Wall]", mailHelper.SmaWall(Wallposts, p, true));
                    body = body.Replace("[sma:attending]", mailHelper.SmaAttending(EventPersons, p, true, PersonPersons, Event));
                    body = body.Replace("[sma:login]", mailHelper.SmaLink(p, Event, true));
                    //includeimages = true;
                    break;
                case Enums.MailType.EventCancellation:

                    subject = Event.Name + "is canceled";
                    body = mailHelper.MailTemplate();
                    body = body.Replace("[sma:preheader]", CreatePreHeader(Event.Name + "is canceled by "+EventTriggerPerson.Name));
                    body = body.Replace("[sma:invitation]", mailHelper.SmaInvitation(false));
                    body = body.Replace("[sma:eventname]", Event.Name);
                    body = body.Replace("[sma:event]", mailHelper.GetWhenWhereTable(Event, true));
                    body = body.Replace("[sma:optional]", additionalinfo);
                    body = body.Replace("[sma:firsttime]", string.Empty);
                    body = body.Replace("[sma:Wall]", mailHelper.SmaWall(Wallposts, p, true));
                    body = body.Replace("[sma:attending]", mailHelper.SmaAttending(EventPersons, p, true, PersonPersons, Event));
                    body = body.Replace("[sma:login]", mailHelper.SmaLink(p, Event, true));
                    //includeimages = true;
                    break;

                case Enums.MailType.EventReminder:

                    subject = "This is a reminder of " + Event.Name;
                    body = mailHelper.MailTemplate();
                    body = body.Replace("[sma:preheader]", CreatePreHeader("This is a reminder of " + Event.Name));
                    body = body.Replace("[sma:invitation]", mailHelper.SmaInvitation(false));
                    body = body.Replace("[sma:eventname]", Event.Name);
                    body = body.Replace("[sma:event]", mailHelper.GetWhenWhereTable(Event, true));
                    body = body.Replace("[sma:optional]", additionalinfo);
                    body = body.Replace("[sma:firsttime]", string.Empty);
                    body = body.Replace("[sma:Wall]", mailHelper.SmaWall(Wallposts, p,  true));
                    body = body.Replace("[sma:attending]", mailHelper.SmaAttending(EventPersons, p, true,  PersonPersons, Event));
                    body = body.Replace("[sma:login]", mailHelper.SmaLink(p, Event, true));
                    //includeimages = true;
                    break;
                case Enums.MailType.EventConfirmation:

                    subject = "Event confirmation, " + Event.Name;
                    body = mailHelper.MailTemplate();
                    body = body.Replace("[sma:preheader]", CreatePreHeader(Event.Name+ " is confirmed by " + EventTriggerPerson.Name));
                    body = body.Replace("[sma:invitation]", mailHelper.SmaInvitation(false));
                    body = body.Replace("[sma:eventname]", Event.Name);
                    body = body.Replace("[sma:event]", mailHelper.GetWhenWhereTable(Event, true));
                    body = body.Replace("[sma:optional]", additionalinfo);
                    body = body.Replace("[sma:firsttime]", string.Empty);
                    body = body.Replace("[sma:Wall]", mailHelper.SmaWall(Wallposts, p,  true));
                    body = body.Replace("[sma:attending]", mailHelper.SmaAttending(EventPersons, p, true,  PersonPersons, Event));
                    body = body.Replace("[sma:login]", mailHelper.SmaLink(p, Event, true));
                    //includeimages = true;
                    break;
            }

            //body += MailFooter();
            var m = new MailMessage
            {
                Body = body,
                From = new MailAddress("*****@*****.**", "SignMiApp.com"),
                BodyEncoding = System.Text.Encoding.UTF8,
                IsBodyHtml = true,
                Subject = subject,
                SubjectEncoding = System.Text.Encoding.UTF8,


            };
            var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");

            //if (_attachments != null && includeimages)
            //{
            //    foreach (var attachment in _attachments)
            //    {
            //        view.LinkedResources.Add(attachment);
            //    }
            //}
            m.AlternateViews.Add(view);
            m.Bcc.Add(type + "@signmiapp.com");
            try
            {
                m.To.Add(p.Email);
            }
            catch (Exception ex)
            {
                p.Loggs.Add(new Logg { Date = DateTime.Now, Message = ex.Message });
                return p;

            }


            //p.Mails.Add(new Mail
            //{
            //    ExternalID = mailId,
            //    PersonID = p.ID,
            //    Message = mailBody,
            //    Type = (int)type,
            //    Date = DateTime.Now

            //});

            try
            {
                _smtpServer.Send(m);
            }
            catch (Exception ex)
            {
                p.Loggs.Add(new Logg { Date = DateTime.Now, Message = ex.Message });
                return p;
            }
            return p;
        }
Exemplo n.º 32
0
        public ActionResult weeklyserviceemail()
        {
            string name = WebRequest.GetString("name", true);

            #region 查找
            try
            {
                if (Masterpage.CurrUser.email == null || Masterpage.CurrUser.email.ToString() == "")
                {
                    LogHelper.Info(Masterpage.CurrUser.alias, "606013:客户," + Masterpage.CurrUser.client_code + ",邮箱为空,无法发送邮件");
                    return Json(new ReturnValue { message = "邮箱为空,无法发送邮件", status = "error" }, JsonRequestBehavior.AllowGet);
                }
                var filepath = ConfigurationManager.AppSettings["CustomerRes"] + Masterpage.CurrUser.client_code + "/files/servicereport/" + Masterpage.CurrUser.guid.ToString() + "/" + name;
                if (FileHelper.IsFileExist(filepath))
                {
                    #region 发送邮件
                    var send = managementService.GetSendEmailModel();
                    if (send == null)
                    {
                        LogHelper.Info(Masterpage.CurrUser.alias, "606013:客户," + Masterpage.CurrUser.client_code + ",服务报告邮件发送,发送失败未设置系统邮箱");
                        return Json(new ReturnValue { message = "未设置系统邮箱", status = "error" }, JsonRequestBehavior.AllowGet);
                    }
                    MailHelper mh = new MailHelper();
                    var html = "";
                    var title = Masterpage.CurrUser.client_name + "服务报告";
                    mh.Mail(Masterpage.CurrUser.email, send.text, html, title, send.value);
                    mh.Attachments(filepath);

                    try
                    {
                        mh.Send();
                        LogHelper.Info(Masterpage.CurrUser.alias, "606013:客户," + Masterpage.CurrUser.client_code + ",服务报告邮件发送成功" + filepath);
                        return Json(new ReturnValue { message = "", status = "ok" }, JsonRequestBehavior.AllowGet);
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Info(Masterpage.CurrUser.alias, "606013:客户," + Masterpage.CurrUser.client_code + ",服务报告邮件发送,发送失败" + ex.Message);
                        return Json(new ReturnValue { message = ex.Message, status = "error" }, JsonRequestBehavior.AllowGet);
                    }
                    #endregion
                }
                else
                {
                    LogHelper.Info(Masterpage.CurrUser.alias, "606013:客户," + Masterpage.CurrUser.client_code + ",服务报告邮件发送,发送失败,文件不存在" + filepath);
                    return Json(new ReturnValue { message = "文件不存在", status = "error" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception exx)
            {
                LogHelper.Info(Masterpage.CurrUser.alias, "606013:客户," + Masterpage.CurrUser.client_code + ",服务报告邮件发送,发送失败" + exx.Message);
                return Json(new ReturnValue { message = "发送失败", status = "error" }, JsonRequestBehavior.AllowGet);
            }
            #endregion
        }
Exemplo n.º 33
0
        public static void SendNewsLetterEmail(string username, string sendername, string email)
        {
            try
            {
                MailHelper mailhelper = new MailHelper();
                string mailpath = HttpContext.Current.Server.MapPath("~/Layouts/Mails/SendNewsLetter.htm");
                string html = File.ReadAllText(mailpath);
                string fromemail = ConfigurationManager.AppSettings["username"];
                string host = ConfigurationManager.AppSettings["host"];
                string port = ConfigurationManager.AppSettings["port"];
                string pass = ConfigurationManager.AppSettings["pasword"];
                string Body = mailhelper.NewsLetterMail(html, username, sendername, "");
                string Subject = "News From SocialSuitePro Account";
                MailHelper.SendMailMessage(host, int.Parse(port.ToString()), fromemail, pass, email, string.Empty, string.Empty, Subject, Body);

            }
            catch (Exception ex)
            {

                logger.Error(ex.Message);
            }
        }
Exemplo n.º 34
0
        public static void SendEmailForOrder(int portalID, OrderDetailsCollection orderdata, string addressPath, string templateName, string transID)
        {
            StoreSettingConfig ssc = new StoreSettingConfig();
            // sendEmailFrom = ssc.GetStoreSettingsByKey(StoreSetting.SendEcommerceEmailsFrom, storeID, portalID, "en-US");
            string sendOrderNotice = ssc.GetStoreSettingsByKey(StoreSetting.SendOrderNotification, orderdata.ObjCommonInfo.StoreID, portalID, orderdata.ObjCommonInfo.CultureName);
            string logosrc         = ssc.GetStoreSettingsByKey(StoreSetting.StoreLogoURL, orderdata.ObjCommonInfo.StoreID, portalID, orderdata.ObjCommonInfo.CultureName);
            string inquiry         = ssc.GetStoreSettingsByKey(StoreSetting.SendEcommerceEmailTo, orderdata.ObjCommonInfo.StoreID, portalID, orderdata.ObjCommonInfo.CultureName);
            string storeName       = ssc.GetStoreSettingsByKey(StoreSetting.StoreName, orderdata.ObjCommonInfo.StoreID, portalID, orderdata.ObjCommonInfo.CultureName);

            if (bool.Parse(sendOrderNotice))
            {
                MessageTemplateDataContext dbMessageTemplate = new MessageTemplateDataContext(SystemSetting.SageFrameConnectionString);
                MessageTokenDataContext    messageTokenDB    = new MessageTokenDataContext(SystemSetting.SageFrameConnectionString);
                SageFrameConfig            pagebase          = new SageFrameConfig();
                var    template        = dbMessageTemplate.sp_MessageTemplateByMessageTemplateTypeID(SystemSetting.ORDER_PLACED, portalID).SingleOrDefault();
                string messageTemplate = template.Body;
                if (template != null)
                {
                    string[] tokens = GetAllToken(messageTemplate);
                    foreach (string token in tokens)
                    {
                        switch (token)
                        {
                        case "%OrderRemarks%":
                            messageTemplate = messageTemplate.Replace(token, orderdata.ObjOrderDetails.Remarks);
                            break;

                        case "%InvoiceNo%":
                            messageTemplate = messageTemplate.Replace(token, orderdata.ObjOrderDetails.InvoiceNumber);
                            break;

                        case "%OrderID%":
                            messageTemplate = messageTemplate.Replace(token, orderdata.ObjOrderDetails.OrderID.ToString());
                            break;

                        case "%BillingAddress%":
                            string billing = orderdata.ObjBillingAddressInfo.FirstName.ToString() + " " +
                                             orderdata.ObjBillingAddressInfo.LastName.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">";

                            if (orderdata.ObjBillingAddressInfo.CompanyName != null)
                            {
                                billing += orderdata.ObjBillingAddressInfo.CompanyName.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">";
                            }

                            billing += orderdata.ObjBillingAddressInfo.City.ToString() + ", " + orderdata.ObjBillingAddressInfo.Address.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">" +
                                       orderdata.ObjBillingAddressInfo.Country.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">" +
                                       orderdata.ObjBillingAddressInfo.EmailAddress.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">" +
                                       orderdata.ObjBillingAddressInfo.Phone.ToString();
                            messageTemplate = messageTemplate.Replace(token, billing);
                            break;

                        case "%ShippingAddress%":
                            string shipping = "";
                            if (!orderdata.ObjOrderDetails.IsDownloadable)
                            {
                                if (orderdata.ObjOrderDetails.IsMultipleCheckOut == false)
                                {
                                    shipping = orderdata.ObjShippingAddressInfo.FirstName.ToString() + " " +
                                               orderdata.ObjShippingAddressInfo.LastName.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">";
                                    if (orderdata.ObjShippingAddressInfo.CompanyName != null)
                                    {
                                        shipping += orderdata.ObjShippingAddressInfo.CompanyName.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">";
                                    }

                                    shipping += orderdata.ObjShippingAddressInfo.City.ToString() + ", " + orderdata.ObjShippingAddressInfo.Address.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">" +
                                                orderdata.ObjShippingAddressInfo.Country.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">" +
                                                orderdata.ObjShippingAddressInfo.EmailAddress.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">" +
                                                orderdata.ObjShippingAddressInfo.Phone.ToString() + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">";
                                }
                                else
                                {
                                    shipping = "Multiple addresses<br />Plese log in to view." + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">";
                                }
                            }
                            else
                            {
                                shipping = "Your Ordered Item is Downloadable Item." + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">";
                            }

                            messageTemplate = messageTemplate.Replace(token, shipping);
                            break;

                        case "%UserFirstName%":
                            messageTemplate = messageTemplate.Replace(token, orderdata.ObjBillingAddressInfo.FirstName);
                            break;

                        case "%UserLastName%":
                            messageTemplate = messageTemplate.Replace(token, orderdata.ObjBillingAddressInfo.LastName);
                            break;

                        case "%TransactionID%":
                            messageTemplate = messageTemplate.Replace(token, transID);
                            break;

                        case "%PaymentMethodName%":
                            messageTemplate = messageTemplate.Replace(token, orderdata.ObjPaymentInfo.PaymentMethodName);
                            break;

                        case "%DateTimeDay%":
                            messageTemplate = messageTemplate.Replace(token, DateTime.Now.ToString("dddd, dd MMMM yyyy"));
                            break;

                        case "%DateYear%":
                            messageTemplate = messageTemplate.Replace(token, DateTime.Now.Year.ToString());
                            break;

                        case "%CustomerID%":
                            messageTemplate = messageTemplate.Replace(token, orderdata.ObjOrderDetails.CustomerID.ToString());
                            break;

                        case "%PhoneNo%":
                            messageTemplate = messageTemplate.Replace(token, orderdata.ObjBillingAddressInfo.Phone);
                            break;

                        case "%AccountLogin%":
                            string account = "";
                            if (orderdata.ObjCommonInfo.AddedBy.ToString().ToLower() == "anonymoususer" && orderdata.ObjOrderDetails.CustomerID == 0)
                            {       // future login process for annoymoususr
                                account += "Please Register and log in to your <span style=\"font-weight: bold; font-size: 11px;\">AspxCommerce</span>";

                                account += "<a  style=\"color: rgb(39, 142, 230);\"  href=" + addressPath + "User-Registration.aspx" + ">account</a>";
                            }
                            else
                            {
                                account += "  Please log in to your <span style=\"font-weight: bold; font-size: 11px;\">AspxCommerce</span>";

                                account += " <a style=\"color: rgb(39, 142, 230);\"  href=" + addressPath + "Login.aspx" + ">account</a>";
                            }
                            messageTemplate = messageTemplate.Replace(token, account);
                            break;

                        case "%LogoSource%":
                            // string src = " http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/Templates/" + templateName + "/images/aspxcommerce.png";
                            string src = " http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/" + logosrc;
                            messageTemplate = messageTemplate.Replace(token, src);
                            break;

                        case "%DateTime%":
                            messageTemplate = messageTemplate.Replace(token, DateTime.Now.ToString("dd MMMM yyyy "));

                            break;

                        case "%InquiryEmail%":
                            string x =
                                "<a  target=\"_blank\" style=\"text-decoration: none;color: #226ab7;font-style: italic;\" href=\"mailto:" +
                                inquiry + "\" >" + inquiry + "</a>";
                            messageTemplate = messageTemplate.Replace(token, x);
                            break;

                        case "%StoreName%":
                            messageTemplate = messageTemplate.Replace(token, storeName);
                            break;
                        }
                    }
                    // return messageTemplate;
                    MailHelper.SendMailNoAttachment(template.MailFrom, orderdata.ObjBillingAddressInfo.EmailAddress, template.Subject, messageTemplate, string.Empty, string.Empty);
                }
            }
        }
Exemplo n.º 35
0
        public ActionResult servicesemail()
        {
            string guid = WebRequest.GetString("guid", true);
            SiteServiceManagementModel one = new SiteServiceManagementModel();
            #region 查找
            try
            {
                if (Masterpage.CurrUser.email == null || Masterpage.CurrUser.email.ToString() == "")
                {
                    LogHelper.Info(Masterpage.CurrUser.alias, "609014:客户," + Masterpage.CurrUser.client_code + ",服务监管邮件发送失败,guid:" + guid + "用户邮箱为空,无法发送邮件");
                    return Json(new ReturnValue { message = "邮箱为空,无法发送邮件", status = "error" }, JsonRequestBehavior.AllowGet);
                }
                Guid g = Guid.Parse(guid);
                one = managementService.GetSiteServiceManagement(Masterpage.CurrUser.client_code).FirstOrDefault(p => p.service_management_guid == g);
                if (one == null || one.service_content == "")
                {
                    LogHelper.Info(Masterpage.CurrUser.alias, "609014:客户," + Masterpage.CurrUser.client_code + ",服务监管邮件发送失败,guid:" + guid + "未报表未生成");
                    return Json(new ReturnValue { message = "未报表未生成", status = "error" }, JsonRequestBehavior.AllowGet);
                }
                string title = Masterpage.CurrUser.client_name + "[" + one.service_start_time.Value.ToString("yyyyMMdd") + "]现场服务报告";
                //html = html.Replace("$title$", title);
                //html = html.Replace("$number$", one.employee_guid.ToString());
                //html = html.Replace("$employeename$", Masterpage.CurrUser.client_name);
                //html = html.Replace("$starttime$", one.service_start_time.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                //html = html.Replace("$content$", one.service_content);
                //html = html.Replace("$completetime$", one.service_completion_time.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                //html = html.Replace("$checkperson$", one.employee_chinese_name);
                //html = html.Replace("$checktime$", one.service_validate_time.Value.ToString("yyyy-MM-dd HH:mm:ss"));
                //html = html.Replace("$checkcontent$", one.service_validate_comments);

                //createservices(one);
                //string attachment = "~/content/management/" + Masterpage.CurrUser.client_code + "/" + guid + ".pdf";
                string attachment = ConfigurationManager.AppSettings["CustomerRes"] + Masterpage.CurrUser.client_code + "/files/localservice/" + guid + ".pdf";
                #region 发送邮件
                var send = managementService.GetSendEmailModel();
                if (send == null)
                {
                    LogHelper.Info(Masterpage.CurrUser.alias, "609014:客户," + Masterpage.CurrUser.client_code + ",服务监管邮件发送失败,guid:" + guid + "未设置系统邮箱");
                    return Json(new ReturnValue { message = "未设置系统邮箱", status = "error" }, JsonRequestBehavior.AllowGet);
                }
                MailHelper mh = new MailHelper();
                mh.Mail(Masterpage.CurrUser.email, send.text, title, title, send.value);
                mh.Attachments(attachment);

                try
                {
                    mh.Send();
                }
                catch (Exception ex)
                {
                    LogHelper.Info(Masterpage.CurrUser.alias, "609014:客户," + Masterpage.CurrUser.client_code + ",服务监管邮件发送失败,guid:" + guid + ex.Message);
                    return Json(new ReturnValue { message = ex.Message, status = "error" }, JsonRequestBehavior.AllowGet);
                }
                #endregion
                LogHelper.Info(Masterpage.CurrUser.alias, "609014:客户," + Masterpage.CurrUser.client_code + ",服务监管邮件发送成功,guid:" + guid + attachment);
                return Json(new ReturnValue { message = "", status = "ok" }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {
                LogHelper.Info(Masterpage.CurrUser.alias, "609014:客户," + Masterpage.CurrUser.client_code + ",服务监管邮件发送失败,guid:" + guid + ex.Message);
                return Json(new ReturnValue { message = "发送失败" + ex.Message, status = "error" }, JsonRequestBehavior.AllowGet);
            }
            #endregion
        }
Exemplo n.º 36
0
 public MailHelperActionResult(MailHelper mailHelperInstance, Encoding fileEncoding)
 {
     _mailHelperInstance = mailHelperInstance;
     //_pureFileName = completefilePath.Substring(completefilePath.LastIndexOf('\\'));
     _fileEncoding = fileEncoding;
 }
Exemplo n.º 37
0
        partial void Emails_Inserting(Emails entity)
        {
            if (entity.Message == null)
            {
                entity.Message = "";
            }
            if (entity.Subject == null)
            {
                entity.Subject = "";
            }

            UserPrefs latest = null;
            foreach (UserPrefs prefs in this.DataWorkspace.ApplicationData.UserPrefs)
            {
                if (null == prefs)
                {
                    continue;
                }

                if (latest == null)
                    latest = prefs;
                else if (latest.CreatedDate < prefs.CreatedDate)
                    latest = prefs;
            }

            if (latest == null)
            {
                return;
            }
            else if (latest.MailAddress == null || latest.Password == null || latest.DisaplayName == null)
            {
                return;
            }


            MailHelper mailHelper =
                new MailHelper(
                    latest.DisaplayName,
                    entity.ReceiverMail,
                    entity.Receiver,
                    entity.Subject,
                    entity.Message,
                    latest);

            // Send Email
            mailHelper.SendMail();
        }
Exemplo n.º 38
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string  tableName = "rides";
        string  strSql1   = "SELECT * FROM " + tableName + " ORDER BY id";
        DataSet ds        = db.ShowTable(strSql1, tableName);

        if (Session["isAdmin"] == null)//אם הקליינט הוא אורח
        {
            hello     = "שלום אורח חביב";
            connGuest = "<a href='Login.aspx'>התחברות</a> | <a href='Register.aspx'>הרשמה</a>";
        }
        else if (Session["isAdmin"] == "1")//אם הקליינט הוא מנהל
        {
            hello        = "שלום המנהל, " + Session["userName"];
            controlPanel = "<a href='ControlPanel.aspx'>פאנל ניהול</a>|";
            sessAbnd     = "<a href='LogOut.aspx'>התנתק</a>";
        }
        else
        {//אם הקליינט הוא משתמש רגיל
            hello        = "שלום, " + Session["userName"];
            controlPanel = "<a href='ControlPanel.aspx'>פאנל ניהול</a>|";
            sessAbnd     = "<a href='LogOut.aspx'>התנתק</a>";
        }

        //אם זה הדף הראשי של רכיבות
        if (Request.QueryString["post"] == null)
        {
            str += "<h1>רכיבות</h1>";
            str += "<div id='tableWrapper'><table class='oddEven'>";
            str += "<tr class='trFirstRow'><td> שם הטיול </td> <td> תאריך </td><td> יום </td><td> איזור </td><td>אופי</td><td>מרחק</td><td> סטטוס </td> </tr>";

            //הצגת כל הרכיבות שנוצרו
            for (int i = 0; i < ds.Tables[tableName].Rows.Count; i++)
            {
                string  strSql2 = "SELECT fName FROM members WHERE mail = '" + ds.Tables[tableName].Rows[i]["mail"].ToString() + "'";
                DataSet ds2     = db.ShowTable(strSql2, "members");

                string trClassOddEven = "even";

                if (i % 2 == 0)
                {
                    trClassOddEven = "even";
                }
                else
                {
                    trClassOddEven = "odd";
                }

                str += "<tr class='" + trClassOddEven + "'>";

                str += "<td style='text-align: right;'><a href='Rides.aspx?post=" + ds.Tables[tableName].Rows[i]["id"].ToString() + "'><div style='font-size: 14px; font-weight: bold;'>" + ds.Tables[tableName].Rows[i]["routeName"].ToString() + "</div>";
                str += "<div>" + ds2.Tables["members"].Rows[0]["fName"].ToString() + "-" + ds.Tables[tableName].Rows[i]["dateCreate"].ToString() + "</div></a></td>";
                str += "<td><a href='Rides.aspx?post=" + i + "'><div>" + ds.Tables[tableName].Rows[i]["dateRide"].ToString() + "</div>";
                str += "<div>" + ds.Tables[tableName].Rows[i]["rideHourStart"].ToString() + "</div></a></td>";
                str += "<td><a href='Rides.aspx?post=" + i + "'>" + ds.Tables[tableName].Rows[i]["day"].ToString() + "</td>";
                str += "<td><a href='Rides.aspx?post=" + i + "'>" + ds.Tables[tableName].Rows[i]["area"].ToString() + "</a></td>";
                str += "<td><a href='Rides.aspx?post=" + i + "'><div>" + ds.Tables[tableName].Rows[i]["teq"].ToString() + "</div>";
                str += "<div>" + ds.Tables[tableName].Rows[i]["hardness"].ToString() + "</div></a></td>";
                str += "<td><a href='Rides.aspx?post=" + i + "'>" + ds.Tables[tableName].Rows[i]["km"].ToString() + " ק''מ</a></td>";
                str += "<td><a href='Rides.aspx?post=" + i + "'>פתוח להרשמה עד " + ds.Tables[tableName].Rows[i]["maxRiders"].ToString() + " רוכבים";
                str += "<div>רשומים " + int.Parse(ds.Tables[tableName].Rows[i]["numRiders"].ToString()) + "</div></a></td>";

                str += "</tr>";
            }
            str += "</table></div>";
        }
        else//אם זה רכיבה מסויימת
        {
            //מספר הפוסט
            int postNo = int.Parse(Request.QueryString["post"]);

            str += "<br /><div style='font-size: 19px; font-weight: bold;'>" + ds.Tables[tableName].Rows[postNo]["routeName"].ToString() + "</div>";
            str += "<div>";
            str += "<br /><div style='float: right;font-size: 14px;margin: 0 0 0 56px; font-family: Arial, Tahoma;'>";
            str += "<h4 style='font-size:17px;'>פרטי טיול</h4><br /><ul style='list-style-type: none;'>";
            str += "<li><b>איזור: </b>" + ds.Tables[tableName].Rows[postNo]["area"].ToString() + "</li> ";
            str += "<li><b>מרחק: </b>" + ds.Tables[tableName].Rows[postNo]["km"].ToString() + "</li> ";
            str += "<li><b>אופי: </b>" + ds.Tables[tableName].Rows[postNo]["teq"].ToString() + "</li> ";
            str += "<li><b>קושי: </b>" + ds.Tables[tableName].Rows[postNo]["hardness"].ToString() + "</li> ";
            str += "<li><b>טיפוס מצטבר: </b>" + ds.Tables[tableName].Rows[postNo]["up"].ToString() + " מטר</li> ";
            str += "<li><b>ירידות מצטברות: </b>" + ds.Tables[tableName].Rows[postNo]["down"].ToString() + "מטר</li> ";
            str += "<li><b>מסלול מעגלי </b>" + ds.Tables[tableName].Rows[postNo]["circleRoad"].ToString() + "</li> ";

            str += "</ul></div>";

            str += "<div style='float: right;font-size: 14px; margin: 0 0 0 56px; font-family: Arial, Tahoma;'>";
            str += "<h4 style='font-size:17px;'>תאריך, יום ושעה</h4><br /><ul style='list-style-type: none;'>";
            str += "<li>" + ds.Tables[tableName].Rows[postNo]["dateRide"].ToString() + "</li> ";

            string day = ds.Tables[tableName].Rows[postNo]["day"].ToString();
            if (day == "א")
            {
                day = "ראשון";
            }
            if (day == "ב")
            {
                day = "שני";
            }
            if (day == "ג")
            {
                day = "שלישי";
            }
            if (day == "ד")
            {
                day = "רביעי";
            }
            if (day == "ה")
            {
                day = "חמישי";
            }
            if (day == "ו")
            {
                day = "שישי";
            }
            if (day == "ש")
            {
                day = "שבת";
            }
            str += "<li>יום " + day + "</li> ";
            str += "<li>" + ds.Tables[tableName].Rows[postNo]["rideHourEnd"].ToString() + " - " + ds.Tables[tableName].Rows[postNo]["rideHourStart"].ToString() + "</li> ";

            str += "</ul></div>";

            string  strSql3 = "SELECT imgPath,fName,lName,city,mail FROM members WHERE mail = '" + ds.Tables[tableName].Rows[postNo]["mail"].ToString() + "'";
            DataSet ds3     = db.ShowTable(strSql3, "members");

            str += "<div style='float: right;font-size: 14px;margin: 0 0 0 56px; font-family: Arial, Tahoma;'>";
            str += "<h4 style='font-size:17px;'>מוביל הטיול</h4><br /><ul style='list-style-type: none;'>";
            str += "<li><img src='" + ds3.Tables["members"].Rows[0]["imgPath"].ToString() + "' alt='' width='130' height='100' /></li> ";
            str += "<li>" + ds3.Tables["members"].Rows[0]["fName"].ToString() + " " + ds3.Tables["members"].Rows[0]["lName"].ToString() + "</li> ";

            str += "</ul></div>";

            str += "</div>";



            if (Session["userMail"] != null)//אם הקלינט הוא משתמש מחובר ולא אורח
            {
                string mailGroup  = ds.Tables[tableName].Rows[postNo]["ridersMail"].ToString();
                string mailLeader = ds.Tables[tableName].Rows[postNo]["mail"].ToString();

                //אם הקלינט הוא לא מוביל הטיול
                if (ds.Tables[tableName].Rows[postNo]["mail"].ToString().Trim() != Session["userMail"].ToString())
                {
                    if (mailGroup != "")//אם יש כבר אנשים בטיול חוץ מהמוביל
                    {
                        int      counter         = 0;
                        string[] ridersMailArray = mailGroup.Split(',');
                        bool     flag            = false;
                        string   mails           = "";
                        counter += ridersMailArray.Length;

                        for (int i = 0; i < ridersMailArray.Length; i++)
                        {
                            //אם הקליינט נמצא בטיול
                            if (Session["userMail"].ToString() == ridersMailArray[i])
                            {
                                str += "<input type='submit' name='quitTrip' id='quitTrip' value='צא מטיול' /><div style='font-weight: bold; color: red;'>" + err + "</div>";
                                flag = true;
                            }
                            else
                            {
                                //כל המיילים חוץ משלי
                                mails += ridersMailArray[i] + ",";
                            }
                        }
                        if (flag)//אם הקלינט כבר בטיול
                        {
                            if (Request.Form["quitTrip"] != null && Request.Form["quitTrip"] != "")
                            {
                                //if (mails.IndexOf())
                                //{

                                //}
                                //מחיקת המשתמש מהרכיבה
                                string strUpdate = "UPDATE " + tableName + " SET ridersMail='" + mails.Trim(',') + "', numRiders=" + (counter);
                                strUpdate += " WHERE id=" + postNo;

                                db.InsertUpdateDelete(strUpdate);

                                err = "יצאת מטיול זה";
                                Response.Redirect("Rides.aspx?post=" + Request.QueryString["post"]);//רענון הדף
                            }
                        }
                        else//אם הקליינט לא בטיול
                        {
                            str += "<input type='submit' name='joinTrip' id='joinTrip' value='הצטרף לטיול' /><div style='font-weight: bold; color: red;'>" + err + "</div>";
                        }
                    }
                    else
                    {
                        str += "<input type='submit' name='joinTrip' id='joinTrip' value='הצטרף לטיול' /><div style='font-weight: bold; color: red;'>" + err + "</div>";
                    }


                    if (Request.Form["joinTrip"] != null && Request.Form["joinTrip"] != "")//אם הכפתור "הצטרף לטיול" נלחץ
                    {
                        int counter = 1;

                        if (mailGroup != "")//אם יש כבר אנשים בטיול חוץ מהמוביל
                        {
                            string[] ridersMailArray = mailGroup.Split(',');
                            bool     flag            = false;
                            counter += ridersMailArray.Length;
                            for (int i = 0; i < ridersMailArray.Length && !flag; i++)
                            {
                                if (Session["userMail"].ToString() == ridersMailArray[i])
                                {
                                    err  = "הינך רשום לטיול זה";
                                    flag = true;

                                    //רענון הדף
                                    Response.Redirect("Rides.aspx?post=" + Request.QueryString["post"]);
                                }
                            }
                            if (!flag)
                            {
                                string mails     = Session["userMail"].ToString() + "," + mailGroup;
                                string strUpdate = "UPDATE " + tableName + " SET ridersMail='" + mails + "', numRiders=" + (counter + 1);
                                strUpdate += " WHERE id=" + postNo;

                                db.InsertUpdateDelete(strUpdate);
                                err = "נרשמת בהצלחה לטיול זה";

                                //שליחת אימייל למשתמש שנכנס לרכיבה
                                string from    = "*****@*****.**";
                                string to      = Session["userMail"].ToString();
                                string subject = ds.Tables[tableName].Rows[postNo]["routeName"].ToString() + " - RIDE IT";
                                string body    = "<div style='color: rgb(75, 75, 75); padding: 15px;'><img src='http://localhost:13691/RIDEIT010513 _0000/images/logoBig.png' width='112' height='105' style='float: left;' />&nbsp;&nbsp;<img src='http://localhost:13691/RIDEIT010513 _0000/images/logo2Big.png' style='margin: 30px 0 0 0; float: left;' />";
                                body += "<div style='font-size: 26px; font-weight: bold; text-align: right;'>";
                                body += "&nbsp;&nbsp;" + ds.Tables[tableName].Rows[postNo]["routeName"].ToString();
                                body += "</div>";

                                body += "<br /><div style='float: right;font-size: 14px;margin: 0 0 0 56px; font-family: Arial, Tahoma; text-align: right;'>";
                                body += "<h4 style='font-size:17px; text-align: right;'>פרטי טיול</h4><ul style='list-style-type: none; text-align: right;'>";
                                body += "<li><b>איזור: </b>" + ds.Tables[tableName].Rows[postNo]["area"].ToString() + "</li> ";
                                body += "<li><b>מרחק: </b>" + ds.Tables[tableName].Rows[postNo]["km"].ToString() + "</li> ";
                                body += "<li><b>אופי: </b>" + ds.Tables[tableName].Rows[postNo]["teq"].ToString() + "</li> ";
                                body += "<li><b>קושי: </b>" + ds.Tables[tableName].Rows[postNo]["hardness"].ToString() + "</li> ";
                                body += "<li><b>טיפוס מצטבר: </b>" + ds.Tables[tableName].Rows[postNo]["up"].ToString() + " מטר</li> ";
                                body += "<li><b>ירידות מצטברות: </b>" + ds.Tables[tableName].Rows[postNo]["down"].ToString() + "מטר</li> ";
                                body += "<li><b>מסלול מעגלי: </b>" + ds.Tables[tableName].Rows[postNo]["circleRoad"].ToString() + "</li> ";

                                body += "</ul></div>";

                                body += "<div style='float: right;font-size: 14px; margin: 0 0 0 56px; font-family: Arial, Tahoma; text-align: right;'>";
                                body += "<h4 style='font-size:17px;'>תאריך, יום ושעה</h4><ul style='list-style-type: none;'>";
                                body += "<li>" + ds.Tables[tableName].Rows[postNo]["dateRide"].ToString() + "</li> ";

                                day = ds.Tables[tableName].Rows[postNo]["day"].ToString();
                                if (day == "א")
                                {
                                    day = "ראשון";
                                }
                                if (day == "ב")
                                {
                                    day = "שני";
                                }
                                if (day == "ג")
                                {
                                    day = "שלישי";
                                }
                                if (day == "ד")
                                {
                                    day = "רביעי";
                                }
                                if (day == "ה")
                                {
                                    day = "חמישי";
                                }
                                if (day == "ו")
                                {
                                    day = "שישי";
                                }
                                if (day == "ש")
                                {
                                    day = "שבת";
                                }
                                body += "<li>" + day + "</li> ";
                                body += "<li>" + ds.Tables[tableName].Rows[postNo]["rideHourEnd"].ToString() + " - " + ds.Tables[tableName].Rows[postNo]["rideHourStart"].ToString() + "</li> ";

                                body += "</ul></div>";

                                body += "<div style='float: right;font-size: 14px;margin: 0 0 0 56px; font-family: Arial, Tahoma; text-align: right;'>";
                                body += "<h4 style='font-size:17px;'>מוביל הטיול</h4><ul style='list-style-type: none;'>";
                                body += "<li><a href='" + mailLeader + "'><img src='http://localhost:13691/RIDEIT010513%20_0000/";
                                body += ds3.Tables["members"].Rows[0]["imgPath"].ToString() + "' alt='' width='130' height='100' style='border: #aaaaaa solid 1px;' /></a></li> ";
                                body += "<li><a href='" + mailLeader + "'>" + ds3.Tables["members"].Rows[0]["fName"].ToString() + " " + ds3.Tables["members"].Rows[0]["lName"].ToString() + "</a></li> ";

                                body += "</ul></div>";

                                body += "<div style='clear: right;margin: 170px auto 30px auto;width: 90%;'><hr /></div>";//divider

                                body += "<div style='clear: right;'>";

                                bool f1 = false;
                                bool f2 = false;
                                body += "<div style='float: right; text-align: right;'>";
                                if (ds.Tables[tableName].Rows[postNo]["howToGet"].ToString().Trim() != "")
                                {
                                    body += "<div style='font-size: 14px; margin: 0 0 30px 20px; font-family: Arial, Tahoma;'>";
                                    body += "<h4 style='font-size:17px;'>הסבר הגעה</h4>";
                                    body += "<div style='width: 240px;'>" + ds.Tables[tableName].Rows[postNo]["howToGet"].ToString() + "</div>";
                                    body += "</div>";

                                    f1 = true;
                                }

                                if (ds.Tables[tableName].Rows[postNo]["bring"].ToString().Trim() != "")
                                {
                                    body += "<div style='font-size: 14px;margin: 0 0 30px 20px; font-family: Arial, Tahoma;'>";
                                    body += "<h4 style='font-size:17px;'>מה להביא</h4>";
                                    body += "<div style='width: 240px;'>" + ds.Tables[tableName].Rows[postNo]["bring"].ToString() + "</div>";
                                    body += "</div>";

                                    f2 = true;
                                }
                                body += "</div>";
                                if (f1 && f2)
                                {
                                    if (ds.Tables[tableName].Rows[postNo]["bring"].ToString() != "" || ds.Tables[tableName].Rows[postNo]["howToGet"].ToString() != "")
                                    {
                                        body += "<div style='float: right; background: grey;width: 1px; height:150px; margin: 30px 0 0 0'></div>";//divider
                                    }
                                }
                                if (ds.Tables[tableName].Rows[postNo]["content"].ToString().Trim() != "")
                                {
                                    body += "<div style='float: right;font-size: 14px;margin: 0 20px 0 56px; font-family: Arial, Tahoma; text-align: right;'>";
                                    body += "<h4 style='font-size:17px;'>תיאור הרכיבה</h4>";
                                    body += "<div style='width: 500px;'>" + ds.Tables[tableName].Rows[postNo]["content"].ToString() + "</div>";
                                    body += "</div>";
                                }
                                body += "</div>";

                                //ביצוע שליחת האימייל
                                MailHelper reminder = new MailHelper(from, to, null, null, subject, body);
                                reminder.SendMailMessage();

                                Response.Redirect("Rides.aspx?post=" + Request.QueryString["post"]);//רענון הדף
                            }
                        }
                        else
                        {
                            string strUpdate = "UPDATE " + tableName + " SET ridersMail='" + Session["userMail"].ToString() + "', numRiders=" + (counter + 1);
                            strUpdate += " WHERE id=" + postNo;
                            db.InsertUpdateDelete(strUpdate);

                            err = "נרשמת בהצלחה לטיול זה";
                            Response.Redirect("Rides.aspx?post=" + Request.QueryString["post"]);//רענון הדף
                        }
                    }
                }
                else//אם הקלינט הוא מוביל הטיול
                {
                    str += "<a href='UpdateRide.aspx?id=" + postNo + "'><input type='button' value='עדכן טיול' style='margin: 0 0 0 10px;' /></a>";
                    str += "<a href='DeleteRide.aspx?id=" + postNo + "'><input type='button' value='מחק טיול' /></a>";
                }
            }
            else//אם הקלינט הוא אורח
            {
                str += "<input type='submit' name='joinTrip' id='joinTrip' value='הצטרף לטיול' /><div style='font-weight: bold; color: red;'>" + err + "</div>";

                if (Request.Form["joinTrip"] != null && Request.Form["joinTrip"] != "")//אם הכפתור "הצטרף לטיול" נלחץ
                {
                    Response.Redirect("Login.aspx");
                }
            }

            str += "<div style='clear: right;margin: 170px auto 30px auto;width: 90%;'><hr /></div>";//divider

            bool g1 = false;
            bool g2 = false;
            str += "<div style='float: right;'>";
            if (ds.Tables[tableName].Rows[postNo]["howToGet"].ToString().Trim() != "")
            {
                str += "<div style='font-size: 14px; margin: 0 0 30px 20px; font-family: Arial, Tahoma;'>";
                str += "<h4 style='font-size:17px;'>הסבר הגעה</h4><br />";
                str += "<div style='width: 240px;'>" + ds.Tables[tableName].Rows[postNo]["howToGet"].ToString() + "</div>";
                str += "</div>";

                g1 = true;
            }

            if (ds.Tables[tableName].Rows[postNo]["bring"].ToString().Trim() != "")
            {
                str += "<div style='font-size: 14px;margin: 0 0 30px 20px; font-family: Arial, Tahoma;'>";
                str += "<h4 style='font-size:17px;'>מה להביא</h4><br />";
                str += "<div style='width: 240px;'>" + ds.Tables[tableName].Rows[postNo]["bring"].ToString() + "</div>";
                str += "</div>";

                g2 = true;
            }
            str += "</div>";
            if (g1 && g2)
            {
                if (ds.Tables[tableName].Rows[postNo]["bring"].ToString() != "" || ds.Tables[tableName].Rows[postNo]["howToGet"].ToString() != "")
                {
                    str += "<div style='float: right; background: grey;width: 1px; height:150px; margin: 30px 0 0 0'></div>";//divider
                }
            }
            if (ds.Tables[tableName].Rows[postNo]["content"].ToString().Trim() != "")
            {
                str += "<div style='float: right;font-size: 14px;margin: 0 20px 0 56px; font-family: Arial, Tahoma;'>";
                str += "<h4 style='font-size:17px;'>תיאור הרכיבה</h4><br />";
                str += "<div style='width: 500px;'>" + ds.Tables[tableName].Rows[postNo]["content"].ToString() + "</div>";
                str += "</div>";
            }

            //הצגת רשימת המשתתפים
            str += "<div style='padding: 22px 0 0 0;clear:right; font-size: 14px;margin: 60px 0 0 56px; font-family: Arial, Tahoma;'>";
            str += "<h4 style='font-size:17px;'>רשימת משתתפים</h4><br />";
            str += "<div id='tableWrapper'><table class='oddEven' style='width:100%;'>";
            str += "<tr class='trFirstRow'><td> שם משתתף </td><td> איזור </td> </tr>";


            //הצגת מוביל הטיול ראשון
            str += "<tr class='odd'>";
            str += "<td style='text-align: right;'><a href='PersonInfo.aspx?mail=" + ds3.Tables["members"].Rows[0]["mail"].ToString() + "'><img src='" + ds3.Tables["members"].Rows[0]["imgPath"].ToString() + "' alt='' width='40' height='30' style='float:right; margin: 0 5px 0 9px;' /><div style='font-size: 14px; font-weight: bold;'>" + ds3.Tables["members"].Rows[0]["fName"].ToString() + " " + ds3.Tables["members"].Rows[0]["lName"].ToString() + "</div> מוביל /ה</a></td>";
            str += "<td><a href='#'><div>" + ds3.Tables["members"].Rows[0]["city"].ToString() + "</div></a></td>";
            str += "</tr>";


            string mailGroup2         = ds.Tables[tableName].Rows[postNo]["ridersMail"].ToString();
            string[] ridersMailArray2 = mailGroup2.Split(',');

            //הצגת שאר המשתמשים
            for (int i = 0; i < ridersMailArray2.Length; i++)
            {
                if (ridersMailArray2[i].Trim() != "" && ridersMailArray2[i].Trim() != null)
                {
                    string  strSql4 = "SELECT imgPath,fName,lName,city,mail FROM members WHERE mail = '" + ridersMailArray2[i].Trim() + "'";
                    DataSet ds4     = db.ShowTable(strSql4, "members");

                    string trClassOddEven = "even";

                    if (i % 2 == 0)
                    {
                        trClassOddEven = "even";
                    }
                    else
                    {
                        trClassOddEven = "odd";
                    }

                    str += "<tr class='" + trClassOddEven + "'>";

                    str += "<td style='text-align: right;'><a href='PersonInfo.aspx?mail=" + ds4.Tables["members"].Rows[0]["mail"].ToString() + "'><img src='" + ds4.Tables["members"].Rows[0]["imgPath"].ToString() + "' alt='' width='40' height='30' style='float:right; margin: 0 5px 0 9px;' /><div style='font-size: 14px; font-weight: bold;'>" + ds4.Tables["members"].Rows[0]["fName"].ToString() + " " + ds4.Tables["members"].Rows[0]["lName"].ToString() + "</div></a></td>";
                    str += "<td><a href='Rides.aspx?post=" + i + "'><div>" + ds4.Tables["members"].Rows[0]["city"].ToString() + "</div></a></td>";

                    str += "</tr>";
                }
            }
            str += "</table></div></div>";
            str += "מספר המשתתפים: " + ds.Tables[tableName].Rows[postNo]["numRiders"].ToString();
        }
    }
 protected void wzdForgotPassword_NextButtonClick(object sender, WizardNavigationEventArgs e)
 {
     try
     {
         if (ValidateCaptcha())
         {
             MembershipController member = new MembershipController();
             if (txtEmail.Text != "" && txtUsername.Text != "")
             {
                 UserInfo user = member.GetUserDetails(GetPortalID, txtUsername.Text);
                 if (user.UserExists)
                 {
                     if (user.IsApproved == true)
                     {
                         if (user.Email.ToLower().Equals(txtEmail.Text.ToLower()))
                         {
                             ForgotPasswordInfo objInfo = UserManagementController.GetMessageTemplateByMessageTemplateTypeID(SystemSetting.PASSWORD_FORGOT_USERNAME_PASSWORD_MATCH, GetPortalID);
                             if (objInfo != null)
                             {
                                 ((Literal)WizardStep2.FindControl("litInfoEmailFinish")).Text = objInfo.Body;
                             }
                             List <ForgotPasswordInfo> objList = UserManagementController.GetMessageTemplateListByMessageTemplateTypeID(SystemSetting.PASSWORD_CHANGE_REQUEST_EMAIL, GetPortalID);
                             foreach (ForgotPasswordInfo objPwd in objList)
                             {
                                 DataTable      dtTokenValues           = UserManagementController.GetPasswordRecoveryTokenValue(txtUsername.Text, GetPortalID);
                                 CommonFunction comm                    = new CommonFunction();
                                 string         replaceMessageSubject   = MessageToken.ReplaceAllMessageToken(objPwd.Subject, dtTokenValues);
                                 string         replacedMessageTemplate = MessageToken.ReplaceAllMessageToken(objPwd.Body, dtTokenValues);
                                 try
                                 {
                                     MailHelper.SendMailNoAttachment(objPwd.MailFrom, txtEmail.Text, replaceMessageSubject, replacedMessageTemplate, string.Empty, string.Empty);
                                 }
                                 catch (Exception)
                                 {
                                     //divForgotPwd.Visible = false;
                                     InitializeCaptcha();
                                     CaptchaValue.Text = string.Empty;
                                     FailureText.Text  = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("PasswordRecovery", "SecureConnectionFPError"));
                                     e.Cancel          = true;
                                 }
                             }
                         }
                         else
                         {
                             InitializeCaptcha();
                             CaptchaValue.Text = string.Empty;
                             FailureText.Text  = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("PasswordRecovery", "UsernameOrEmailAddressDoesnotMatched"));
                             e.Cancel          = true;
                         }
                     }
                     else
                     {
                         InitializeCaptcha();
                         CaptchaValue.Text = string.Empty;
                         FailureText.Text  = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("PasswordRecovery", "UsernameNotActivated"));
                         e.Cancel          = true;
                     }
                 }
                 else
                 {
                     InitializeCaptcha();
                     CaptchaValue.Text = string.Empty;
                     FailureText.Text  = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("UserManagement", "UserDoesNotExist"));
                     e.Cancel          = true;
                 }
             }
             else
             {
                 InitializeCaptcha();
                 e.Cancel          = true;
                 CaptchaValue.Text = string.Empty;
                 FailureText.Text  = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("PasswordRecovery", "PleaseEnterAllTheRequiredFields"));
             }
         }
         else
         {
             InitializeCaptcha();
             e.Cancel          = true;
             CaptchaValue.Text = string.Empty;
         }
     }
     catch (Exception ex)
     {
         ProcessException(ex);
     }
 }
Exemplo n.º 40
0
 public static async Task SendGridSendAsync(string apiKey, string from, string to, string subject, string body)
 {
     var client   = new SendGridClient(apiKey);
     var message  = MailHelper.CreateSingleEmail(new EmailAddress(from), new EmailAddress(to), subject, body, body);
     var response = await client.SendEmailAsync(message);
 }
Exemplo n.º 41
0
 private static void Main_MailHelper(string[] args)
 {
     var msg = "";
     var sendMail = new MailHelper("smtp.sina.com", 25, "*****@*****.**", "123456", new string[] { "你自己的邮箱@qq.com" }, "title is hitch send", "body is xxxx", false);
     sendMail.Send(out msg);
 }
Exemplo n.º 42
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            string _res = string.Empty;

            using (var ctx = new RachnaDBContext())
            {
                int   productId     = Convert.ToInt32(hdnOrderId.Value);
                Order _productOrder = new Order();
                _productOrder = ctx.Orders.ToList().Where(m => m.Order_Id == productId).FirstOrDefault();

                if (_productOrder.Order_Status != eOrderStatus.Rejected.ToString())
                {
                    if (_productOrder.Order_Status != ddlSorderStatus.Text)
                    {
                        if (_productOrder.Order_Status ==
                            eOrderStatus.Approved.ToString() &&
                            (ddlSorderStatus.Text == eOrderStatus.Placed.ToString() ||
                             ddlSorderStatus.Text == eOrderStatus.Approved.ToString()))
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "Order", "new Messi('update failed because, order status is lower then current.', { title: 'Failed!! ' });", true);
                        }
                        else if (_productOrder.Order_Status ==
                                 eOrderStatus.Packed.ToString() &&
                                 (ddlSorderStatus.Text == eOrderStatus.Placed.ToString() ||
                                  ddlSorderStatus.Text == eOrderStatus.Approved.ToString() ||
                                  ddlSorderStatus.Text == eOrderStatus.Packed.ToString()))
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "Order", "new Messi('update failed because, order status is lower then current.', { title: 'Failed!! ' });", true);
                        }
                        else if (_productOrder.Order_Status == eOrderStatus.Shipped.ToString() &&
                                 (ddlSorderStatus.Text == eOrderStatus.Placed.ToString() ||
                                  ddlSorderStatus.Text == eOrderStatus.Approved.ToString() ||
                                  ddlSorderStatus.Text == eOrderStatus.Packed.ToString() ||
                                  ddlSorderStatus.Text == eOrderStatus.Shipped.ToString()))
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "Order", "new Messi('update failed because, order status is lower then current.', { title: 'Failed!! ' });", true);
                        }
                        else if (_productOrder.Order_Status == eOrderStatus.Delevery.ToString() &&
                                 (ddlSorderStatus.Text == eOrderStatus.Placed.ToString() ||
                                  ddlSorderStatus.Text == eOrderStatus.Approved.ToString() ||
                                  ddlSorderStatus.Text == eOrderStatus.Packed.ToString() ||
                                  ddlSorderStatus.Text == eOrderStatus.Shipped.ToString()))
                        {
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "Order", "alert('update failed because, order status is lower then current');", true);
                        }
                        else
                        {
                            _productOrder.Order_Status     = ddlSorderStatus.Text;
                            ctx.Entry(_productOrder).State = EntityState.Modified;
                            ctx.SaveChanges();

                            var            adminId      = Convert.ToInt32(Session[ConfigurationSettings.AppSettings["AdminSession"].ToString()]);
                            Administrators _adm         = ctx.Administrator.Where(m => m.Administrators_Id == adminId).FirstOrDefault();
                            OrderHistory   _orderCancel = new OrderHistory();
                            _orderCancel.Order_Id = Convert.ToInt32(hdnOrderId.Value);
                            _orderCancel.OrderHistory_Description = txtOrderDescription.Text;
                            _orderCancel.OrderHistory_Status      = ddlSorderStatus.Text;
                            _orderCancel.OrderHistory_CreatedDate = DateTime.Now;
                            _orderCancel.OrderHistory_UpdatedDate = DateTime.Now;
                            _orderCancel.Administrators_Id        = _adm.Administrators_Id;
                            _orderCancel.Store_Id = _adm.Store_Id;

                            ctx.OrderHistories.Add(_orderCancel);
                            ctx.SaveChanges();

                            if (pnlDeleveryTeam.Visible == true)
                            {
                                OrderDelivery OrderDelivery = new OrderDelivery()
                                {
                                    Order_Id          = _productOrder.Order_Id,
                                    Administrators_Id = Convert.ToInt32(Session[ConfigurationSettings.AppSettings["AdminSession"].ToString()].ToString()),
                                    TeamId            = Convert.ToInt32(ddlDelieveryTeam.SelectedValue.ToString()),
                                    Comment           = txtOrderDescription.Text,
                                    Status            = eOrderDeliveryStatus.InTransist.ToString(),
                                    Store_Id          = _productOrder.Store_Id,
                                    Customer_Id       = _productOrder.Customer_Id,
                                    DateCreated       = DateTime.Now,
                                    DateUpdated       = DateTime.Now
                                };

                                ctx.OrderDelivery.Add(OrderDelivery);
                                ctx.SaveChanges();
                            }

                            Customers _cust = ctx.Customer.ToList().Where(m => m.Customer_Id == Convert.ToInt32(_productOrder.Customer_Id)).FirstOrDefault();

                            string productUrl = "http://rachnateracotta.com/product/index?id=" + _productOrder.Product_Id;
                            _res = _res + "<tr style='border: 1px solid black;'><td style='border: 1px solid black;'><img src='" + _productOrder.Product_Banner + "' width='100' height='100'/></td>"
                                   + "<td style='border: 1px solid black;'><a href='" + productUrl + "'>" + _productOrder.Product_Title + "</a></td><td style='border: 1px solid black;'> Total Quantity :" + _productOrder.Order_Qty + " </td><td style='border: 1px solid black;'> " + _productOrder.Order_Price + " </td></tr>";

                            if (Convert.ToBoolean(ConfigurationSettings.AppSettings["IsEmailEnable"]))
                            {
                                string host = string.Empty;
                                host = "<table style='width:100%'>" + _res + "</ table >";
                                string body = MailHelper.CustomerOrderProcessed(host, (_cust.Customers_FullName), txtOrderDescription.Text);
                                MailHelper.SendEmail(_cust.Customers_EmailId, "Success!!! " + txtOrderDescription.Text + " Rachna Teracotta Estore.", body, "Rachna Teracotta Order" + txtOrderDescription.Text);
                            }

                            Response.Redirect("/administration/salesmanagement/vorderdetail.aspx?orderId=" + hdnOrderId.Value + "&requesttype=view-order-detail.html");
                        }
                    }
                    else
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), "Order", "new Messi('update failed because, order status is same as current.', { title: 'Failed!! ' });", true);
                    }
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "Order", "new Messi('update failed because, order status is not valid.', { title: 'Failed!! ' });", true);
                }
            }
        }
 public AppManager()
 {
     DataAccess = new AccessDB(dbINFO._SRV, dbINFO._CAT, dbINFO._UID, dbINFO._PWD);
     AppLogin = new AppLoginHelper();
     Utility = new UtilityHelper();
     SendMail = new MailHelper();
     Report = new ReportHelper(Utility, dbINFO._SRV, dbINFO._CAT, dbINFO._UID, dbINFO._PWD);
 }
Exemplo n.º 44
0
        public static void SendEmailForOrderSIM(int orderId, int storeID, int portalID, string custom, string billing, string billingadd, string billingcity, string shipping, string shippingadd, string shippingcity, string payment, string info, string templateName, string transID, string remarks)
        {
            string[]           infos    = info.Split('#');
            string[]           payments = payment.Split('#');
            string[]           ids      = custom.Split('#');
            StoreSettingConfig ssc      = new StoreSettingConfig();
            // sendEmailFrom = ssc.GetStoreSettingsByKey(StoreSetting.SendEcommerceEmailsFrom, storeID, portalID, "en-US");
            string sendOrderNotice = ssc.GetStoreSettingsByKey(StoreSetting.SendOrderNotification, storeID, portalID, "en-US");
            string logosrc         = ssc.GetStoreSettingsByKey(StoreSetting.StoreLogoURL, storeID, portalID, "en-US");
            string storeName       = ssc.GetStoreSettingsByKey(StoreSetting.StoreName, storeID, portalID, "en-US");
            string inquiry         = ssc.GetStoreSettingsByKey(StoreSetting.SendEcommerceEmailTo, storeID, portalID, "en-US");

            if (bool.Parse(sendOrderNotice))
            {
                MessageTemplateDataContext dbMessageTemplate = new MessageTemplateDataContext(SystemSetting.SageFrameConnectionString);
                MessageTokenDataContext    messageTokenDB    = new MessageTokenDataContext(SystemSetting.SageFrameConnectionString);
                SageFrameConfig            pagebase          = new SageFrameConfig();
                var    template        = dbMessageTemplate.sp_MessageTemplateByMessageTemplateTypeID(SystemSetting.ORDER_PLACED, portalID).SingleOrDefault();
                string messageTemplate = template.Body;
                if (template != null)
                {
                    string[] tokens = GetAllToken(messageTemplate);
                    foreach (string token in tokens)
                    {
                        switch (token)
                        {
                        case "%OrderRemarks%":
                            messageTemplate = messageTemplate.Replace(token, remarks);
                            break;

                        case "%InvoiceNo%":
                            messageTemplate = messageTemplate.Replace(token, infos[3].ToString());
                            break;

                        case "%OrderID%":
                            messageTemplate = messageTemplate.Replace(token, orderId.ToString());
                            break;

                        case "%BillingAddress%":
                            string billingfull = billing + billingadd + billingcity;
                            messageTemplate = messageTemplate.Replace(token, billingfull);
                            break;

                        case "%ShippingAddress%":
                            string shippingFull = "";
                            if (!bool.Parse(infos[5].ToString()))
                            {
                                if (bool.Parse(infos[6].ToString()) == false)
                                {
                                    shippingFull = shipping + shippingcity + shippingadd;
                                }
                                else
                                {
                                    shippingFull = "Multiple addresses<br />Plese log in to view." + "</td></tr><tr><td height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">";
                                }
                            }
                            else
                            {
                                shippingFull = "Your Ordered Item is Downloadable Item." + "</td></tr><tr><td  height=\"32\" style=\"border-bottom:thin dashed #d1d1d1; padding:10px 0 5px 10px; font:normal 12px Arial, Helvetica, sans-serif\">";
                            }

                            messageTemplate = messageTemplate.Replace(token, shippingFull);
                            break;

                        case "%UserFirstName%":
                            messageTemplate = messageTemplate.Replace(token, infos[0].ToString());
                            break;

                        case "%UserLastName%":
                            messageTemplate = messageTemplate.Replace(token, "");
                            break;

                        case "%TransactionID%":
                            messageTemplate = messageTemplate.Replace(token, transID);
                            break;

                        case "%PaymentMethodName%":
                            messageTemplate = messageTemplate.Replace(token, payments[0].ToString());
                            break;

                        case "%DateTimeDay%":
                            messageTemplate = messageTemplate.Replace(token, payments[1].ToString());
                            break;

                        case "%DateYear%":
                            messageTemplate = messageTemplate.Replace(token, DateTime.Now.Year.ToString());
                            break;

                        case "%CustomerID%":
                            messageTemplate = messageTemplate.Replace(token, infos[2].ToString());
                            break;

                        case "%PhoneNo%":
                            messageTemplate = messageTemplate.Replace(token, infos[4].ToString());
                            break;

                        case "%AccountLogin%":
                            string account = "";
                            if (infos[1].ToString().ToLower() == "anonymoususer" && int.Parse(infos[2].ToString()) == 0)
                            {           // future login process for annoymoususr
                                account = "Please Register and log in to your <span style=\"font-weight: bold; font-size: 11px;\">AspxCommerce</span>";

                                account += "<a  style=\"color: rgb(39, 142, 230);\" href=" + ids[6].Replace("Home", "User - Registration") + ">account</a>";
                            }
                            else
                            {
                                account = "Please log in to your <span style=\"font-weight: bold; font-size: 11px;\">AspxCommerce</span>";

                                account += "<a style=\"color: rgb(39, 142, 230);\" href=" + ids[6].Replace("Home", "Login") + ">account</a>";
                            }
                            messageTemplate = messageTemplate.Replace(token, account);
                            break;

                        case "%LogoSource%":
                            //    string src = " http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/Templates/" + templateName + "/images/aspxcommerce.png";
                            string src = " http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/" + logosrc;
                            messageTemplate = messageTemplate.Replace(token, src);
                            break;

                        case "%DateTime%":
                            messageTemplate = messageTemplate.Replace(token, DateTime.Now.ToString("dd MMMM yyyy "));
                            break;

                        case "%StoreName%":
                            messageTemplate = messageTemplate.Replace(token, storeName);
                            break;

                        case "%InquiryEmail%":
                            string x =
                                "<a  target=\"_blank\" style=\"text-decoration: none;color: #226ab7;font-style: italic;\" href=\"mailto:" +
                                inquiry + "\" >" + inquiry + "</a>";
                            messageTemplate = messageTemplate.Replace(token, x);
                            break;
                        }
                    }
                    // return messageTemplate;
                    MailHelper.SendMailNoAttachment(template.MailFrom, infos[7].ToString(), template.Subject, messageTemplate, string.Empty, string.Empty);
                }
            }
        }