Example #1
0
    /// <summary>
    /// Loads data of specific e-mail from DB.
    /// </summary>
    protected void LoadData()
    {
        if (mEmailId <= 0)
        {
            return;
        }

        // Get specific e-mail
        EmailInfo ei = EmailInfoProvider.GetEmailInfo(mEmailId);

        if (ei == null)
        {
            plcDetails.Visible = false;
            ShowInformation(GetString("emailqueue.details.emailalreadysent"));
            return;
        }

        EditedObject = ei;

        lblFromValue.Text         = HTMLHelper.HTMLEncode(ei.EmailFrom);
        lblToValue.Text           = !ei.EmailIsMass ? HTMLHelper.HTMLEncode(ei.EmailTo) : GetString("emailqueue.detail.multiplerecipients");
        lblCcValue.Text           = HTMLHelper.HTMLEncode(ei.EmailCc);
        lblBccValue.Text          = HTMLHelper.HTMLEncode(ei.EmailBcc);
        lblReplyToValue.Text      = HTMLHelper.HTMLEncode(ei.EmailReplyTo);
        lblSubjectValue.Text      = HTMLHelper.HTMLEncode(ei.EmailSubject);
        lblErrorMessageValue.Text = HTMLHelper.HTMLEncodeLineBreaks(ei.EmailLastSendResult);

        if (UserIsAdmin)
        {
            LoadHTMLBody(ei);
            LoadPlainTextBody(ei);
            GetAttachments();
        }
    }
Example #2
0
        private void MakeEmail(EmailInfo EInfo, List <string> ListFileName, List <string> ListAddress, SqlHelper help, List <string> ListSupervisor)
        {
            if (Common.Common.MailPassword != "")
            {
                EInfo.User     = Common.Common.MailAddress;
                EInfo.PassWord = Common.Common.MailPassword;
                EmailRecordInfo ERecord;
                sentnum = ListFileName.Count;
                for (int i = 0; i < ListFileName.Count; i++)
                {
                    EInfo.AddFiles = ListFileName[i];
                    EInfo.Content  = "";
                    EInfo.Receiver = ListAddress[i];
                    EInfo.Title    = DateTime.Now + "听课安排";
                    string successflag = "";
                    ERecord = new EmailRecordInfo(ListSupervisor[i], "督导", EInfo.Title, ListSupervisor[i] + DateTime.Now.ToLongTimeString() + i, "听课安排", successflag, ListFileName[i]);

                    AsynEmail EmailSendPoccess = new AsynEmail(EInfo, ERecord, this.EmailResultCallBack);
                    EmailSendPoccess.ThreadSend();
                    //MessageBox.Show(successflag);
                    //help.Insert(ERecord,"Logs_Data");
                    Main.fm.SetStatusText("正在发送邮件", 0);
                }
            }
            else
            {
                MessageBox.Show("发件人邮箱不能为空,请设置发件人邮箱!");
            }
        }
Example #3
0
        public ActionResult ReceiveEmail()
        {
            var emailAddress = Request.Form["txtEmailAddress"];
            var model        = new DataViewerModel();

            if (string.IsNullOrEmpty(emailAddress))
            {
                model.Status = false;
                model.Data   = T("Địa chỉ email không để trống.");
                return(Json(model));
            }

            var service = WorkContext.Resolve <IEmailsService>();
            var status  = service.CheckEmailExist(emailAddress);

            if (!status)
            {
                var email = new EmailInfo
                {
                    Email     = emailAddress,
                    FullName  = string.Empty,
                    IsBlocked = false,
                    Notes     = "Yêu cầu nhận gửi thông tin qua email."
                };
                service.Save(email);
            }

            model.Status = true;
            model.Data   = T("Đã lưu lại địa chỉ email của bạn thành công.");

            return(Json(model));
        }
Example #4
0
        protected void SendEmail(string subject, string body, List <MailAddress> to, List <MailAddress> cc = null)
        {
            EmailInfo emailInfo = new EmailInfo();

            emailInfo.To      = to;
            emailInfo.CC      = cc;
            emailInfo.Subject = subject;
            emailInfo.Body    = body;

            //set smtp info
            //emailInfo.SMTPInfo.From;

            Helpers.EmailHelper emailHelper = new Helpers.EmailHelper();
            Action action = (async() =>
            {
                try
                {
                    //IQueryable<AspNetUser> AspNetUsers = dbContext.AspNetUsers.Where(x => to.Any(y => y.Email == x.Email));
                    await emailHelper.SendEmail(emailInfo);
                }
                catch (Exception ex)
                {
                    this.HandleError(null, LookUps.ErrorType.Exception, ex);
                }
            });

            this.AddAfterExecutionAction(action);
        }
Example #5
0
        void sendDelete_Click(object sender, EventArgs e)
        {
            TreeView tree = tvSendMail;

            if (tree == null || tree.SelectedNode == null)
            {
                LogHelper.Info("請選擇需要删除的郵件");
                return;
            }
            EmailInfo email = tree.SelectedNode.Tag as EmailInfo;

            if (email == null || string.IsNullOrEmpty(email.EmailID))
            {
                LogHelper.Info("操作的郵件信息為空。");
                return;
            }
            string emailID = email.EmailID;

            #region 临时处理没做事务
            if (MessageBox.Show("是否對郵件進行刪除操作?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                if (EmailInfoBLL.Current.Delete(emailID))
                {
                    EmailSendAccountBLL.Current.DeleteByEmailID(emailID);
                    EmailSendBccAccountBLL.Current.DeleteByEmailID(emailID);
                    Init("  EmailIsDel=1 order by EmailCreateTime desc");
                }
            }
            #endregion
        }
Example #6
0
        public Guid InsertImplicitSyncEmailUpload(EmailInfo emailinfo)
        {
            Guid requestguid = Guid.NewGuid();

            Logger.Current.Verbose("Request received for logging the mail response");
            var sentMail = new SentMailDb
            {
                TokenGuid       = Guid.NewGuid(),
                RequestGuid     = requestguid,
                From            = emailinfo.FromEmail,
                PriorityID      = 0,
                ScheduledTime   = emailinfo.SentDate,
                QueueTime       = DateTime.Now.ToUniversalTime(),
                StatusID        = Responses.CommunicationStatus.Success,
                ServiceResponse = ""
            };
            var sentMailDetail = new SentMailDetailDb
            {
                RequestGuid                                        = requestguid,
                To                                                 = emailinfo.To != null?string.Join(",", emailinfo.To) : "",
                                            CC                     = emailinfo.CC != null?string.Join(",", emailinfo.CC) : "",
                                                               BCC = emailinfo.BCC != null?string.Join(",", emailinfo.BCC) : "",
                                                                         Subject    = emailinfo.Subject,
                                                                         Body       = emailinfo.Body,
                                                                         IsBodyHtml = true
            };

            unitOfWork.SentMailsRepository.Add(sentMail);
            unitOfWork.SentMailDetailsRepository.Add(sentMailDetail);
            unitOfWork.Commit();
            Logger.Current.Verbose("Logging mail response was successful");
            return(requestguid);
        }
        public ActionResult RegisterUser(string userName, string userEmail, string password)
        {
            var checkUser = userDataDapper.FindUser(userName);

            if (checkUser != null)
            {
                return(Json(new { success = false, error = "用户已存在!" }));
            }
            try
            {
                string    token = Tools.GetMD5(encryptionTools.Crypt(userName + userEmail));
                EmailInfo email = new EmailInfo();
                email.Body = $"Hi,{userName}. <br>欢迎您注册地图搜租房(woyaozufang.live),你的账号已经注册成功." +
                             "<br/>为了保证您能正常体验网站服务,请点击下面的链接完成邮箱验证以激活账号."
                             + $"<br><a href='https://woyaozufang.live/Account/Activated?activatedCode={token}'>https://woyaozufang.live/Account/Activate?activatedCode={token}</a> "
                             + "<br>如果您以上链接无法点击,您可以将以上链接复制并粘贴到浏览器地址栏打开."
                             + "<br>此信由系统自动发出,系统不接收回信,因此请勿直接回复。" +
                             "<br>如果有其他问题咨询请发邮件到[email protected].";
                email.Receiver     = userEmail;
                email.Subject      = "地图找租房-激活账号";
                email.ReceiverName = userName;
                emailService.Send(email);
                var user = new UserInfo();
                user.UserName      = userName;
                user.Password      = password;
                user.Email         = userEmail;
                user.ActivatedCode = token;
                userDataDapper.InsertUser(user);
                return(Json(new { success = true, message = "注册成功!" }));
            }
            catch (Exception ex)
            {
                return(Json(new { success = false, error = ex.ToString() }));
            }
        }
        public ActionResult AcceptInvitation(int id)
        {
            var applicant   = GetCurrentApplicant();
            var application = _context.Applications.Find(id);

            if (application == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            EmailInfo info  = new EmailInfo(applicant.User.Email);
            int       index = application.SharedRequests.IndexOf(info);

            if (index < 0)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }
            application.SharedRequests.RemoveAt(index);
            application.Applicants.Add(applicant);
            applicant.Applications.Add(application);

            // Try to remove notification if it exists
            var foundShareNotification =
                applicant.Notifications.FirstOrDefault(x => x is ShareApplicationNotification && ((ShareApplicationNotification)x).ApplicationId == id);

            if (foundShareNotification != null)
            {
                applicant.Notifications.Remove(foundShareNotification);
            }
            _context.SaveChanges();
            return(RedirectToAction("Details", "Applications", new { id = id }));
        }
Example #9
0
 private void Clear()
 {
     AddressLabel.Content    = "Адрес почты: ";
     LiveTimeLabel.Content   = "";
     LettersGrid.ItemsSource = null;
     _emailInfo = null;
 }
        public IActionResult SendHtmlEmail(
            [FromQuery] string username,
            [FromQuery] string password,
            [FromBody] EmailInfo emailInfo)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                this._emailService.SendHtmlAsync(emailInfo, new EmailCredentials()
                {
                    Username = username,
                    Password = password
                });
            }
            catch (Exception ex)
            {
                return(this.StatusCode(503, ex.Message));
            }

            return(Ok(new { Message = "Successfully sent HTML email!" }));
        }
        public void Run()
        {
            var       today = DateTime.Now.ToLocalTime();
            EmailInfo email = new EmailInfo();

            email.Receiver     = configuration.ReceiverAddress;
            email.ReceiverName = configuration.ReceiverName;
            email.Subject      = $"地图搜租房每日数据汇总({today.ToString("yyyy-MM-dd")})";
            var    statList = houseDapper.GetHouseStatList();
            string bodyHTML = @"<table border='1' cellpadding='0' cellspacing='0' width='100%'> 
             <tr> 
             <td>来源</td>
             <td>数量</td>
             <td>最晚发布时间</td>
             <td>最晚入库时间</td> 
             </tr>";

            foreach (var stat in statList)
            {
                bodyHTML = bodyHTML + $" <tr> <td>{stat.Source}</td><td>{stat.HouseSum}</td><td>{stat.LastPubTime}</td> <td>{stat.LastCreateTime}</td> </tr>";
            }
            bodyHTML   = bodyHTML + $" <tr> <td>共计</td><td>{statList.Sum(s => s.HouseSum)}</td> </tr>";
            bodyHTML   = bodyHTML + " </table>";
            email.Body = bodyHTML;
            emailService.Send(email);
        }
Example #12
0
        public void SendEmail_WhenRecipientOverrideDisabled_ShouldSendEmailWithoutManipulatingTheReceiversOrChangingTheEmailContent()
        {
            using (var testScope = SiteTestScope.BlankSite())
            {
                // Arrange
                var web            = testScope.SiteCollection.RootWeb;
                var webApplication = testScope.SiteCollection.WebApplication;

                var emailInformation = new EmailInfo();
                emailInformation.To.Add("*****@*****.**");
                emailInformation.To.Add("*****@*****.**");
                emailInformation.CarbonCopy.Add("*****@*****.**");
                emailInformation.BlindCarbonCopy.Add("*****@*****.**");
                emailInformation.Subject = "Quoi faire à Barcelone?";
                emailInformation.Body    = "J'ai un ami qui me propose un hike! :)";

                // Expected values
                string           expectedBody    = emailInformation.Body;
                StringDictionary expectedHeaders = new StringDictionary();
                expectedHeaders.Add("to", string.Join(",", emailInformation.To));
                expectedHeaders.Add("cc", string.Join(",", emailInformation.CarbonCopy));
                expectedHeaders.Add("bcc", string.Join(",", emailInformation.BlindCarbonCopy));
                expectedHeaders.Add("subject", emailInformation.Subject);

                // Actual values
                StringDictionary actualHeaders = null;
                string           actualBody    = null;
                bool?            actualIsRecipientOverrideEnabled = null;

                using (ShimsContext.Create())
                {
                    // Mock the SendEmail method so no emails are actualy sent.
                    ShimSPUtility.SendEmailSPWebStringDictionaryString = (pWeb, pHeaders, pBody) =>
                    {
                        actualHeaders = pHeaders;
                        actualBody    = pBody;
                        return(true);
                    };

                    using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope())
                    {
                        var emailHelper = injectionScope.Resolve <IEmailHelper>();

                        // Act
                        actualIsRecipientOverrideEnabled = emailHelper.IsRecipientOverrideEnabled(webApplication);
                        emailHelper.SendEmail(web, emailInformation);

                        // Assert
                        Assert.IsTrue(actualIsRecipientOverrideEnabled.HasValue && !actualIsRecipientOverrideEnabled.Value, "Recipient override should not have been enabled.");
                        Assert.IsTrue(actualHeaders.Count == expectedHeaders.Count, "The headers should not have changed.");
                        Assert.IsTrue(actualBody == expectedBody, "The email body should not have changed.");

                        foreach (string key in actualHeaders.Keys)
                        {
                            Assert.IsTrue(actualHeaders[key] == expectedHeaders[key], "Header with key '{0}' should not have changed.", key);
                        }
                    }
                }
            }
        }
Example #13
0
 protected void btnPlaceOffer_Click(object sender, EventArgs e)
 {
     try
     {
         ShoppingCartManager cart   = new ShoppingCartManager();
         FacadeManager       facade = new FacadeManager();
         if (Session["orderid"] != null)
         {
             cart.OrderID = Session["orderid"].ToString();
             facade.ConfirmOrder(cart, "B");
             HCustomers hUser = (HCustomers)Session["userrole"];
             if (hUser != null)
             {
                 string orderid  = Session["orderid"] != null ? Session["orderid"].ToString() : "Order ID Could not retrieve";
                 string heyEmail = ConfigurationManager.AppSettings["hey-admin-mail"];
                 string msg      = "Product purchase order submitted.<br /> Order ID : " + orderid + "<br/> Total Amount: " + lblTotal.Text +
                                   "<br/><br/> With kind regards,<br/>" + hUser.Email;;
                 EmailInfo eInfo = new EmailInfo();
                 eInfo.Email = hUser.Email;
                 bool success = new FacadeManager().OrderConfirmationMailToAdmin(eInfo, heyEmail, msg);
             }
             ManageSession();
             Response.Redirect("Home.aspx");
         }
     }
     catch (Exception ex)
     {
     }
 }
Example #14
0
 protected void btnNaarProd_Click(object sender, EventArgs e)
 {
     try
     {
         ShoppingCartManager cart   = new ShoppingCartManager();
         FacadeManager       facade = new FacadeManager();
         if (Session["orderid"] != null)
         {
             cart.OrderID = Session["orderid"].ToString();
             HCustomers hUser = (HCustomers)Session["userrole"];
             if (ViewState[userType] != null && hUser != null)
             {
                 facade.ConfirmOrder(cart, "P");
                 // insert toedm and basematerial
                 int       IsEDM          = 0;
                 int       IsBaseMaterial = 0;
                 DataTable ItemTable      = new DataTable();
                 ItemTable = new FacadeManager().GetAllItemForOrder(int.Parse(cart.OrderID));
                 if (ItemTable.Rows.Count > 0)
                 {
                     foreach (DataRow row in ItemTable.Rows)
                     {
                         IsEDM = Convert.ToInt32(row["to_edm"].ToString());
                         if (IsEDM == 1)
                         {
                             // insert EDM
                             int res = InsertEDMData(hUser);
                         }
                         IsBaseMaterial = Convert.ToInt32(row["to_products"].ToString());
                         if (IsBaseMaterial == 1)
                         {
                             // insert into BaseMaterial
                             int res = InsertBaseMaterialData(hUser);
                         }
                     }
                 }
                 if (chkConfirmation.Checked) // if confirmation checkbox selected then send Order Finalize mail to customer.
                 {
                     string    orderid  = Session["orderid"] != null ? Session["orderid"].ToString() : "Order ID Could not retrieve";
                     string    heyEmail = ConfigurationManager.AppSettings["hey-admin-mail"];
                     EmailInfo eInfo    = new EmailInfo();
                     eInfo.Email = hUser.Email;
                     string msg = "Product purchase order finalized.<br /> Order ID : " + orderid +
                                  "<br/> Total Amount: " + lblTotal.Text +
                                  "<br/> Product Discount: " + lblProductDiscout.Text +
                                  "<br/> Other Discount: " + lblOtherDiscount.Text +
                                  "<br/> Shipping Cost: " + lblShippingCost.Text +
                                  "<br/> Total Amount (Including vat): " + lblTotalIncludingVat.Text +
                                  "<br/><br/> With kind regards,<br/><a href='new.hey-ermelo.nl'>HEY</a>";
                     bool success = new FacadeManager().OrderFinalizeMailToCustomer(eInfo, heyEmail, msg);
                 }
                 ManageSession();
                 Response.Redirect("Home.aspx");
             }
         }
     }
     catch (Exception ex)
     {
     }
 }
Example #15
0
 protected void lnkForgetPassword_Click(object sender, EventArgs e)
 {
     try
     {
         if (!String.IsNullOrEmpty(txtUserName.Text))
         {
             EmailInfo eInfo = new EmailInfo();
             eInfo.Email    = txtUserName.Text.Trim();
             lblMsg.Visible = false;
             bool success = new FacadeManager().SendPasswordRecoveryMail(eInfo);
             if (success)
             {
                 lblMsg.Visible = true;
                 lblMsg.Text    = "Uw wachtwoord is verstuurd naar het opgegeven e-mailadres.";
             }
             else
             {
                 lblMsg.Visible = true;
                 lblMsg.Text    = "Het opgegeven e-mailadres is onbekend in ons systeem.";
             }
         }
         else
         {
             lblMsg.Visible = true;
             lblMsg.Text    = "Het opgegeven e-mailadres is onbekend in ons systeem.";
         }
     }
     catch (Exception ex)
     { }
 }
Example #16
0
        void GetAddBccSQL(EmailInfo info)
        {
            StringBuilder sbSql = new StringBuilder();
            int           count = 0;

            foreach (var bcc in _BccMailList)
            {
                try
                {
                    count++;

                    sbSql.AppendFormat("insert into EmailSendBccAccount(EmailSendBccAccountID,EmailID,EmailBccAccountID,EmailAccountID,EmailSendBccAccountState,EmailSendBccAccountCreateTime,EmailSendBccAccountLastTime) values ('{0}','{1}','{2}','{3}',{4},'{5}','{6}');", Guid.NewGuid().ToString(), info.EmailID, bcc.EmailBccAccountID, "", (short)SendBccAccountState.Unsent, DateTime.Now, DateTime.Now);
                    if (count >= 5000)
                    {
                        EmailSendBccAccountBLL.Current.ExecSql(sbSql.ToString());
                        sbSql = new StringBuilder();
                        count = 0;
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error("新建郵件", "生成批量語句出錯", ex.Message, ex);
                    continue;
                }
            }
            if (sbSql.Length > 0 && !string.IsNullOrEmpty(sbSql.ToString()))
            {
                EmailSendBccAccountBLL.Current.ExecSql(sbSql.ToString());
            }
        }
Example #17
0
        void sendDeleteMore_Click(object sender, EventArgs e)
        {
            TreeView tree = tvSendMail;

            if (tree == null)
            {
                return;
            }
            if (MessageBox.Show("是否對郵件進行刪除操作?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                foreach (TreeNode node in tree.Nodes)
                {
                    if (node.Checked)
                    {
                        EmailInfo ei = node.Tag as EmailInfo;
                        if (EmailInfoBLL.Current.Delete(ei.EmailID))
                        {
                            EmailSendAccountBLL.Current.DeleteByEmailID(ei.EmailID);
                            EmailSendBccAccountBLL.Current.DeleteByEmailID(ei.EmailID);
                        }
                    }
                }
                Init("  EmailIsDel=1 order by EmailCreateTime desc");
            }
        }
        public override void SaveMessage(EmailInfo message)
        {
            List <EmailAddress> recipientNames = new List <EmailAddress>();

            foreach (var toAddress in message.To)
            {
                recipientNames.Add(toAddress);
            }
            foreach (var ccAddress in message.Cc)
            {
                recipientNames.Add(ccAddress);
            }
            Message payrollMessage = new Message(message.ReceiveDate,
                                                 message.Subject, message.From,
                                                 recipientNames, message.BodyText);
            string pathStart = Path.Combine(LocalFolder, UIDFilePrefix + message.UID);
            string filePath  = pathStart + Message.ReadExtension;

            if (!File.Exists(filePath))
            {
                filePath = pathStart + Message.UnreadExtension;
                if (!File.Exists(filePath))
                {
                    payrollMessage.Save(filePath);
                }
            }
        }
Example #19
0
        static void Main(string[] args)
        {
            Html2Image html2Image = new Html2Image();

            Html2Image.Coordinates coor = new Html2Image.Coordinates {
                lat = 32.33344, lon = 34.324322
            };
            double[] arr = new double[6] {
                5.5, 3, 8, 2, 6.5, 3.8
            };
            string    addrress  = "Kabirim 28, Haiafa Israel";
            string    customer  = "Jamil";
            string    MapFile   = "file:///C:/Users/jamil-g/Desktop/map.jpg";
            string    report    = html2Image.CustomizeReport(coor, customer, addrress, arr, MapFile);
            EmailInfo EmailInfo = new EmailInfo();

            EmailInfo.Sender     = "*****@*****.**";
            EmailInfo.Recipients = "*****@*****.**";
            EmailInfo.Subject    = $"Dear.Earth Indcies report of location: {addrress} - " + coor.lat.ToString() + "," + coor.lon.ToString();
            EmailInfo.EmailMsg   = $"Dear {customer}, <br><br> Thank you for choosing Dear.Earth to Calculate your environmental Indcies. <br>" +
                                   $"Please find attached the requested information of location: {addrress} - Coordinates:[" + coor.lat.ToString() + "," + coor.lon.ToString() + "].<br><br>" +
                                   "Best Regards, <br> Dear.Earth Team";
            EmailInfo.Attachment = $@"C:\Users\jamil-g\source\repos\ShortReportGen\ShortReportGen\bin\Debug\netcoreapp2.1\{report}";
            StmpEmail email = new StmpEmail();

            email.SendEmail(EmailInfo);
        }
        public void Analyze_WebServiceThrows_SendEmail_Ver2()
        {
            FakeWebService stubService = new FakeWebService();

            stubService.ToThrow = new Exception("fake exception");

            FakeEmailServiceVer2             mockEmail = new FakeEmailServiceVer2();
            LogAnalyzerCh4withTwoServiceVer2 log       = new LogAnalyzerCh4withTwoServiceVer2(stubService, mockEmail);
            string tooShortFileName = "abc.ext";

            log.Analyze(tooShortFileName);

            EmailInfo expectedEmail = new EmailInfo()
            {
                Body    = "fake exception",
                To      = "*****@*****.**",
                Subject = "can't log"
            };

            //書本內容有點錯
            //因為是比位址,所以不能兩個class去比,除非兩個class一樣,
            //ex: var a = b = new class
            //範例是 EmailInfo vs FakeEmailServiceVer2.EmailInfo 所以比對會不過
            //也可以用 Assert.AreSame
            Assert.AreEqual(expectedEmail.Body, mockEmail.email.Body);
            Assert.AreEqual(expectedEmail.To, mockEmail.email.To);
            Assert.AreEqual(expectedEmail.Subject, mockEmail.email.Subject);
        }
Example #21
0
        /// <summary>
        /// 获取邮件
        /// </summary>
        /// <param name="emailInfo">邮件实体</param>
        /// <param name="pageInfo">分页实体</param>
        /// <returns></returns>
        public IList <EmailInfo> GetEmail(EmailInfo emailInfo, PageInfo pageInfo)
        {
            using (DataContextDB DB = new DataContextDB())
            {
                IQueryable <EmailInfo> emailInfos =
                    (
                        from item in DB.GetTable <EmailInfo>()
                        orderby item.ID descending
                        select item
                    );
                if (emailInfo != null && emailInfo.ID != 0)
                {
                    emailInfos = emailInfos.Where <EmailInfo>(m => m.ID == emailInfo.ID);
                }
                if (emailInfo != null && emailInfo.UserID != 0)
                {
                    emailInfos = emailInfos.Where <EmailInfo>(m => m.UserID == emailInfo.UserID);
                }

                if (pageInfo != null)
                {
                    pageInfo.TotalRecord = emailInfos.Count();
                    return(emailInfos.Skip(pageInfo.PageSize * (pageInfo.PageIndex - 1)).Take(pageInfo.PageSize).ToList <EmailInfo>());
                }
                else
                {
                    return(emailInfos.ToList <EmailInfo>());
                }
            }
        }
Example #22
0
        public void SendEmail(EmailInfo emailinfo)
        {
            // let's define the stmp parameters
            var smtpClient = new SmtpClient(c_StmpAddr)
            {
                Port = 587,
                UseDefaultCredentials = false,
                EnableSsl             = true,
                Credentials           = new NetworkCredential(c_StmpUser, c_StmpPassword),
            };

            // let's set the message info parameters
            var mailMessage = new MailMessage
            {
                From       = new MailAddress(emailinfo.Sender),
                Subject    = emailinfo.Subject,
                Body       = emailinfo.EmailMsg,
                IsBodyHtml = true,
            };

            mailMessage.To.Add(emailinfo.Recipients);

            // let's add the message attachment
            var attachment = new Attachment(emailinfo.Attachment, MediaTypeNames.Image.Jpeg);

            mailMessage.Attachments.Add(attachment);
            smtpClient.Send(mailMessage);
        }
Example #23
0
        public string ParseTemplate(int TemplateID, EmailInfo emailInfo, UserInfo MyUserInfo)
        {
            string ReturnValue  = "";
            string TemplateBody = "";
            string ParseValue   = "";

            try
            {
                //Get Template Body from TemplateID
                //TemplateBody = m_TemplateDbService.GetTemplateBodyByTemplateID(TemplateID, MyUserInfo);


                //Parse Here
                FormatCompiler compiler = new FormatCompiler();

                Generator generator = compiler.Compile(TemplateBody);

                string JSONString = string.Empty;
                JSONString = JsonConvert.SerializeObject(emailInfo);
                //var reportData = String.Format("{{ feeTypes: {0} }}", JSONString);
                var     reportData = JSONString;
                JObject jsonData   = JObject.Parse(reportData);
                ParseValue = generator.Render(jsonData);

                ReturnValue = ParseValue;

                return(ReturnValue);
            }

            catch (Exception exp)
            {
                throw;
            }
        }
Example #24
0
        private void CriarCaixa()
        {
            pictureBoxLoad.Visible = true;
            thread = new Thread(PreencherCaixaThread);
            form1.ExecutarThread(thread);
            this.Activate();

            if (Form1.EmpresaEmail != null)
            {
                if (enumCaixa == EnumCaixa.Caixa)
                {
                    EmailNegocio negocioEmail = new EmailNegocio(Form1.EmpresaEmail, Form1.Empresa.empfantasia);
                    EmailInfo    email        = new EmailInfo
                    {
                        emailAssunto = "Caixa Fechado - " + caixaAbrirInfo.caixaabrirdata.Date.ToShortDateString(),
                        emailMessage = ArrCupom[0],
                        emailTo      = Form1.EmpresaEmail.emailenviar,
                        emailCC      = new string[0],
                        emailCCo     = new string[0],
                        emailAnexo   = new string[0]
                    };

                    negocioEmail.EnviarEmailGmail(email);
                }
            }

            PreencherForm(ArrCupom[0]);
        }
Example #25
0
        public async Task <IActionResult> SendEmailForgotPassword(EmailForgotPassword model, string baseUrl)
        {
            try
            {
                var user = await db.Users.Where(u => u.Mail == model.Email).FirstOrDefaultAsync();

                if (user == null)
                {
                    return(new NotFoundResult());
                }
                if (!user.IsMailConfirmed)
                {
                    return(new OkObjectResult(new { msg = "Почта не подтверждена" }));
                }
                var emailInfo = new EmailInfo();
                emailInfo.Subject = "Заменя пароля в приложении MusicApp";
                emailInfo.Body    = $"<div><p>Кликните по ссылке ниже, чтобы заменить пароль</p><a href='{baseUrl}{forgotPasswordLink}/{user.UserId}/{user.VerifyCode}'>Заменить пароль</a></div>";
                emailInfo.ToMails.Add(model.Email);
                var emailResult = emailManager.Send(emailInfo);
                if (emailResult.Sended)
                {
                    return(new OkResult());
                }
                return(new StatusCodeResult(500));
            }
            catch
            {
                return(new StatusCodeResult(500));
            }
        }
Example #26
0
        public async Task <ApiResponse <string> > SendEmail([FromBody] EmailInfo emailInfo)
        {
            var response = new ApiResponse <string>();
            var msg      = new MailMessage();

            try
            {
                msg.From = new MailAddress("*****@*****.**");
                msg.To.Add(emailInfo.AddressTo);
                msg.Subject = emailInfo.Subject;
                msg.Body    = emailInfo.Body;

                using (var client = new SmtpClient())
                {
                    client.Host = "smtp.gmail.com"; //"smtp.gmail.com";  // get it from options / 587
                    client.Port = 587;              //get it from options
                    client.UseDefaultCredentials = false;
                    client.Credentials           = new NetworkCredential("*****@*****.**", "santony106");

                    client.EnableSsl = true;
                    await client.SendMailAsync(msg);
                }
            }
            catch (Exception e)
            {
                response.Status.SetError(-1, "error in Post", e);
            }
            return(response);
        }
 public ActionResult SendRetrievePasswordEmail(string emailAccount)
 {
     try
     {
         var       user  = userDataDapper.FindUser(emailAccount);
         var       token = Tools.GetMD5(encryptionTools.Crypt(user.UserName + user.Email + DateTime.Now.ToString()));
         EmailInfo email = new EmailInfo();
         email.Body = $"Hi,{user.UserName}. <br>您正在通过注册邮箱找回密码,如果非本人操作,请勿继续."
                      + "<br>请在24小时内点击以下链接重置密码:"
                      + $"<br><a href='https://woyaozufang.live/Account/ModifyPassword?token={token}'>https://woyaozufang.live/Account/ModifyPassword?token={token}</a> "
                      + "<br>如果您以上链接无法点击,您可以将以上链接复制并粘贴到浏览器地址栏打开."
                      + "<br>此信由系统自动发出,系统不接收回信,因此请勿直接回复。" +
                      "<br>如果有其他问题咨询请发邮件到[email protected].";
         email.Receiver     = user.Email;
         email.Subject      = "地图找租房-找回密码";
         email.ReceiverName = user.UserName;
         emailService.Send(email);
         userDataDapper.SaveRetrievePasswordToken(user.ID, token);
         return(Json(new { success = true }));
     }
     catch (Exception ex)
     {
         return(Json(new { success = false, error = ex.ToString() }));
     }
 }
Example #28
0
    /// <summary>
    /// Gets the HTML body of the e-mail message.
    /// </summary>
    /// <param name="ei">The e-mail message object</param>
    /// <returns>HTML body</returns>
    private string GetHTMLBody(EmailInfo ei)
    {
        string body = ei.EmailBody;

        // Regular expression to search the tracking image in HTML code
        Regex regExp     = RegexHelper.GetRegex("(src=\"[^\"]+Track.ashx)\\?[^\"]*", RegexOptions.IgnoreCase);
        Match matchTrack = regExp.Match(body);

        if (matchTrack.Success && (matchTrack.Groups.Count > 0))
        {
            // Remove parameters from tracking image URL so the statistics are not influenced by e-mail previews
            body = regExp.Replace(body, matchTrack.Groups[1].Value);
        }

        // Transform inline attachments back to metafile attachments
        regExp = RegexHelper.GetRegex("src=\"cid:(?<cidCode>[a-z0-9]{32})\"", RegexOptions.IgnoreCase);
        body   = regExp.Replace(body, match => TransformSrc(match));

        htmlTemplateBody.Visible            = true;
        htmlTemplateBody.ResolvedValue      = body;
        htmlTemplateBody.AutoDetectLanguage = false;
        htmlTemplateBody.DefaultLanguage    = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

        return(body);
    }
        public static bool SendPasswordRecoveryMail(EmailInfo eInfo)
        {
            bool             success   = false;
            DataTable        dt        = new DataTable();
            IDatabaseFactory dbFactory = new DatabaseFactory();
            IDatabase        dbObject  = dbFactory.CreateDatabaseInstance(ACTIVE_DATABASE);

            Npgsql.NpgsqlCommand command = new Npgsql.NpgsqlCommand(SQLClass.GET_FORGETUSERPASSWORD);
            command.Parameters.Add("email", eInfo.Email.ToLower());
            dt = dbObject.GetDataTable(command);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    eInfo.Email       = dr["email"].ToString();
                    eInfo.Password    = dr["webshop_pwd"].ToString();
                    eInfo.CompanyName = dr["companytype"].ToString();
                }
                string adminMail = Hey.Common.Utils.Functions.GetValueFromWebConfig("hey-admin-mail");
                try
                {
                    success = SendPasswordRecoveryMailToUser(eInfo, adminMail);
                }
                catch (Exception ex)
                {
                    throw new Exception("The email is unknown to the server.");
                }
            }
            else
            {
                success = false;
            }

            return(success);
        }
Example #30
0
    /// <summary>
    /// Prepare the HTML body of the e-mail message for display.
    /// </summary>
    /// <param name="ei">The e-mail message object</param>
    private void LoadHTMLBody(EmailInfo ei)
    {
        string body = ei.EmailBody;

        if (string.IsNullOrEmpty(body))
        {
            lblBodyValue.Visible = true;
            lblBodyValue.Text    = GetString("emailqueue.detail.valuenotentered");
            return;
        }

        // Regular expression to search the tracking image in HTML code
        Regex regExp     = RegexHelper.GetRegex("(src=\"[^\"]+Track.ashx)\\?[^\"]*", true);
        Match matchTrack = regExp.Match(body);

        if (matchTrack.Success && (matchTrack.Groups.Count > 0))
        {
            // Remove parameters from tracking image URL so the statistics are not influenced by e-mail previews
            body = regExp.Replace(body, matchTrack.Groups[1].Value);
        }

        // Transform inline attachments back to metafile attachments
        regExp = RegexHelper.GetRegex("src=\"cid:(?<cidCode>[a-z0-9]{32})\"", true);
        body   = regExp.Replace(body, TransformSrc);

        htmlTemplateBody.Visible            = true;
        htmlTemplateBody.ResolvedValue      = body;
        htmlTemplateBody.AutoDetectLanguage = false;
        htmlTemplateBody.DefaultLanguage    = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
    }
Example #31
0
        private EmailInfo GetEmailInfo(String body, String emailTo)
        {
            EmailInfo info = new EmailInfo();

            Match match = SubjectPattern.Match(body);
            if (match.Success)
            {
                info.Subject = match.Groups[1].Value;
                if (info.Subject != null)
                    info.Subject = info.Subject.Trim();

                body = SubjectPattern.Replace(body, "");
            }

            info.Body = body.Trim();
            info.To = emailTo;
            info.From = GooeyConfigManager.EmailAddresses.SiteAdmin;

            return info;
        }
Example #32
0
        /// <summary>
        ///     发送电子邮件
        /// </summary>
        /// <param name="mail">Email配置</param>
        /// <param name="lstAddress">收件人地址</param>
        /// <param name="subject">邮件的标题</param>
        /// <param name="body">邮件的正文</param>
        /// <param name="fileName">邮件附件路径名</param>
        public static bool Send(List<string> lstAddress, string subject, string body, EmailInfo mail = null,
                                string fileName = "")
        {
            if (mail == null)
            {
                mail = 0;
            }
            if (lstAddress.Count > mail.RecipientMaxNum)
            {
                new Terminator().Throw("收件人地址数量不能超过" + mail.RecipientMaxNum);
                return false;
            }

            var ObjSmtpClient = new SmtpClient(mail.SmtpServer, mail.SmtpPort)
                                    {
                                        DeliveryMethod =
                                            SmtpDeliveryMethod.Network,
                                        Credentials =
                                            new NetworkCredential(
                                            mail.LoginName, mail.LoginPwd)
                                    };

            var ObjMailMessage = new MailMessage {From = new MailAddress(mail.SendMail, mail.SendUserName)};
            foreach (var item in lstAddress)
            {
                ObjMailMessage.To.Add(new MailAddress(item));
            }

            ObjMailMessage.Subject = subject; //发送邮件主题
            ObjMailMessage.Body = body; //发送邮件内容
            ObjMailMessage.BodyEncoding = Encoding.Default; //发送邮件正文编码
            ObjMailMessage.IsBodyHtml = true; //设置为HTML格式
            ObjMailMessage.Priority = MailPriority.High; //优先级
            if (!fileName.IsNullOrEmpty()) ObjMailMessage.Attachments.Add(new Attachment(fileName)); //邮件的附件

            ObjSmtpClient.Send(ObjMailMessage);
            return true;
        }
Example #33
0
 /// <summary>
 ///     发送电子邮件
 /// </summary>
 /// <param name="mail">Email配置</param>
 /// <param name="lstAddress">收件人地址</param>
 /// <param name="subject">邮件的标题</param>
 /// <param name="body">邮件的正文</param>
 /// <param name="fileName">邮件附件路径名</param>
 public static bool Send(List<string> lstAddress, string subject, string body, EmailInfo mail = null, string fileName = "")
 {
     if (mail == null) { mail = 0; }
     return new Utils.SmtpMail(mail.LoginName, mail.LoginPwd, mail.SendMail, mail.SendUserName, mail.SmtpServer, mail.RecipientMaxNum, mail.SmtpPort).Send(lstAddress, subject, body, fileName);
 }
Example #34
0
        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtMail.Text) || (txtMail.Text.Contains("@") == false))
            {
                MessageBox.Show("Invalid E-Mail address. \r\nYour E-Mail is very important. \r\nWe will contact you as soon as possible when we have solution.");
                txtMail.Focus();
            }
            else if (string.IsNullOrWhiteSpace(txtMailContent.Text))
            {
                MessageBox.Show("Message connot be empty.");
                txtMailContent.Focus();
            }
            else
            {
                IsSending = true;
                EmailInfo info = new EmailInfo();
                info.From = rcSupport.UserProxyEmail;
                info.To = rcSupport.SupportEmail;
                info.Subject = txtSubject.Text;
                info.Body = string.Format("From User: {0}", txtMail.Text) + Environment.NewLine + txtMailContent.Text;
                info.ProxyName = rcSupport.UserProxyEmail;
                info.ProxyPwd = Decrypt(rcSupport.UserID);
                FSendingEmailThread = new Thread(new ParameterizedThreadStart(SendEmail));
                FSendingEmailThread.Start(info);
            }

        }
Example #35
0
        static async Task<EmailInfo> CheckEmailAddresses(
            string email,
            string mxHostAddress,
            int port,
            ProgressBar pbar
        )
        {
            pbar.Tick($"Currently processing: #{pbar.CurrentTick} emails searched...");

            var mailInfo = new EmailInfo
            {
                Email = email,
                ProviderExists = false,
                EmailResolution = EmailResolutionType.CantDetemine
            };

            try
            {
                if (!string.IsNullOrEmpty(mxHostAddress) && !string.IsNullOrEmpty(email))
                {
                    using (var telnetClient = new Client(
                        mxHostAddress,
                        port,
                        CancellationToken.None
                    ))
                    {
                        if (mailInfo.ProviderExists = telnetClient.IsConnected)
                        {
                            mailInfo.Email = email;
                            await telnetClient.Write("HELO localhost\r\n");
                            await telnetClient.ReadAsync(new TimeSpan(0, 0, 10));

                            await telnetClient.Write("MAIL FROM:<*****@*****.**>\r\n");
                            await telnetClient.ReadAsync(new TimeSpan(0, 0, 10));

                            await telnetClient.Write(
                                string.Format("RCPT TO:<{0}>\r\n", email)
                            );

                            var response = await telnetClient.ReadAsync(new TimeSpan(0, 1, 0));

                            if (response.StartsWith("2"))
                                mailInfo.EmailResolution = EmailResolutionType.Exist;
                            else if (response.StartsWith("5") && response.Contains("exist"))
                                mailInfo.EmailResolution = EmailResolutionType.NotExist;
                            else
                                mailInfo.EmailResolution = EmailResolutionType.CantDetemine;
                        }

                        await telnetClient.Write("QUIT");
                    }
                }
            }
            catch (Exception ex)
            {
                _log.Error(string.Empty, ex);
            }

            return mailInfo;
        }
Example #36
0
 private void SendEmail(EmailInfo info)
 {
     EmailClient client = EmailClient.GetDefaultClient();
     client.FromAddress = info.From;
     client.ToAddress = info.To;
     client.Send(info.Subject, info.Body);
 }
    /// <summary>
    /// Gets the HTML body of the e-mail message.
    /// </summary>
    /// <param name="ei">The e-mail message object</param>
    /// <returns>HTML body</returns>
    private string GetHTMLBody(EmailInfo ei)
    {
        string body = ei.EmailBody;

        // Regular expression to search the tracking image in HTML code
        Regex regExp = RegexHelper.GetRegex("(src=\"[^\"]+Track.ashx)\\?[^\"]*", RegexOptions.IgnoreCase);
        Match match = regExp.Match(body);
        if (match.Success && (match.Groups.Count > 0))
        {
            // Remove parameters from tracking image URL so the statistics are not influenced by e-mail previews
            body = regExp.Replace(body, match.Groups[1].Value);
        }

        htmlTemplateBody.Visible = true;
        htmlTemplateBody.ResolvedValue = body;
        htmlTemplateBody.AutoDetectLanguage = false;
        htmlTemplateBody.DefaultLanguage = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

        return body;
    }
    /// <summary>
    /// Gets the HTML body of the e-mail message.
    /// </summary>
    /// <param name="ei">The e-mail message object</param>
    /// <returns>HTML body</returns>
    private string GetHTMLBody(EmailInfo ei)
    {
        string body = ei.EmailBody;

        // Regular expression to search the tracking image in HTML code
        Regex regExp = RegexHelper.GetRegex("(src=\"[^\"]+Track.ashx)\\?[^\"]*", true);
        Match matchTrack = regExp.Match(body);
        if (matchTrack.Success && (matchTrack.Groups.Count > 0))
        {
            // Remove parameters from tracking image URL so the statistics are not influenced by e-mail previews
            body = regExp.Replace(body, matchTrack.Groups[1].Value);
        }

        // Transform inline attachments back to metafile attachments
        regExp = RegexHelper.GetRegex("src=\"cid:(?<cidCode>[a-z0-9]{32})\"", true);
        body = regExp.Replace(body, match => TransformSrc(match));

        htmlTemplateBody.Visible = true;
        htmlTemplateBody.ResolvedValue = body;
        htmlTemplateBody.AutoDetectLanguage = false;
        htmlTemplateBody.DefaultLanguage = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

        return body;
    }
    /// <summary>
    /// Gets the plain text body of the e-mail message.
    /// </summary>
    /// <param name="ei">The e-mail message object</param>
    /// <returns>Plain-text body</returns>
    private string GetPlainTextBody(EmailInfo ei)
    {
        DiscussionMacroResolver dmh = new DiscussionMacroResolver { ResolveToPlainText = true };
        string body = dmh.ResolveMacros(ei.EmailPlainTextBody);

        body = HTMLHelper.HTMLEncode(body);

        lblBodyValue.Visible = true;

        // Replace line breaks with br tags and modify discussion macros
        lblBodyValue.Text = DiscussionMacroResolver.RemoveTags(HTMLHelper.HTMLEncodeLineBreaks(body));

        return body;
    }