protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Exception objError = Server.GetLastError(); objError = objError.GetBaseException(); ErrorMessage = objError.Message; // these are errors most likely caused by robots. We don't want to be alerted when they occur. if (objError.Message.Contains("A potentially dangerous Request.Path value was detected from the client")) return; if (objError.Message.Contains("Invalid viewstate")) return; if (objError.Message.Contains("Invalid length for a Base-64 char array.")) return; if (objError.Message.Contains("The input is not a valid Base-64 string")) return; if (objError.Message.Contains("The file") && objError.Message.Contains("does not exist")) { Response.RedirectPermanent("http://pinnacle3learning.com", true); return; } Response.StatusCode = 404; SendMail objSendEmail = new SendMail(); objSendEmail.IsHTML = true; objSendEmail.Subject = "Error on pinnacle3learning.com"; string body = "<b>Message</b><br>" + objError.Message + "<br><br>"; body += "<b>Inner Exception</b><br>" + objError.InnerException + "<br><br>"; body += "<b>Stack Trace</b><br>" + objError.StackTrace + "<br><br>"; body += "<b>TimeStamp</b><br>" + DateTime.Now.ToString() + "<br><br>"; objSendEmail.Body = body; SendMail.Send(objSendEmail, true); } }
protected void btnLogin_OnClick(object sender, EventArgs e) { string loginUrl = Request.Url.AbsoluteUri.Replace("forgetPassword.aspx", "login.aspx"); string sql = "select * from users where username=@username"; Database db=new Database(); db.AddParameter("@username", txtUserName.Text); DataTable dt = db.ExecuteDataTable(sql); if(dt.Rows.Count==0) { ErrorDiv.Visible = true; lblError.Text = "هذا البريد الالكتروني غير مسجل لدينا الرجاء مراجعة مدير النظام"; return; } StringBuilder strBuild=new StringBuilder(); strBuild.Append("<h1>المركز الوطني للبحوث و الدراسات الاجتماعية</h1>"); strBuild.Append("<h2>استرجاع كلمة السر الخاص بنظام الارشفة</h2>"); strBuild.Append("<h4>معلومات الدخول الخاص بك الى النظام</h4>"); strBuild.Append(String.Format("<p>اسم المستخدم : <b>{0}</b></p>",dt.Rows[0]["username"].ToString())); strBuild.Append(String.Format("<p>كلمة السر : <b>{0}</b></p>",dt.Rows[0]["password"])); strBuild.Append(String.Format("<p>لتسجيل الدخول <a href=\"{0}\">من هنا</a></p>", loginUrl)); SendMail mail=new SendMail(); mail.SendMsg(dt.Rows[0]["username"].ToString(), "استعادة كلمة المرور", strBuild.ToString()); ClientScript.RegisterClientScriptBlock(this.GetType(),"msgBox","alert('تم ارسال كلمة السر على بريدك الالكتروني');",true); }
public void SendEmail() { Email email = new Email() { To = "*****@*****.**", Subject = "Unit Test", DeliveryType ="Email", Message = "Test" }; SendMail sendMail = new SendMail(); Assert.IsTrue(sendMail.SendEmail(email)); }
protected void btnForgetPass_Click(object sender, EventArgs e) { AppFunctions v = new AppFunctions(); if (!v.IsEmailValid(txtEmail.Text)) { ErrorDiv.Visible = true; sp1.Visible = true; lblError.Text = "<i class=\"fa fa-exclamation-triangle fcRed\"></i> الرجاء التأكد من البريد الالكتروني."; return; } Database db = new Database(); db.AddParameter("@email", txtEmail.Text); System.Data.DataTable dt = db.ExecuteDataTable("Select * from AdminUsers where email=@email"); if (dt.Rows.Count == 0) { ErrorDiv.Visible = true; sp1.Visible = true; lblError.Text = "<i class=\"fa fa-exclamation-triangle fcRed\"></i> هذا البريد الالكتروني غير مسجل في النظام"; return; } string body = "<h2>"; body += "هذة معلومات الدخول الى لوحة التحكم الخاصة بموقع الدليل الاإلكتروني لإرشفة القرارات و التعاميم الحكومية<br/>"; body += "اسم المستخدم : " + dt.Rows[0]["username"].ToString() + "<br/>"; body += "البريد الالكتروني : " + dt.Rows[0]["email"].ToString() + "<br/>"; body += "كلمة السر : " + dt.Rows[0]["password"].ToString() + "<br/>"; body += "</h2>"; SendMail mail = new SendMail(); mail.SendMsg(txtEmail.Text, "الدليل الاإلكتروني لإرشفة القرارات و التعاميم الحكومية", body); ScriptManager.RegisterClientScriptBlock(this,GetType(), "writeMsg", "alert('تم ارسال كلمة السر الي البريد الالكتروني " + txtEmail.Text + " ');", true); }
protected void Submit_Click(object sender, EventArgs e) { if (findUs.SelectedValue != "0") { var objSendEmail = new SendMail(); objSendEmail.IsHTML = true; objSendEmail.Subject = "An Inquiry From Your Website for Private Group Training"; objSendEmail.Body = "<br>Name: " + fname.Text + " " + lname.Text; objSendEmail.Body += "<br>Email: " + email.Text; objSendEmail.Body += "<br>Heard From: " + findUs.SelectedItem.Text + " " + sourceOther.Text; objSendEmail.Body += "<br>Source IP Address: " + Request.UserHostAddress; objSendEmail.Body += "<br>Company: " + company.Text; objSendEmail.Body += "<br>Daytime Phone: " + dayPhone.Text; objSendEmail.Body += "<br>Approx Attendee Count: " + ddlAttendeeCount.SelectedValue; objSendEmail.Body += "<br>Preferred Course: " + ddlCourse.SelectedValue; objSendEmail.Body += "<br>Preferred Location: " + ddlLocation.SelectedValue; objSendEmail.Body += "<br>Comments: " + comments.Text; SendMail.Send(objSendEmail); if (ConfigurationManager.AppSettings["SendLeadsToSalesForce"] == "true") _postFormToSalesForce(); Response.Redirect("private-group-sent.aspx"); } else { Label2.Visible = true; } }
protected void Submit_Click(object sender, EventArgs e) { if (findUs.SelectedValue != "0") { if (!validateForm()) return; SendMail objSendEmail = new SendMail(); //send notification in email objSendEmail.IsHTML = true; objSendEmail.Subject = "An Inquiry From Your Website"; objSendEmail.Body = "<br>Name: " + fname.Text + " " + lname.Text; objSendEmail.Body += "<br>Email: " + email.Text; objSendEmail.Body += "<br>Heard From: " + findUs.SelectedItem.Text + " " + sourceOther.Text; objSendEmail.Body += "<br>Source IP Address: " + Request.UserHostAddress.ToString(); objSendEmail.Body += "<br>Company: " + company.Text; objSendEmail.Body += "<br>Daytime Phone: " + dayPhone.Text; objSendEmail.Body += "<br>Comments: " + comments.Text; SendMail.Send(objSendEmail); if (ConfigurationManager.AppSettings["SendLeadsToSalesForce"] == "true") _postFormToSalesForce(); Response.Redirect("contact-sent.aspx"); } else { Label2.Visible = true; } }
protected void btnRetrieve_Click(object sender, EventArgs e) { fname = txtFName.Text; lname = txtLName.Text; user = txtUser.Text; try { string connection = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString; SqlConnection conn = new SqlConnection(connection); SqlCommand cmd = new SqlCommand("Select EmpEmail, EmpPass FROM Employee WHERE EmpFName = @EmpFName AND EmpLName = @EmpLName AND EmpUser = @EmpUser;", conn); cmd.Parameters.AddWithValue("@EmpFName", fname); cmd.Parameters.AddWithValue("@EmpLName", lname); cmd.Parameters.AddWithValue("@EmpUser", user); conn.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { email = dt.Rows[0][0].ToString(); pass = dt.Rows[0][1].ToString(); SendMail sm = new SendMail(); success = sm.Retrieve_Password(email, pass); if (success) { lblSucc.Text = "Your password has been sent."; lblSucc.Visible = true; txtFName.Text = ""; txtLName.Text = ""; txtUser.Text = ""; } else { lblSucc.Text = "There was a problem sending the email. Please try again later or contact the administration."; lblSucc.ForeColor = System.Drawing.Color.Red; lblSucc.Visible = true; } } else { lblSucc.Text = "There are no records matching that information. Please try again."; lblSucc.ForeColor = System.Drawing.Color.Red; lblSucc.Visible = true; } conn.Close(); } catch (SqlException se) { lblSucc.Text = "There was a problem connecting to the server. Please try again later."; lblSucc.ForeColor = System.Drawing.Color.Red; lblSucc.Visible = true; } }
protected void btnCreateWO_Click(object sender, EventArgs e) { DateTime today = DateTime.Now; try { string connection = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString; SqlConnection conn = new SqlConnection(connection); SqlCommand cmd = new SqlCommand("INSERT INTO WorkOrder (CustomerID, WCaseNumber, WFName, WLName, WOPFName, WOPLName, WServAdd, WServApt, WServCity, WServState, WServZip, WStatus, WDateCreated, WEmpBPay) VALUES (@CustomerID, @WCaseNumber, @WFName, @WLName, @WOPFname, @WOPLName, @WServAdd, @WServApt, @WServCity, @WServState, @WServZip, @WStatus, @WDateCreated, @WEmpBPay);", conn); cmd.Parameters.AddWithValue("@CustomerID", id); cmd.Parameters.AddWithValue("@WCaseNumber", txtCaseNumber.Text); cmd.Parameters.AddWithValue("@WFName", txtFNameServiceRequestedBy.Text); cmd.Parameters.AddWithValue("@WLName", txtLNameServiceRequestedBy.Text); cmd.Parameters.AddWithValue("@WOPFName", txtOppFName.Text); cmd.Parameters.AddWithValue("@WOPLName", txtOppLName.Text); cmd.Parameters.AddWithValue("@WServAdd", txtServiceStreetAddress.Text); cmd.Parameters.AddWithValue("@WServApt", txtApartment.Text); cmd.Parameters.AddWithValue("@WServCity", txtCity.Text); cmd.Parameters.AddWithValue("@WServState", ddState.SelectedValue); cmd.Parameters.AddWithValue("@WServZip", txtZip.Text); cmd.Parameters.AddWithValue("@WStatus", "A"); cmd.Parameters.AddWithValue("@WDateCreated", today); cmd.Parameters.AddWithValue("@WEmpBPay", "0"); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); // Email the admin about the new work order SendMail sm = new SendMail(); if(sm.Send_AdminMail(id.ToString())) { //Show a success label lblCreateWOError.Text = "Your work order was created successfully. Please navigate to the Upload document page to upload the needed court documents."; lblCreateWOError.ForeColor = System.Drawing.Color.Green; lblCreateWOError.Visible = true; btnGoToUpload.Visible = true; ClearInputs(Page.Controls); } else { lblCreateWOError.Text = "Your work order was created successfully but the system failed to properly notify the staff at WeServeU LLC."; lblCreateWOError.ForeColor = System.Drawing.Color.Green; lblCreateWOError.Visible = true; } } catch(SqlException se) { lblCreateWOError.Text = "There was an error creating your work order" + se.ToString(); lblCreateWOError.ForeColor = System.Drawing.Color.Red; lblCreateWOError.Visible = true; } }
protected void Button1_Click(object sender, EventArgs e) { string fname; string lname; string email; string message; fname = txtFName.Text; lname = txtLName.Text; email = txtEmail.Text; message = txtMessage.Text; SendMail sm = new SendMail(); sm.CustQuestion(email, fname, lname, message); lblAddSuccess.Visible = true; ClearInputs(Page.Controls); }
//protected void PostCartToGoogle(object sender, System.Web.UI.ImageClickEventArgs e) //{ // CheckoutShoppingCartRequest Req = GCheckoutButton1.CreateRequest(); // int qty = Convert.ToInt32(Session["studentNum"]); // int amountToCharge = Convert.ToInt32(Session["amountToCharge"]); // Req.AddItem("Project Management Class", Convert.ToString(Session["classLocation"]) + " at Date " + Convert.ToString(Session["classDate"]), amountToCharge / qty, qty); // Req.EditCartUrl = clsGeneral.UrlBase + "register.aspx"; // GCheckoutResponse Resp = Req.Send(); // if (Resp.IsGood) // { // ///send Email Notification // SendMail objSendEmail = new SendMail(); // ///send notification in email // objSendEmail.From = billTo_email.Text.Trim(); // objSendEmail.ToEmail = "*****@*****.**"; // objSendEmail.Subject = "Registration Done By " + billTo_firstName.Text.Trim() + " " + billTo_lastName.Text.Trim(); // objSendEmail.Body = string.Format(clsGeneral.EmailNotificationBody, DateTime.Now.ToString(), "NA", Convert.ToString(Session["classLocation"]), Convert.ToString(Session["classDate"]) // , amountToCharge, "Discover", billTo_firstName.Text.Trim(), billTo_lastName.Text.Trim(), "", billTo_street1.Text.Trim(), // billTo_city.Text.Trim(), billTo_state.Text.Trim(), billTo_postalCode.Text.Trim(), billTo_country.Text.Trim(), // billTo_phoneNumber.Text.Trim(), "", billTo_email.Text.Trim()); // SendMail.Send(objSendEmail); // Response.Redirect(Resp.RedirectUrl, true); // } // else // { // Response.Write("Resp.ResponseXml = " + Resp.ResponseXml + "<br>"); // Response.Write("Resp.RedirectUrl = " + Resp.RedirectUrl + "<br>"); // Response.Write("Resp.IsGood = " + Resp.IsGood + "<br>"); // Response.Write("Resp.ErrorMessage = " + Resp.ErrorMessage + "<br>"); // } //} protected void btnEnroll_Click(object sender, EventArgs e) { int qty = Convert.ToInt32(Session["studentNum"]); int amountToCharge = Convert.ToInt32(Session["amountToCharge"]); ///send Email Notification SendMail objSendEmail = new SendMail(); ///send notification in email objSendEmail.IsHTML = true; objSendEmail.ToEmail = "*****@*****.**"; objSendEmail.Subject = "Registration Done By " + billTo_firstName.Text.Trim() + " " + billTo_lastName.Text.Trim(); objSendEmail.Body = string.Format(clsGeneral.EmailNotificationBody, DateTime.Now.ToString(), "NA", Convert.ToString(Session["classLocation"]), Convert.ToString(Session["classDate"]) , amountToCharge, drpPaymentMethod.SelectedValue, billTo_firstName.Text.Trim(), billTo_lastName.Text.Trim(), "", billTo_street1.Text.Trim(), billTo_city.Text.Trim(), billTo_state.Text.Trim(), billTo_postalCode.Text.Trim(), billTo_country.Text.Trim(), billTo_phoneNumber.Text.Trim(), "", billTo_email.Text.Trim()); SendMail.Send(objSendEmail); Response.Redirect("Thanks.aspx", true); }
private void SendEMail(string email) { string str; IList <MailAddress> list = new List <MailAddress>(); MailState none = MailState.None; MailInfo mailInfo = new MailInfo(); mailInfo.MailBody = base.MessageBody; mailInfo.Subject = base.MessageTitle; mailInfo.IsBodyHtml = true; if (this.m_SendType == SendType.SendToContacter) { str = "收货人"; } else { str = "会员"; } if (!string.IsNullOrEmpty(email) && DataValidator.IsEmail(email)) { list.Add(new MailAddress(email)); mailInfo.MailToAddressList = list; none = SendMail.Send(mailInfo); if (none == MailState.Ok) { base.SuccessMsg.Append("<br>已经向" + str + "发送了一封Email,通知他"); base.SuccessMsg.Append(base.OperationMsg); base.SuccessMsg.Append("!"); } else { string mailStateInfo = SendMail.GetMailStateInfo(none); base.ErrorMsg.Append("<br>"); base.ErrorMsg.Append(mailStateInfo); base.ErrorMsg.Append(",向" + str + "发送邮件失败!"); } } else { base.ErrorMsg.Append("<br>邮件地址为空或无效邮件地址,向" + str + "发送邮件失败!"); } }
public bool mytestemail2() { string to = VendorEmailID; //To address string from = "*****@*****.**"; //From address MailMessage message = new MailMessage(from, to); string mailbody = ""; using (StreamReader reader = new StreamReader(Server.MapPath("~/emailPage/VenRegisOrPassGenerateLink.html"))) { mailbody = reader.ReadToEnd(); } mailbody = mailbody.Replace("{UserName}", VendorEmailID); mailbody = mailbody.Replace("{refno}", HttpUtility.UrlEncode(ObjEnc.EncryptData(Session["NewVendorid"].ToString()))); mailbody = mailbody.Replace("{mcurid}", Resturl(56)); SendMail s; s = new SendMail(); //mailbody = mailbody.Replace("{UserName}", ObjEnc.DecryptData(Session["User"].ToString())); //mailbody = mailbody.Replace("{refno}", HttpUtility.UrlEncode(ObjEnc.DecryptData(Session["User"].ToString()))); mailbody = mailbody.Replace("{mcurid}", Resturl(56)); message.Subject = "New Vendor : RAKSHA UDYOG MITRA PORTAL"; message.Body = mailbody; message.BodyEncoding = Encoding.UTF8; message.IsBodyHtml = true; SmtpClient client = new SmtpClient("smtp.gmail.com", 587); //Gmail smtp System.Net.NetworkCredential basicCredential1 = new System.Net.NetworkCredential("*****@*****.**", "#"); client.EnableSsl = true; client.UseDefaultCredentials = false; client.Credentials = basicCredential1; try { client.Send(message); MsgStatus = true; } catch (Exception ex) { throw ex; } return(MsgStatus); }
public ActionResult Unpublish(int NoteID, RejectNoteModel Rn) { if (Session["UserID"] == null) { return(RedirectToAction("Login", "Authentication", new { ReturnUrl = @"/Admin/AdminDashBoard" })); } if (!ModelState.IsValid) { TempData["Message"] = "Something went wrong"; return(RedirectToAction("AdminDashBoard", "Admin")); } int UserID = Convert.ToInt32(User.Identity.Name); if (AdminNoteRepository.UnpublishNote(NoteID, UserID, Rn.Remarks)) { TempData["Message"] = "Note Unpublished"; NoteModel Note = NotesRepository.GetNoteDetailsById(NoteID); UserProfileModel Seller = UserRepository.GetUserData(Note.SellerID); ViewBag.SellerName = Seller.User.FirstName + " " + Seller.User.LastName; ViewBag.NoteTitle = Note.Title; ViewBag.Remarks = Rn.Remarks; SendMail.SendEmail(new EmailModel() { EmailTo = new string[] { Seller.User.Email }, EmailSubject = "Sorry! We need to remove your notes from our portal", EmailBody = this.getHTMLViewAsString("~/Views/Email/NoteUnpublished.cshtml") }); return(RedirectToAction("AdminDashBoard", "Admin")); } else { TempData["Message"] = "Unpublication of Note failed"; return(RedirectToAction("AdminDashBoard", "Admin")); } }
public JsonResult SendNoteReply(string Note_NO, string ReplyContent, string LoginACCOUNT) { try { string receEmail; string conn = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString; using (SqlConnection sqlconnection = new SqlConnection(conn)) { sqlconnection.Open(); //取得客戶或顧問的email string sqlcommandstring = @" select (CASE NR.Source_Role when '0' THEN Cli.Cli_Email ELSE Con.Con_Email END)as email from NoteRecord NR left join CliInfoDetail Cli on NR.Source_ID=Cli.Cli_ID left join ConInfoDetail Con on NR.Source_ID=Con.Con_ID where Note_NO=@Note_NO"; SqlCommand sqlcommand = new SqlCommand(sqlcommandstring, sqlconnection); sqlcommand.Parameters.AddRange(new SqlParameter[] { new SqlParameter("@Note_NO", Note_NO.Trim()) }); receEmail = Convert.ToString(sqlcommand.ExecuteScalar()); //收件信箱 if (receEmail.Trim() == "") { return(Json(new { result = false, message = "請確認收件者信箱" }, "text/html")); } SendMail send = new SendMail(); if (!send.Send(receEmail, "照會回覆", ReplyContent)) { return(Json(new { result = false, message = "發送失敗" }, "text/html")); } } return(Json(new { result = true, message = "發送成功" }, "text/html")); } catch (Exception e) { log.writeLogToDB("", "NoteRecord/SendNoteReply", e.ToString()); return(Json(new { result = false, message = "系統發生錯誤" }, "text/html")); } }
public ActionResult IndexPost() { string code = Request["email"]; account a = new accountDAO().getaccbyEmail(code); if (a == null) { Session["fogot"] = "Email is not yet Register"; return(RedirectToAction("Index", "Fogot")); } else { SendMail SendMailDAO = new SendMail(); string subject = "Thông tin tài khoản"; string content = "Cảm ơn bạn đã đăng ký sử dụng dịch vụ ! Tài khoản của bạn là: " + a.username + "Mật khẩu:" + a.password; SendMailDAO.Send(a.email, subject, content); return(RedirectToAction("Index", "Login")); } }
public ActionResult IssueDone(IssueDetailsViewModel issueDetails) { Issue issue = db.Issues.Find(issueDetails.Id); if (issue == null) { return(HttpNotFound()); } issue.State = 1; db.SaveChanges(); var userMails = new List <string>(); var userId = User.Identity.GetUserId(); userMails.Add(db.Users.First(u => u.Id == userId).Email); var type = db.Types.First(t => t.Id == issue.TypeId); SendMail.InformUsers(userMails, issue, "", "", 3); TempData["Success"] = "Usterka została wykonana. Użytkownik został poinformowany!"; return(RedirectToAction("Index", "Home")); }
private void sendMailOTP2() { try { string body; using (StreamReader reader = new StreamReader(Server.MapPath("~/emailPage/OTP.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{OTP}", PMotp.Value); SendMail M; M = new SendMail(); M.CreateMail("*****@*****.**", VendorEmailID, "We have Migrating Profile With You Please follow Profile Migration", body); M.sendMail(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alert", "alert('" + ex.Message + "')", true); } }
private SendMailResponse SendPasswordResetNotificationEmail(string email, string userName, string newPassword) { SendMailResponse result = null; MailDetails datails = new MailDetails(); datails.MessageType = "PasswordResetNotification"; datails.ToAddress = email; datails.Parameters.Add("UserName", userName); datails.Parameters.Add("Password", newPassword); SendMail sendMailRequest = new SendMail(); sendMailRequest.SessionToken = ConfigurationManager.AppSettings["MailServiceSessionToken"]; sendMailRequest.Details.Add(datails); Client.Mail.ServiceClient client = new Client.Mail.ServiceClient(); result = client.PostSendMail(sendMailRequest); return(result); }
protected override void OnStop() { WriteErrorLog("eKnowId Order Status enquiry Service stopped"); this.Schedular.Dispose(); var sendWithAttachment = new Email() { To = Constant.DeveloperEmail, From = Constant.FromEmailAddress, Subject = Constant.DeveloperEmailSubject, DisplayName = Constant.DeveloperEmailDisplayName, Attachment = string.Format("{0}{1}", AppDomain.CurrentDomain.BaseDirectory, ("Logs\\LogFile_" + DateTime.Now.ToString("MMddyyyy") + ".log")), }; SendMail.SendWithAttachment(sendWithAttachment); //using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("StatusEnquiryService")) { // serviceController.Start(); //} }
public async Task <DataTable> ForgotPasswordData(FJC_ForgotPassword fJC_forgot) { Dictionary <string, object> dictForgotPwd = new Dictionary <string, object>(); dictForgotPwd.Add("@DPIIDCLID", fJC_forgot.UserID); dictForgotPwd.Add("@EMAILID", fJC_forgot.EmailID); DataSet ds = new DataSet(); ds = await AppDBCalls.GetDataSet("Evote_ForgotPassword", dictForgotPwd); //mailing contents are here if (ds.Tables[0].Columns.Contains("rowid")) { SendMail sendmail = new SendMail(); string EmailerType = "ForgotPasswordEmailer"; int row_id = Convert.ToInt32(ds.Tables[0].Rows[0]["rowid"]); sendmail.SendLetterMail(0, EmailerType, 0, row_id); } return(Reformatter.Validate_DataTable(ds.Tables[0])); }
//SMPT Async mail sending public async Task <ActionResult> sendFromMicrosoftAsync(SendMail model, MailMessage message) { using (var smtp = new SmtpClient()) { smtp.UseDefaultCredentials = false; var credential = new NetworkCredential { UserName = model.FromEmail, Password = model.Password }; smtp.Credentials = credential; smtp.Host = "smtp-mail.outlook.com"; smtp.Port = 587; smtp.EnableSsl = true; await smtp.SendMailAsync(message); return(RedirectToAction("Sent")); } }
protected void btnCadastro_Click(object sender, EventArgs e) { MensagemMoradorBLL oMensagemMorador = new MensagemMoradorBLL(); try { oMensagemMorador.cadastraContato(drpListSubject.SelectedItem.Text, txtDescription.Text, Convert.ToInt32(Session["Bloco"]), Convert.ToInt32(Session["AP"])); lblMsg.Visible = true; lblMsg.Text = "Obrigado por entrar em contato! <br> <br> <font size='1' color='#948c8c'>Em breve entraremos em contato com você via sistema para sanar sua dúvida e/ou agradecermos o seu comentário ou sugestões! </font> "; txtDescription.Text = ""; drpListSubject.SelectedIndex = -1; Util.SendMail oEmail = new SendMail(); oEmail.enviaSenha("Assunto:" + drpListSubject.SelectedItem.Text + "<br> Descrição: " + txtDescription.Text + "<br> Bloco: " + Session["Bloco"].ToString() + " <br> Apto: " + Session["AP"].ToString(), "Fale Conosco Azuli", "*****@*****.**", 0); } catch (Exception er) { throw er; } }
public IActionResult ReceberContato([FromForm] Contato contato) { if (ModelState.IsValid) { //string conteudo = string.Format("Nome: {0}, E-mail: {1}, Assunto: {2}, Mensagem: {3}", //contato.Nome, contato.Email, contato.Assunto, contato.Mensagem); //return new ContentResult() { Content = conteudo }; ViewBag.Contato = new Contato(); SendMail.EnviarMensagem(contato); ViewBag.Mensagem = "Mensagem enviada com sucesso!"; return(View("Index")); } else { ViewBag.Contato = contato; return(View("Index")); } }
protected void submit_Click(object sender, EventArgs e) { try { SendMail email = new SendMail(); email.SendEMail(nameTextBox.Text, emailTextBox.Text, ctcNoTextBox.Text, "Application for TIN Registration", messageTextBox.Text, confirmationLabel.Text, "", ""); confirmationLabel.Text = "Thanks for contacting us. We will get back to you in 24Hrs.<br />" + " You will be redirected to home page."; confirmationLabel.Visible = true; ctcNoTextBox.Text = ""; emailTextBox.Text = ""; nameTextBox.Text = ""; messageTextBox.Text = ""; Response.AddHeader("REFRESH", "6;URL=../default.aspx"); } catch (Exception) { } }
private void sendMailOTP(string email) { try { string body; using (StreamReader reader = new StreamReader(Server.MapPath("~/emailPage/OTP.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{OTP}", hfotp.Value); SendMail s; s = new SendMail(); s.CreateMail("*****@*****.**", email.ToString(), "OTP Verification HelpDesk.", body); s.sendMail(); } catch (Exception ex) { ex.Message.ToString(); } }
public void SendAdminMail(string mailTlp, DataTable dt) { DataRow dr = dt.Rows[0]; M_UserInfo mu = buser.GetUserByName(dr["UserName"].ToString()); if (string.IsNullOrEmpty(mu.Email)) { function.WriteErrMsg("这个账号未绑定邮件!"); } MailAddress adMod = new MailAddress(mu.Email); MailInfo mailInfo = new MailInfo() { ToAddress = adMod, IsBodyHtml = true }; mailInfo.FromName = SiteConfig.SiteInfo.SiteName; mailInfo.Subject = "恭喜您已获得" + SiteConfig.SiteInfo.SiteName + "申请测试帐号资格"; mailInfo.MailBody = new OrderCommon().TlpDeal(mailTlp, dt); SendMail.Send(mailInfo); }
public async Task <IActionResult> Register([FromBody] aa0001 user) { string checkUser = _context.aa0001 .Where(a => a.aa0001c13 == user.aa0001c13) .Select(a => a.aa0001c13).FirstOrDefault(); if (!string.IsNullOrEmpty(checkUser)) { return(BadRequest(string.Format("This mail {0} is aready exist!", checkUser))); } MD5 algorithm = MD5.Create(); string salt = EncryptData.RandomSalt(12); aa0001 outUser = new aa0001 { aa0001c07 = user.aa0001c13, aa0001c08 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), aa0001c11 = user.aa0001c11, aa0001c12 = user.aa0001c12, aa0001c13 = user.aa0001c13, aa0001c14 = user.aa0001c14, aa0001c15 = "0", aa0001c16 = user.aa0001c16, aa0001c20 = salt, aa0001c21 = EncryptData.StringToHash(user.aa0001c21, salt, algorithm), aa0001c23 = "Not active", aa0001c26 = EncryptData.StringToHash(user.aa0001c13, salt, algorithm), }; _context.aa0001.Add(outUser); await _context.SaveChangesAsync(); MailInfo mailInfo = new MailInfo { mailTo = outUser.aa0001c13, mailSubject = string.Format("Active Account From {0}", baseUrl), mailMessage = string.Format("{0}/Account/ActiveUser/?email={1}", baseUrl, outUser.aa0001c13) }; SendMail.SendMailAuto(mailInfo); return(Ok("Your are registed! Please check mail and active your account!")); }
protected void btnSend_Click(object sender, EventArgs e) { bool boolIsValidPast = true; boolIsValidPast = txtSenderName.Text.IsNotEmpty() && txtMessage.Text.IsNotEmpty() && txtEmail.Text.IsNotEmpty() && AdvantShop.Helpers.ValidationHelper.IsValidEmail(txtEmail.Text); if (!boolIsValidPast) { ShowMessage(Notify.NotifyType.Error, Resource.Client_Feedback_WrongData); validShield.TryNew(); return; } if (SettingsMain.EnableCaptcha && !validShield.IsValid()) { ShowMessage(Notify.NotifyType.Error, Resource.Client_Feedback_WrongCaptcha); validShield.TryNew(); return; } try { var mailTemplate = new FeedbackMailTemplate(SettingsMain.SiteUrl, SettingsMain.ShopName, HttpUtility.HtmlEncode(txtSenderName.Text), HttpUtility.HtmlEncode(txtEmail.Text), HttpUtility.HtmlEncode(txtPhone.Text), Resource.Client_Feedback_Header, HttpUtility.HtmlEncode(txtMessage.Text)); mailTemplate.BuildMail(); SendMail.SendMailNow(SettingsMail.EmailForFeedback, mailTemplate.Subject, mailTemplate.Body, true); MultiView1.SetActiveView(ViewEmailSend); } catch (Exception ex) { Debug.LogError(ex); } }
public static async Task ProcessEmailQueue( [QueueTrigger(EMAIL_QUEUE)] OutgoingEmail emailQueue, [Table(EMAIL_TRACK)] CloudTable tbEmailTrack, [Table(EMAIL_BLOCKED)] CloudTable tbEmailBlocked, int dequeueCount, ILogger log) { log.LogInformation($"New email to send. Dequeue count for this message: {dequeueCount}."); try { var toEmail = emailQueue.ToAddress.Email; //Check whether the recipient of the message is blocked //TODO: Change this method to check if the email is blocked calling a SendGrid Api var recipientIsBlocked = await EmailBlocker.CheckIfBlocked(toEmail, tbEmailBlocked); if (recipientIsBlocked) { log.LogInformation($"Can't send email to {toEmail} because it has been blocked"); await EmailTracker.Update(tbEmailTrack, toEmail, emailQueue.TrackerId, Event.Blocked, log); return; } var response = await SendMail.SendSingleEmail(emailQueue.FromAddress, emailQueue.ToAddress, emailQueue.Subject, emailQueue.Body, emailQueue.TrackerId, log); if (!SuccessStatusCodes.Contains(response.StatusCode)) { throw new Exception($"Error sending mail. SendGrid response {response.StatusCode}"); } //Track that email request was sent await EmailTracker.Update(tbEmailTrack, toEmail, emailQueue.TrackerId, Event.SendRequested, log, response.MessageId); } catch (Exception ex) { log.LogError("An error has occurred: {0}", ex); throw; } }
private void PaymentDoneMessage(decimal r, decimal r1, decimal t) { try { string Date_time = DateTime.Now.ToString(); string datenew = Date_time.ToString(); string emailadd = Session["emailid"].ToString(); string body = emailadd + " Has Paid Successfully."; string totalprice = (r + r1 + t).ToString(); string CC_Name1 = Session["CC_Name"].ToString(); string CC_Name2 = Session["CC_Name1"].ToString(); string CC_Name = CC_Name1 + " " + CC_Name2; string orderno = (string)Session["OrderNumber"]; string UserAppID = Session["GroomerAppointmentId"].ToString(); string Mailbody = ContentManager.GetStaticeContentEmail("PrePaymentEmail.htm").Replace("~", "#"); Mailbody = Mailbody.Replace("<!-- Date -->", Date_time); Mailbody = Mailbody.Replace("<!-- UserAppId -->", UserAppID); Mailbody = Mailbody.Replace("<!-- Total_Amount -->", totalprice); Mailbody = Mailbody.Replace("<!-- CC_Name -->", CC_Name); Mailbody = Mailbody.Replace("<!-- orderNumber -->", orderno); Mailbody = Mailbody.Replace("<!-- Rev_Amount -->", r.ToString()); Mailbody = Mailbody.Replace("<!-- Prior_Amount -->", r1.ToString()); Mailbody = Mailbody.Replace("<!-- Tip_Amount -->", t.ToString()); Mailbody = Mailbody.Replace("<!-- Details -->", body); SendMail ObjMail = new SendMail(); MailMessage objMailMsg = new MailMessage(ConfigurationManager.AppSettings["FromEmail"], ConfigurationManager.AppSettings["ToEmail"]); objMailMsg.BodyEncoding = Encoding.UTF8; objMailMsg.Subject = "Groomer Panel:Payment Details For Fritzys Pet Care Pros Mobile Grooming Services"; objMailMsg.Body = Mailbody; objMailMsg.Priority = MailPriority.High; objMailMsg.IsBodyHtml = true; SmtpClient objSMTPClient = new SmtpClient(ConfigurationManager.AppSettings["SmtpServer"].ToString(), 587); objSMTPClient.Host = ConfigurationManager.AppSettings["SmtpServer"]; objSMTPClient.EnableSsl = true; objSMTPClient.Send(objMailMsg); } catch (Exception ex) { string error = ex.Message; } }
public IHttpActionResult ForgotPassword(UsersModel model) { try { if (model.UserName != null && model.UserName != "") { var getCurrentUser = entities.tblUsers.Where(x => x.UserName == model.UserName || x.Email == model.UserName).FirstOrDefault(); if (getCurrentUser != null) { SendMail mail = new SendMail(); string body = mail.createEmailBody("ForgotPassword.html"); body = body.Replace("{UserName}", getCurrentUser.UserName); body = body.Replace("{Password}", getCurrentUser.Password); mail.SendGeneralMail("Forgot Password", getCurrentUser.Email, body); } else { responseData.success = false; responseData.code = 500; responseData.message = "User name or Email does not exist!"; return(Ok(responseData)); } } //list.BookingID = entities.Bookings.Where(x => x.PatientID == list.RefID).Select(x => x.BookingID).FirstOrDefault(); responseData.success = true; responseData.code = 200; responseData.message = "Login Credential sent to your mail successfully."; return(Ok(responseData)); } catch (Exception ex) { responseData.message = ex.Message != null?ex.Message.ToString() : "server error"; return(Ok(responseData)); } }
public JsonResult ContactUs(string UserName, string Title, string Content) { int InResult = 0; try { crm_EmailQueues crm_emailqueues = new crm_EmailQueues(); string EmailFrom = ConfigurationManager.AppSettings["EmailFrom"]; string EmailContact = ConfigurationManager.AppSettings["EmailContact"]; string EmailPassword = ConfigurationManager.AppSettings["EmailPassword"]; string Host = ConfigurationManager.AppSettings["Host"]; string Port = ConfigurationManager.AppSettings["Port"]; string EmailCc = ConfigurationManager.AppSettings["EmailCc"]; string EmailBcc = ConfigurationManager.AppSettings["EmailBcc"]; string EmailSubject = ConfigurationManager.AppSettings["EmailSubjectContact"]; bool EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); string ip = System.Web.HttpContext.Current.Request.UserHostAddress; bool Active = SendMail.SendMailWithCCAndBcc(EmailFrom, EmailPassword, Host, Convert.ToInt32(Port), Title, Content, EnableSsl, EmailContact, EmailCc, EmailBcc); if (ModelState.IsValid) { crm_emailqueues.EmailFrom = EmailFrom; crm_emailqueues.Active = true; crm_emailqueues.CreatedDate = DateTime.Now; crm_emailqueues.UpdatedDate = DateTime.Now; crm_emailqueues.EmailTo = EmailContact; crm_emailqueues.EmailCc = EmailCc; crm_emailqueues.EmailBcc = EmailBcc; crm_emailqueues.EmailSubject = EmailSubject; crm_emailqueues.SenderIP = ip; crm_emailqueues.IsHtmlContent = true; crm_emailqueues.DisplayNameFrom = UserName; _emailqueuesService.Insert(crm_emailqueues); InResult = _unitOfWork.SaveChanges(); } } catch (Exception) { } return(Json(new { Result = InResult }, JsonRequestBehavior.AllowGet)); }
public IHttpActionResult ApproveUser(UsersModel model) { try { RegisterDL obj = new RegisterDL(); var RefType = ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault(c => c.Type.Equals(ClaimTypes.Name)).Value; obj.ApproveUser(model.UserID); responseData.success = true; responseData.code = 200; responseData.message = "User approve successfully"; var list = obj.GetUserDetails(model.UserID, Convert.ToInt32(RefType)); string subject; SendMail mail = new SendMail(); if (list[0].RefType == 2) // Patient { subject = "Patient Approval"; string body = mail.createEmailBody("PatientApproval.html"); body = body.Replace("{UserName}", list[0].FirstName + " " + list[0].LastName); mail.SendGeneralMail(subject, list[0].Email, body); } else { subject = "Therapist Approval"; string body = mail.createEmailBody("TherapistApproval.html"); body = body.Replace("{UserName}", list[0].FirstName + " " + list[0].LastName); mail.SendGeneralMail(subject, list[0].Email, body); } return(Ok(responseData)); } catch (Exception ex) { responseData.success = false; responseData.message = ex.Message != null?ex.Message.ToString() : "server error"; return(Ok(responseData)); } }
public ActionResult SendEmail(SendMail sendMail) { if (ModelState.IsValid) { try { var senderEmail = new MailAddress("*****@*****.**", "Shivaraj Mehre"); var receiverEmail = new MailAddress(sendMail.To, "Reciever"); var password = "******"; var sub = sendMail.Subject; var body1 = sendMail.To; var body = sendMail.Message; var smtp = new SmtpClient { Host = "smtp.gmail.com", Port = 587, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential(senderEmail.Address, password) }; using (var mess = new MailMessage(senderEmail, receiverEmail) { Subject = sub, Body = sendMail.Message }) { smtp.Send(mess); sendMail.DateTime = DateTime.Now; _emailRepository.Send(sendMail); _emailRepository.Save(); } } catch { return(View()); } } return(RedirectToAction("Index")); }
public async Task <IActionResult> savemailAsync([FromBody] SendMail model) { if (CheckUser() == "1") { return(StatusCode((int)HttpStatusCode.NotAcceptable, "Ban khong co quyen nay")); } if (ModelState.IsValid) { var result = await VerifyCaptcha(model.ReCaptcha); if (!result.Success) { return(StatusCode((int)HttpStatusCode.NotAcceptable, "Captcha is not valid")); } var messages = new MimeMessage(); messages.From.Add(new MailboxAddress("*****@*****.**")); messages.To.Add(new MailboxAddress(model.MailTo)); messages.Subject = model.Subject; var bodyBuilder = new BodyBuilder(); bodyBuilder.HtmlBody = string.Format(model.Messages); messages.Body = bodyBuilder.ToMessageBody(); using (var client = new SmtpClient()) { client.Connect("smtp.gmail.com", 587, false); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate("*****@*****.**", "daylaMATKHAUr4tkh0#"); client.Send(messages); client.Disconnect(true); } DbContext.Email.Add(new Emails { MailTo = model.MailTo, Subject = model.Subject, Messages = model.Messages, UserId = model.UserId }); DbContext.SaveChanges(); return(Ok("Done")); } return(StatusCode((int)HttpStatusCode.NotAcceptable, "Du lieu nhap khong hop le!")); }
public void SimulatesBusinessProcess() { // arrange var dispatcher = _container.GetService <IRequestDispatcher>(); var sendMail1 = new SendMail { Messages = new[] { new MailMessage { From = "Delayed 1", Priority = 1 }, new MailMessage { From = "Express 1", Priority = 3 }, new MailMessage { From = "Standard 1", Priority = 2 }, } }; var sendMail2 = new SendMail { Messages = new[] { new MailMessage { From = "Delayed 2", Priority = 1 }, new MailMessage { From = "Express 2", Priority = 3 }, new MailMessage { From = "Standard 2", Priority = 2 }, } }; // act dispatcher.DispatchCommand(sendMail1); dispatcher.DispatchCommand(sendMail2); // assert }
/// <summary> /// Request admittance to this forum /// </summary> public void RequestAdmittance() { if (CIX.Online) { Thread t = new Thread(() => { try { StringBuilder textTemplate = new StringBuilder(Resources.AdmissionRequestTemplate1); textTemplate.Replace("$username$", CIX.Username); textTemplate.Replace("$forum$", Name); StringBuilder htmlTemplate = new StringBuilder(Resources.AdmissionRequestTemplate); htmlTemplate.Replace("$username$", CIX.Username); htmlTemplate.Replace("$forum$", Name); SendMail sendMail = new SendMail { Text = textTemplate.ToString(), HTML = htmlTemplate.ToString() }; LogFile.WriteLine("Requesting admission to forum {0}", Name); string url = string.Format("moderator/{0}/sendmessage", Name); HttpWebRequest postUrl = APIRequest.Post(url, APIRequest.APIFormat.XML, sendMail); string responseString = APIRequest.ReadResponseString(postUrl); if (responseString == "Success") { LogFile.WriteLine("Successfully sent admittance request for forum {0}", Name); } } catch (Exception e) { CIX.ReportServerExceptions("DirForum.RequestAdmittance", e); } }); t.Start(); } }
protected void btnAssign_Click(object sender, EventArgs e) { lblWONum.Visible = false; string workOrderNum; string empNum; workOrderNum = ddlWOList.SelectedValue; empNum = ddlEmpList.SelectedValue; try { string connection = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString; SqlConnection conn = new SqlConnection(connection); SqlCommand cmd = new SqlCommand("UPDATE WorkOrder SET EmpID = @EmpID WHERE WorkOrderID = @WorkOrderID;", conn); cmd.Parameters.AddWithValue("@EmpID", empNum); cmd.Parameters.AddWithValue("@WorkOrderID", workOrderNum); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); //call the mail class to send the notification SendMail sm = new SendMail(); bool success = sm.Send_EmpEmail(workOrderNum); //Check to see if the email was actually sent or not if (success) { lblWONum.Text = ddlEmpList.SelectedItem.ToString() + " was assigned to work order #" + workOrderNum + " and they were notified by email."; lblWONum.Visible = true; } else { //If there was a problem display this message lblWONum.Text = "There was a problem sending the notification email. But the employee was assigned to the workorder. Please try again later"; lblWONum.ForeColor = System.Drawing.Color.Red; lblWONum.Visible = true; } } catch (SqlException ex) { lblWONum.Text = "The work order was not assigned due to an error"; lblWONum.ForeColor = System.Drawing.Color.Red; lblWONum.Visible = true; } }
public void SendEmailCodeRegis(string empid, string email) { try { string body; using (StreamReader reader = new StreamReader(Server.MapPath("~/emailPage/HelpDeskRegis.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{UserName}", email); body = body.Replace("{refno}", empid); SendMail s; s = new SendMail(); s.CreateMail("*****@*****.**", txtnodelemail.Text, "Registration Email", body); s.sendMail(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "alert", "alert('" + ex.Message + "')", true); } }
protected void submit_Click(object sender, EventArgs e) { try { //It Will call function SendEmail and confirms that message sent succesfully. SendMail email = new SendMail(); email.SendEMail(nameTextBox.Text, emailTextBox.Text, subjectTextBox.Text, "PAN Card Application", messageTextBox.Text, confirmationLabel.Text, "", ""); confirmationLabel.Text = "Thanks for contacting us. We will get back to you in 24Hrs.<br />" + " You will be redirected to home page."; confirmationLabel.Visible = true; subjectTextBox.Text = ""; emailTextBox.Text = ""; nameTextBox.Text = ""; messageTextBox.Text = ""; Response.AddHeader("REFRESH", "6;URL=../default.aspx"); } catch (Exception) { } }
public void SendMailBLockAccount(string mtimeblock) { try { string body; using (StreamReader reader = new StreamReader(Server.MapPath("~/emailPage/AccountBlock.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{UserName}", txtUserName.Text); body = body.Replace("{timeblock}", mtimeblock.ToString()); SendMail s; s = new SendMail(); s.CreateMail("*****@*****.**", txtUserName.Text, "Account Block", body); s.sendMail(); } catch (Exception ex) { ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "ErrorMssgPopup('" + ex.Message + "')", true); } }
protected void submit_Click(object sender, EventArgs e) { try { //It Will call function SendEmail and confirms that message sent succesfully. SendMail email = new SendMail(); email.SendEMail(nameTextBox.Text, emailTextBox.Text, subjectTextBox.Text, "PAN Card Correction", messageTextBox.Text, confirmationLabel.Text, "PAN Card No", pancardNoBox.Text); confirmationLabel.Text = "Thanks for contacting us. We will get back to you in 24Hrs.<br />" + " You will be redirected to home page."; confirmationLabel.Visible = true; subjectTextBox.Text = ""; emailTextBox.Text = ""; nameTextBox.Text = ""; messageTextBox.Text = ""; pancardNoBox.Text = ""; Response.AddHeader("REFRESH", "6;URL=../default.aspx"); } catch (Exception) { } }
public void MainLoop() { try { List<FtpFileModificationDate> lastModList = new List<FtpFileModificationDate>(); int iteration = 0; while (true) { if (iteration == 0) { DeleteOldSharepointRouterConfigTables.DeleteAll(); AddToSharepoint.AddToSharepointTables(); SendMail mail = new SendMail(); mail.SendEmail(); EventLogging.LogEvent( "Deletion and reprint of router config information has been performed. Iteration " + iteration, false); Console.WriteLine( "Deletion and reprint of router config information has been performed. Iteration " + iteration); } EventLogging.LogEvent("Iteration " + iteration + " complete", false); Console.WriteLine("beggining {0} iteration... " + DateTime.Now, iteration); FtpConnectFileGet dates = new FtpConnectFileGet(GlobVar.ServerUri); //w srodku jest Filename, ModificationDate i RouterName dla wszystkich routerów iteration++; if (lastModList.Count > 0) { if (lastModList.Count() != dates.Count) { DeleteOldSharepointRouterConfigTables.DeleteAll(); AddToSharepoint.AddToSharepointTables(); SendMail mail = new SendMail(); mail.SendEmail(); EventLogging.LogEvent( "Deletion and reprint of router config information has been performed. Iteration " + iteration, false); Console.WriteLine( "Deletion and reprint of router config information has been performed. Iteration " + iteration); } Thread.Sleep(300000); } else { lastModList = dates; } } } catch (ThreadAbortException) { return; } catch (Exception ex) { EventLogging.LogEvent(ex.ToString(), true); } }
public NotificationService(SendMail _sendMail) { sendMail = _sendMail; }
/// <summary> /// 邮件通知这些错误 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void btnEmail_Click(object sender, EventArgs e) { //获取邮件配置信息 FrameConfig FC = new FrameConfig(); string ServerEmail = FC.GetDetail("ServerMail").ConfigValue; //接收邮件地址 string HostEmail = FC.GetDetail("HostMail").ConfigValue; //发送方邮件配置信息 if (ServerEmail == "" || HostEmail == "") { ShowJsMessage("您没有配置邮件信息(ServerMail和HostMail),不能发送邮件!"); return; } bool HasMailed = false; string AttachFile = ""; string ReportGuid = ""; for (int i = 0; i < grdList.Items.Count; i++) { CheckBox chkSingle = (CheckBox)grdList.Items[i].FindControl("chkAdd"); if (chkSingle.Checked) { Label lb = (Label)grdList.Items[i].FindControl("lbTime"); DateTime dt = Convert.ToDateTime(lb.Text.Trim()); AttachFile += Server.MapPath("~/Error/" + dt.Year.ToString() + "/" + dt.Month.ToString() + "/" + dt.Day.ToString() + ".txt") + ";"; ReportGuid += Convert.ToString(grdList.DataKeys[i]) + ";"; HasMailed = true; } } if (!HasMailed) { ShowJsMessage("您没有选择要发送邮件的错误报告!"); } else { try { string MailTitle = FC.GetDetail("ErrorReportMailTitle").ConfigValue; string mailBody = FC.GetDetail("ErrorReportMailBody").ConfigValue.Replace(" ", " ").Replace("\r\n", "<br />"); SendMail SM = new SendMail(HostEmail, ServerEmail, MailTitle, mailBody, AttachFile); bool isok = SM.Send(); if (isok) ShowJsMessage("错误报告发送成功!"); else ShowJsMessage("错误报告发送异常,请检查!"); } catch (Exception a) { ShowJsMessage("错误信息:" + a.Message); return; } //设置已发送邮件标识,确保数据库邮件状态与实际邮件发送一致 string[] ReportGuidlist = ReportGuid.Split(';'); for (int i = 0; i < ReportGuidlist.Length; i++) { if (ReportGuidlist[i].Trim() != "") { new FrameErrorLog().UpdateEmailed(ReportGuidlist[i].Trim()); } } } this.BindGrid(); }
private void SendMailTo(object sender, EventArgs e) { if (openFromEmail) ContactAddedToRecipientList(contacts.Where(x => x.Name == lv_contactList.SelectedItems[0].SubItems[0].Text.ToString()).First().Email); else { string msgTo = contacts.Where(x => x.Name == lv_contactList.SelectedItems[0].SubItems[0].Text.ToString()).First().Email; SendMail smf = new SendMail(contacts, login.Username, login.Password, msgTo); smf.Show(); } }
private static void InsertError(Exception ex, SendMail sm) { StringBuilder sb = new StringBuilder(); if (ex != null) { sb.Append(ex.InnerException.Message); sb.Append("\n\n"); sb.Append(ex.InnerException.InnerException.Message); sb.Append("\n\n"); sb.Append(ex.InnerException.StackTrace); sb.Append("\n\n\n"); sb.Append(ex.ToString()); } SendMail smError = new SendMail(); smError.Email = sm.Email; smError.Subject = sm.Subject; smError.Error = sb.ToString(); smError.Content = sm.Content; try { BusinessLogic.SendMailManage.SendMailErrorInsert(smError); } catch { } }
[WebMethod]//string Email, string Header, string Content, string AddFileName public static bool SendMailAdd(SendMail sm) { if (!string.IsNullOrEmpty(sm.Email)) { //单个邮件发送 StartConfig(); System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage(); if (sm.Email.IndexOf(';') == -1) { myMail = new MailMessage("\"" + FromText + "\"<" + FromEmail + ">", sm.Email.Trim(), sm.Subject, sm.Content); if (!string.IsNullOrEmpty(sm.FileName)) myMail.Attachments.Add(new Attachment(sm.FileName)); myMail.IsBodyHtml = true;//设置为HTML格式 myMail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");//正文编码 myMail.SubjectEncoding = System.Text.Encoding.GetEncoding("GB2312");//标题编码 System.Net.Mail.SmtpClient mySMTP = new SmtpClient(); mySMTP.Host = SendHost; mySMTP.UseDefaultCredentials = true; mySMTP.Credentials = new System.Net.NetworkCredential(UserName, UserPass); mySMTP.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式 try { mySMTP.Send(myMail); if (!string.IsNullOrEmpty(sm.FileName)) DeleteFileName(sm.FileName); InsertError(null, sm); return true; } catch (Exception ex) { InsertError(ex, sm); } } else { //多个邮件发送 string[] strArr = sm.Email.Split(';'); for (int i = 0; i < strArr.Length; i++) { if (!string.IsNullOrEmpty(strArr[i].Trim())) { myMail = new MailMessage("\"" + FromText + "\"<" + FromEmail + ">", strArr[i].Trim(), sm.Subject, sm.Content); if (!string.IsNullOrEmpty(sm.FileName)) myMail.Attachments.Add(new Attachment(sm.FileName)); myMail.IsBodyHtml = true; myMail.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312"); myMail.SubjectEncoding = System.Text.Encoding.GetEncoding("GB2312"); System.Net.Mail.SmtpClient mySMTP = new SmtpClient(); mySMTP.Host = SendHost; mySMTP.UseDefaultCredentials = true; mySMTP.Credentials = new System.Net.NetworkCredential(UserName, UserPass); mySMTP.DeliveryMethod = SmtpDeliveryMethod.Network; try { mySMTP.Send(myMail); } catch (Exception ex) { InsertError(ex, sm); } } } try { if (!string.IsNullOrEmpty(sm.FileName)) DeleteFileName(sm.FileName); return true; } catch { } } } return false; //return true; }
IEnumerator Start() { yield return new WaitForSeconds (1); memoryObj = GameObject.Find ("MemoryObject"); if (memoryObj != null) { print (memoryObj); memorize = memoryObj.GetComponent<Memorize> (); stageName = memorize.fGetStageName (); print(memorize.fGetStageName ()); } print (stageName); saveName = pathT + "/" + stageName; if (saveType == 3) { int ln = saveName.Length; GameObject.Find ("saveFolderText").GetComponent<Text> ().text = "all system green "; } createstagecontroll = GameObject.Find ("Main").GetComponent<CreateStageControll> (); sendmail = GameObject.Find ("Main").GetComponent<SendMail> (); }
protected void btnSave_OnClick(object sender, EventArgs e) { string researchid = txtResearchList.Text; if(string.IsNullOrWhiteSpace(researchid) && !CheckBox1.Checked) { ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "<SCRIPT LANGUAGE=\"JavaScript\">alertify.error(\"الرجاء اختيار باحث على الاقل\")</SCRIPT>", false); return; } if (string.IsNullOrWhiteSpace(txtSubject.Text)) { ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "<SCRIPT LANGUAGE=\"JavaScript\">alertify.error(\"الرجاء ادخال عنوان الرسالة\")</SCRIPT>", false); return; } if (string.IsNullOrWhiteSpace(txtTxt.Text)) { ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "<SCRIPT LANGUAGE=\"JavaScript\">alertify.error(\"الرجاء ادخال الرسالة\")</SCRIPT>", false); return; } Database db=new Database(); DataTable dt; if(!CheckBox1.Checked) { dt = db.ExecuteDataTable("select * from Researcher where isAproved=1 and (id in (" + researchid + "))"); } else { dt = db.ExecuteDataTable("select * from Researcher where isAproved=1"); } List<string> to=new List<string>(); AppFunctions validate=new AppFunctions(); foreach (DataRow row in dt.Rows) { if(RadioButtonList1.SelectedValue.Equals("1")) { if (validate.IsEmailValid(row["email"].ToString())) { to.Add(row["email"].ToString()); } } else { if (validate.IsPhoneValid(row["phone"].ToString())) { to.Add(row["phone"].ToString()); } } } if (RadioButtonList1.SelectedValue.Equals("1")) { SendMail mail = new SendMail(); mail.SendMsg(to, txtSubject.Text, txtTxt.Text); ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "<SCRIPT LANGUAGE=\"JavaScript\">alertify.success(\"تم ارسال رسالة بريد الالكتروني الى الباحثين و عددهم " + dt.Rows.Count+"\")</SCRIPT>", false); } else { Tools t = new Tools(); SMSSender sms = new SMSSender(); sms.Message = txtTxt.Text; sms.SendSms(to); ScriptManager.RegisterStartupScript(this, this.GetType(), "WriteMsg", "<SCRIPT LANGUAGE=\"JavaScript\">alertify.success(\"تم ارسال رسالة نصية الى الباحثين و عددهم " + dt.Rows.Count + "\")</SCRIPT>", false); } }
private void SendMailThatPlayersAreChanged() { if (_PlayersChange.Count > 0) { var addresses = RegistrySettings.AddressesList(); if (addresses.Count > 0) { StringBuilder messageBody = new StringBuilder(); messageBody.AppendLine("<html>"); messageBody.AppendLine(@" <head> <style type=""text/css""> table, th, td { border: 1px solid black; border-collapse: collapse; } th, td { padding: 2px; } </style> </head> " ); messageBody.AppendLine(_Server.ServerModel.ToString() + "<br/><br/>New players:"); messageBody.AppendLine(@" <table> <thead> <tr> <th>Name</th> <th>Score</th> </tr> </thead> "); messageBody.AppendLine("<tbody>"); foreach (var player in _PlayersChange) { messageBody.AppendLine(string.Format("<tr><td>{0}</td><td>{1}</td></tr>", player.Name, player.Score)); } messageBody.AppendLine("</tbody>"); messageBody.AppendLine("</table>"); messageBody.AppendLine("</html>"); SendMail sm = new SendMail(RegistrySettings.GMailUser, RegistrySettings.GMailPass, RegistrySettings.GMailSmtpAddress, RegistrySettings.GMailSmtpPort); foreach (var toAdr in addresses) if (!string.IsNullOrWhiteSpace(toAdr)) sm.Send(toAdr, string.Format("Players changed on server '{0}'. Map '{1}", _Server.ServerModel.Name, _Server.ServerModel.Map), messageBody.ToString()); } } }
protected void btnUpload_Click(object sender, EventArgs e) { int fileLength; bool success; bool emailSuccess; //two different connection strings to use to overwrite the doc if there is one in there already string connectionString = "INSERT INTO Docs (WorkOrderID, EmpID, Doc) VALUES (@WorkOrderID, @EmpID, @Doc)"; string altConnString = "UPDATE Docs SET Doc = @Doc, EmpID = @EmpID WHERE WorkOrderID = @WorkOrderID"; //test the docs table and see if there is a doc in there and then switch the connection string string connection = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString; SqlConnection conn = new SqlConnection(connection); SqlCommand cmd = new SqlCommand("SELECT DocID from Docs WHERE WorkOrderID = @WorkOrderID;", conn); cmd.Parameters.AddWithValue("@WorkOrderID", woID); conn.Open(); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); if (dt.Rows.Count > 0) { connectionString = altConnString; } conn.Close(); dt.Clear(); //first check to see if there is actually a file selected, then do work if (cstFileUp.HasFile) { string fileExt = System.IO.Path.GetExtension(cstFileUp.FileName); if (fileExt == ".pdf") { //get the file length to initialize the array to fileLength = cstFileUp.PostedFile.ContentLength; byte[] fileBytes = new byte[fileLength - 1]; //read the bytes of the file fileBytes = cstFileUp.FileBytes; //create a new instance to use its methods FileWork fw = new FileWork(); //method returns a boolean to check for successfull addition of the file to the db success = fw.UploadFile(connectionString, woID.ToString(), fileBytes); if (success) { SendMail sm = new SendMail(); emailSuccess = sm.Send_CustMail(woID.ToString()); if (emailSuccess) { lblUploadStatus.Text = "Your file has been uploaded and the Customer has been notified."; lblUploadStatus.ForeColor = System.Drawing.Color.Green; lblUploadStatus.Visible = true; } else { lblUploadStatus.Text = "The file was uploaded but the system failed to notify the customer. Please notify the customer manually."; lblUploadStatus.ForeColor = System.Drawing.Color.Red; lblUploadStatus.Visible = true; } } else { lblUploadStatus.Text = "There was an error uploading your file. Please try again later"; lblUploadStatus.ForeColor = System.Drawing.Color.Red; lblUploadStatus.Visible = true; } } else { lblUploadStatus.Text = "File is not a PDF. Please only upload PDF documents"; lblUploadStatus.ForeColor = System.Drawing.Color.Red; lblUploadStatus.Visible = true; } } else { lblUploadStatus.Text = "There was no file specified to upload"; } }
private void OpenMailForm(object sender, EventArgs e) { SendMail mailForm = new SendMail(contacts, login.Username, login.Password); mailForm.Show(); }
//发邮件部分 private void SendMail(string Mail_Body) { string P_Language="cn"; string FajianName,MailTo,Mail_subject; string sql="select top 1 fajianname,em_order from webset where planguage='"+P_Language+"'"; OleDbCommand comm=new OleDbCommand(sql,conn); OleDbDataReader dr=comm.ExecuteReader(); if(dr.Read()) { FajianName=dr["fajianname"].ToString(); MailTo=dr["em_order"].ToString(); Mail_subject="来自"+FajianName+"的在线支付通知"; if(MailTo!="") { SendMail Mail=new SendMail(P_Language); bool sendresult=Mail.Send(MailTo,"","",Mail_subject,Mail_Body);//发邮件 } } }