public void CheckIfEmailingAttachement_ReturnsResponseMessage() { string nameOfExchangeserver = @"https://outlook.nhs.net/EWS/exchange.asmx"; ModelLoginDetails login = new ModelLoginDetails { Domain = string.Empty, ExchangeServerAddress = @"https://outlook.nhs.net/EWS/exchange.asmx", Password = "", UserName = "******" }; SendEmail send = new SendEmail(login); BodyType type = new BodyType(); type.BodyType1 = BodyTypeType.Text; send.DetailsWithAttachment( new ModelEmailDetails { SubjectOfEmail = "This is the Subject of the Email", BodyOfEmail = "This is the body of the Email", SenderEmail = "*****@*****.**", RecepientEmail = "*****@*****.**", AttachmentLocation = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"GitHub\NhsCommissioningMailer\CommissioningMailer\SampleData\") + "Surgery.csv", BodyType = type, ContentType = "text/comma-separated-values" }); Assert.True(send.ResponseMessage.Contains("NoError")); }
public void WhenSmtpClientFailsToSendThenErrorStatusReturned() { using (ShimsContext.Create()) { var emailInfo = new EmailInformation { }; ShimMailAddress.ConstructorStringString = (@this, addr, name) => { new ShimMailAddress(@this); }; int emailSendCalled = 0; ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { ++emailSendCalled; throw new SmtpException("Error sending email."); }; }; ShimMailMessage.Constructor = @this => { var msg = new ShimMailMessage(@this); msg.FromSetMailAddress = mailAddr => { }; msg.ToGet = () => new MailAddressCollection(); msg.SubjectSetString = subject => { }; msg.BodySetString = bodyText => { }; msg.IsBodyHtmlSetBoolean = isHtml => { }; }; var sendEmail = new SendEmail(); var status = sendEmail.Send(emailInfo); Assert.AreEqual(1, emailSendCalled); Assert.IsNotNull(status); Assert.AreEqual(false, status.WasSent); Assert.AreEqual("Error sending email.", status.ErrorMessage); } }
public bool SendEmail(Property objProp) { CheckEmailDAL objEmail = new CheckEmailDAL(); if (objEmail.getUser(objProp) == 1) { SendEmail sendEmail = new SendEmail(); if (sendEmail.sendEmail(objProp)) flag = true; else flag = false; } else { flag = false; } return flag; }
protected void Page_Load(object sender, EventArgs e) { CheckRole("email"); if (!Page.IsPostBack) { if (Request.QueryString["E_ID"].ToString() != "") { SendEmail se = new SendEmail(); XYECOM.Model.SendEmailInfo Info = se.GetItem(Convert.ToInt32(Request.QueryString["E_ID"].ToString())); if (null != Info) { this.lbtitle.Text = Info.E_title; this.lbcontent.Text = Info.E_content; this.lbtime.Text = Info.AddTime.ToShortDateString(); } } } }
protected void gvlist_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "del") { SendEmail se = new SendEmail(); int i = 0; i = se.Delete(Convert.ToInt32(this.gvlist.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString())); string url = "SendEmail.aspx"; if (i >= 0) { Alert("删除成功!", url); dvDataBind(); } else { Alert("删除失败!", url); } } }
public ActionResult Contact(ContactModel contactModel) { ViewBag.PageTitle = "CodeGenerate.me - Contact us today."; if (ModelState.IsValid) { SendEmail sendEmail = new SendEmail(contactModel.Email, contactModel.Subject, contactModel.Description, contactModel.Name); // Successful contactModel.SentSuccesfully = sendEmail.SentSuccessfully; } else { // Not ready - validation failed contactModel.SentSuccesfully = 1; } return View(contactModel); }
protected void BtnSend_Click(object sender, EventArgs e) { string companyName = iptCompany.Text; string name = this.name.Text; string tel = iptNumber.Value; string phone = iptPhone.Value; string fax = iptFax.Value; string mail = this.iptEmail.Text; // iptEmail.Value; string address = iptAddress.Value; string webSite = iptWebSite.Value; string optionItem = sltOption.Value; string message = txtMessage.Value; string keyword = sltKeyword.Value; if(companyName == "" || name == "" || tel == "" || mail =="") { Response.Write("<script type='text/javascript'> alert('請確認是『必填』欄位是否已填入。');</script>"); return; } string content = "公司名稱:" + companyName + "<p/>聯絡人:" + name + "<p/>客戶電話:" + "<p/>客戶手機:" + phone + "<p/>客戶信箱:" + mail + "<p/>客戶地址:" + address + "<p/>客戶網站:" + webSite + "<p/>詢問事項:" + optionItem + "<p/>詢問內容:" + message + "<p/>搜尋關鍵字為:" + keyword; SendEmail se = new SendEmail(); try { Dictionary<string, Stream> listStream = new Dictionary<string, Stream>(); string s = se.Mail_Send(SendEmail.sendMail, SendEmail.receiveMails.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries), new string[] { }, SendEmail.mailTitle, content, true, listStream); if (s == "成功") Response.Write("<script type='text/javascript'> alert('信件傳送成功');</script>"); else Response.Write("<script type='text/javascript'> alert('信件伺服器異常,請直接來電與本公司聯繫(02)2998-8895');</script>"); Response.AddHeader("Refresh", "0"); } catch(Exception ex) { MessageBox(ex.ToString()); } }
public IActionResult ForgotPassword(ForgotPasswordViewModel forgot) { if (!ModelState.IsValid) { return(View(forgot)); } string fixedemail = FixedText.Fixemail(forgot.Email); User user = _UserService.getuserbyemail(fixedemail); if (user == null) { ModelState.AddModelError("Email", "کاربری با این ایمیل یافت نشد"); return(View(forgot)); } string body = _viewRender.RenderToStringAsync("forgotpasswordemail", user); SendEmail.Send(forgot.Email, "بازیابی کلمه عبوری", body); ViewBag.issuccess = true; return(View()); }
public async Task <IActionResult> ForgotPassword(ForgotPassViewModel forgotModel) { if (!ModelState.IsValid) { return(View(forgotModel)); } var user = new User(); string userEmail = FixedText.FixedEmail(forgotModel.Email); if ((user = await _UserService.ForgotPassword(userEmail)) == null) { ModelState.AddModelError("Email", "ایمیل وارد شده یافت نشد"); return(View(forgotModel)); } else { string bodyEmail = _renderViewService.RenderToStringAsync("_ForgotPassword", user); SendEmail.Send(userEmail, "ایمیل تایید فراموشی رمز عبور", bodyEmail); ViewBag.IsSuccess = true; return(View()); // return View("ChangePassEmailConfirmation", model: user); } }
public IActionResult ForgotPassword(ForgotPasswordVM forgot) { var Email = forgot.Email; var Get = _employeeRepository.Get(); var CheckLogin = Get.FirstOrDefault(x => x.Email == forgot.Email); if (CheckLogin != null) { Guid newPassword = Guid.NewGuid(); Account account = new Account { NIK = CheckLogin.NIK, AccountPassword = newPassword.ToString("N").Substring(0, 6) }; _accountRepository.ChangePassword(CheckLogin.NIK, account.AccountPassword); SendEmail.ForgotPassword(Email, account.AccountPassword); return(Ok(new { status = HttpStatusCode.OK, message = "New Password has been send to your Email" })); } else { return(NotFound(new { status = HttpStatusCode.OK, message = "Email you entered is wrong" })); } }
public ActionResult ForgotPassword(ForgotPasswordViewModel forgotPasswordViewModel) { if (!(ModelState.IsValid)) { ModelState.AddModelError("UserEmail", "ایمیل را وارد کنید"); return(View(forgotPasswordViewModel)); } var user = _userService.GetUserByEmail(forgotPasswordViewModel.UserEmail); if (user == null) { ModelState.AddModelError("UserEmail", "این ایمیل یافت نشد"); return(View(forgotPasswordViewModel)); } string send = SendEmail.Send(user.UserEmail, "باز یابی کلمه عبور", _viewRenderService.RenderToStringAsync("_ForgotPassworEmail", user)); if (send != "1") { ModelState.AddModelError("UserEmail", "خطا در ارسال ایمیل بازیابی "); return(View(forgotPasswordViewModel)); } ViewBag.isSucsses = true; return(View()); }
public async Task SendVerificationAsync(UserDefinition user, string ccEmail = null) { string retUrl = Manager.ReturnToUrl; string urlOnly; QueryHelper qh = QueryHelper.FromUrl(Manager.CurrentSite.LoginUrl, out urlOnly); qh.Add("Name", user.UserName, Replace: true); qh.Add("V", user.VerificationCode, Replace: true); string urlNoOrigin = qh.ToUrl(urlOnly); qh.Add("CloseOnLogin", "true", Replace: true); qh.Add(Globals.Link_OriginList, Utility.JsonSerialize(new List <Origin> { new Origin { Url = retUrl } }), Replace: true); string url = qh.ToUrl(urlOnly); SendEmail sendEmail = new SendEmail(); object parms = new { User = user, Url = Manager.CurrentSite.MakeUrl(url), UrlNoOrigin = Manager.CurrentSite.MakeUrl(urlNoOrigin), Code = user.VerificationCode, }; string subject = this.__ResStr("verificationSubject", "Verification required for site {0}", Manager.CurrentSite.SiteDomain); await sendEmail.PrepareEmailMessageAsync(user.Email, subject, await sendEmail.GetEmailFileAsync(Package.GetCurrentPackage(this), "Account Verification.txt"), Parameters : parms); if (!string.IsNullOrWhiteSpace(ccEmail)) { sendEmail.AddBcc(ccEmail); } await sendEmail.SendAsync(true); SendingEmailAddress = await sendEmail.GetSendingEmailAddressAsync(); }
public async Task SendPasswordResetEmailAsync(UserDefinition user, string ccEmail = null) { ResetPasswordModule resetMod = (ResetPasswordModule)await ModuleDefinition.CreateUniqueModuleAsync(typeof(ResetPasswordModule)); ModuleAction reset = resetMod.GetAction_ResetPassword(null, user.UserId, user.ResetKey.ToString()); SendEmail sendEmail = new SendEmail(); object parms = new { User = user, ResetUrl = reset.GetCompleteUrl(), ResetKey = user.ResetKey.ToString(), ValidUntil = Formatting.FormatDateTime(user.ResetValidUntil), }; string subject = this.__ResStr("resetSubject", "Password Reset for {0}", Manager.CurrentSite.SiteDomain); await sendEmail.PrepareEmailMessageAsync(user.Email, subject, await sendEmail.GetEmailFileAsync(Package.GetCurrentPackage(this), "Password Reset.txt"), Parameters : parms); if (!string.IsNullOrWhiteSpace(ccEmail)) { sendEmail.AddBcc(ccEmail); } await sendEmail.SendAsync(true); SendingEmailAddress = await sendEmail.GetSendingEmailAddressAsync(); }
private void SendMarkedToSendEmail(Request req) { // Send mail only if there are jobs (e.g. request was MTS and the service is changed) if (req.SourceMaterials.SelectMany(sm => sm.Jobs).Any()) { string priority = req.SourceMaterials.SelectMany(x => x.Jobs).OrderByDescending(j => j.Priority.DisplayOrder).First().Priority.DefaultLabel; string status = req.Status.Code == "MTS" ? "Marked to Send" : "Submitted"; var model = new { Client = req.Client.Abbreviation, Id = req.Id, Identifier = req.RequestIdentifier, Status = status, Priority = priority, Website = ConfigurationManager.AppSettings["ClientPortalAddress"], Username = HttpContext.Current.User.Identity.Name, NumberOfSourceMaterials = req.SourceMaterials.Count, Drafter = req.CreatedBy, ClientReference = req.ClientReference }; var template = Session.Query <EmailTemplate>().Where(x => x.Code == "CPMTS").SingleOrDefault(); var mail = new SendEmail { Subject = Engine.Razor.RunCompile(template.EmailSubject, "emailSubject", null, model, null), Body = Engine.Razor.RunCompile(template.EmailBody, "emailMTS", null, model, null), Priority = (EmailPriorityEnum)template.Priority }; //get all users in roles senders IList <string> to = getMailTo(req); mail.ReplyTo.Add(ConfigurationManager.AppSettings["ReplyToAddress"]); mail.To.AddRange(to); _messageSession.Send(mail); } }
public async Task SendNewUserRegistrationNotification(string UserId) { EmailMessage message = new EmailMessage(); message.Subject = "New user registered"; string temp = (ConfigurationManager.AppSettings["SalesManager"]); string domain = ConfigurationManager.AppSettings["CurrentDomain"]; message.To = "*****@*****.**"; string link = domain + "/SaleOrderHeader/Detail/" + UserId + "?transactionType=approve"; SaleOrderHeader doc = new SaleOrderHeader(); using (ApplicationDbContext context = new ApplicationDbContext()) { var RegUser = (from p in context.Users where p.Id == UserId select p).FirstOrDefault(); message.Body += "New user " + RegUser.UserName + " registered"; } SendEmail se = new SendEmail(); await se.configSendGridasync(message); }
protected void Button2_Click(object sender, EventArgs e) { GridViewRow row = GridView1.SelectedRow; ConnectDB cdb = new ConnectDB(); cdb.connectDataBase(); SqlConnection con = cdb.connect; con.Open(); SqlCommand com = cdb.command; com.CommandText = "UPDATE theater_user set payment = '0' where user_id = @user_id2"; com.Parameters.AddWithValue("@user_id2", row.Cells[1].Text); com.ExecuteNonQuery(); GridView1.DataBind(); Table4.Visible = false; string email = row.Cells[3].Text; string subject = "SHOWIME : PAYMENT"; string msg = "Hello...<br> Your Remaining Amount Of Rs." + row.Cells[9].Text + " has been paid by SHOWTIME.<br><br><br>Thank You."; SendEmail se = new SendEmail(); se.sendEmail(email, subject, msg, ""); }
public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, Created = DateTime.Now, CurrentLog = DateTime.Now, FirstName = model.FirstName, LastName = model.LastName, Address = model.Address, City = model.City, PostalCode = model.PostalCode, Subscribe = model.Subscribe }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { // OM: Assign Role to User for whoever Registers // OM: Finish registration and role assigning and then sign user in to get proper user functionalities tp work correctly (Authorization, cart) await this.UserManager.AddToRoleAsync(user.Id, "User"); string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code }, protocol: Request.Url.Scheme); string body = string.Empty; using (StreamReader reader = new StreamReader(Server.MapPath("~/Email/AccountConfirmation.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{ConfirmationLink}", callbackUrl); body = body.Replace("{UserName}", model.UserName); bool IsSendEmail = SendEmail.EmailSend(model.Email, "Confirm your account", body, true); if (IsSendEmail) { return(RedirectToAction("EmailSent", "Account")); } } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public void EmailOnPracticeRes(int reservationId, string inviteeName, int clientId) { var rsv = Require <ReservationInfo>(reservationId); IList <ResourceClientInfo> clients = Session.SelectNotifyOnPracticeRes(rsv.ResourceID).ToList(); if (clients == null || clients.Count == 0) { return; } string fromAddr, subject, body; List <string> toAddr = new List <string>(); fromAddr = Properties.Current.SchedulerEmail; subject = $"{SendEmail.CompanyName} - {Clients.GetDisplayName(rsv.LName, rsv.FName)} has made Practice reservation on {rsv.ResourceName}"; body = string.Format("Practice reservation from {0} to {1}. The invitee is {2}.", rsv.BeginDateTime.ToString(Reservation.DateFormat), rsv.EndDateTime.ToString(Reservation.DateFormat), inviteeName); foreach (ResourceClientInfo rc in clients) { if (!rc.IsEveryone()) { toAddr.Add(rc.Email); } } if (toAddr.Count == 0) { return; } SendEmail.Send(clientId, "LNF.Scheduler.EmailUtility.EmailOnPracticeRes", subject, body, fromAddr, toAddr); }
public void SendRegisterOTP(Employee e) { var emailID_lowercase = e.EmailID.ToLower(); HttpContext.Current.Session["UserEmail"] = e.EmailID; // session of email ID final var entity = entities.usp_EmailValidate(emailID_lowercase).ToList(); var CharPool = "0123456789"; var stringChars = new char[6]; var random = new Random(); for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = CharPool[random.Next(CharPool.Length)]; } System.Web.HttpContext.Current.Session["GeneratedOTP"] = new String(stringChars); SendEmail send = new SendEmail(); System.Web.HttpContext.Current.Session["OTPTimeStamp"] = DateTime.Now; int x = send._SendEmail("*****@*****.**", System.Web.HttpContext.Current.Session["UserEmail"].ToString(), "Registration OTP", "Hi " + System.Web.HttpContext.Current.Session["UserName"] + ",<br><br> The OTP for registration is : " + System.Web.HttpContext.Current.Session["GeneratedOTP"] + "<br><br>Regards<br>RYM Team"); }
public ActionResult SimulatePay() { var userId = GetId(); Customer customerForEmail = db.Customers.Include(c => c.State).Where(c => c.UserId == userId).Single(); int customerId = db.Customers.Where(c => c.UserId == userId).Select(c => c.Id).Single(); Payment payment = new Payment(); payment.AmountDue = 30; payment.TotalPaid = db.Payments.Where(c => c.CustomerId == customerId).OrderByDescending(p => p.Id).Select(p => p.TotalPaid).FirstOrDefault() + 30; payment.CustomerId = customerId; payment.Date = DateTime.Now; db.Payments.Add(payment); db.SaveChanges(); // Call email to notify customer of payment Shipment shipmentToUpdate = db.Shipments.Where(s => s.CustomerId == customerId).OrderByDescending(p => p.Id).FirstOrDefault(); if (shipmentToUpdate != null) { shipmentToUpdate.Delivered = true; shipmentToUpdate.DateDelivered = DateTime.Now; db.Entry(shipmentToUpdate).State = EntityState.Modified; db.SaveChanges(); } Shipment shipment = new Shipment() { Status = false, Delivered = false, CustomerId = customerId }; db.Shipments.Add(shipment); db.SaveChanges(); // Call email to notify admin of new pending shipment SendEmail.Main(customerForEmail); return(RedirectToAction("Main")); }
public void AddUserJob() { string jobTitle = txtNewUerJobTitle.Value; string jobDesc = txtNewUserJobDesc.Value; string jobLoc = txtNewUserJobLoc.Value; string jobExp = txtNewUserJobExp.Value; string company = txtNewUserJobCompany.Value; Jobs job = new Jobs("N", jobTitle.Trim(), jobDesc.Trim(), jobExp.Trim(), company.Trim(), jobLoc); job.Email = ApplicationSession.Current.user.Email; string adminMessage = SendEmail.BuildPostedJobAdminMail(ApplicationSession.Current.user, job); if (JobBO.AddJob(job, string.Empty, adminMessage, Constants.MailSubject)) { AddUserJobSuccess.Visible = true; //Mailing Windows Service //SendEmail.ReceiveJobEmail(ApplicationSession.Current.user, job); } ApplicationSession.Current.Jobs.Clear(); //FillGrid(); //Email Needs to be sent //ResetControls(); }
public static void OpenURL() { try { webdriver.Url = Readdata.ProcessOnCollection(LoginCollection, "URL"); if (webdriver.Url != null) { webdriver.Url = Readdata.ProcessOnCollection(LoginCollection, "URL"); webdriver.Manage().Window.Maximize(); Thread.Sleep(12000); TakeScreenShot("Pass"); } } catch (Exception Ex) { logger.WriteLog(Ex); ExtentReport.EndReport(); SendEmail.email_send(ExtentReport.reportPath, logger.ErrorLogFilePath, SystemMachineName, MailCollection, ProjectName); webdriver.Quit(); DemoSkip = true; } }
public ActionResult SendEmail(SendEmail sm) { string key = ConfigurationManager.AppSettings["Sendgrid.Key"]; SendGridEmailService messageSvc = new SendGridEmailService(key); string htmlBody = $@"<ul> <li>Name: {sm.Name}</li> <li>Email: {sm.Email}</li> <li>Message Details: {sm.Message}</li> </ul>"; var msg = new EmailMsg() { Body = htmlBody, Subject = sm.Subject, From = sm.Name, Recipient = sm.Email }; return(RedirectToAction("Success", "Home")); //messageSvc.SendMail(msg, true, fileName, fileData); //var fileName = FileConverter.GetFilePath("Logs\\2018-05-21.log"); //var fileData = FileConverter.Convert(fileName); //attaches file //string envPath = HttpRuntime.AppDomainAppPath; //string fileName = $"{envPath}\\Content\\assets\\images\\logo_dark.png"; //byte[] imageData = null; //FileInfo fileInfo = new FileInfo(fileName); //long imageFileLength = fileInfo.Length; //FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); //BinaryReader br = new BinaryReader(fs); //imageData = br.ReadBytes((int)imageFileLength); //messageSvc.SendMail(msg, true, fileName, imageData); }
void Awake() { if (INSTANCE != null) { Destroy(gameObject); } else { INSTANCE = this; DontDestroyOnLoad(gameObject); } _dbConnection = GetComponent <DataBaseConnection>(); _dbVerification = GetComponent <DataBaseVerification>(); _dbCryptage = GetComponent <DataBaseCryptage>(); _dbRegister = GetComponent <DataBaseRegister>(); _dbChangePassword = GetComponent <DataBaseChangePassword>(); _dbUrl = GetComponent <DataBaseURL>(); _dbAdd = GetComponent <DataBaseAdd>(); _dbGet = GetComponent <DataBaseGet>(); _dbDelete = GetComponent <DataBaseDelete>(); _sendEmail = GetComponent <SendEmail>(); _message = GetComponent <Message>(); }
public void CanSerializeSendEmail() { var ser = new XmlSerializer(typeof(SendEmail)); var sendEmail = new SendEmail( timeStamp: DateTime.Now, to: "*****@*****.**", cc: "", bcc: "", body: "Hi there!", returnAddress: "*****@*****.**", topic: "emailsender"); using (var sw = new StringWriter()) { ser.Serialize(sw, sendEmail); Console.WriteLine(sw.ToString()); using (var sr = new StringReader(sw.ToString())) { var deserializedEmail = (SendEmail)ser.Deserialize(sr); Assert.AreEqual(sendEmail.TimeStamp, deserializedEmail.TimeStamp); } } }
private async Task DefaultLoadAsync() { try { var mailSettings = await TrackService.GetTrackSendEmailAsync(); if (mailSettings == null) { mailSettings = new SendEmail(); } await mailSettingsForm.InitAsync(mailSettings.Map <MailSettingsViewModel>(afterMap => { afterMap.MailProvider = mailSettings.SmtpHost?.IsNullOrWhiteSpace() == false ? MailProviders.Smtp : MailProviders.SendGrid; })); } catch (TokenUnavailableException) { await(OpenidConnectPkce as TenantOpenidConnectPkce).TenantLoginAsync(); } catch (Exception ex) { mailSettingsForm.SetError(ex.Message); } }
public static async Task EnviarCorreo(SendEmail email) { var message = new MailMessage(); message.To.Add(new MailAddress(email.To)); message.From = new MailAddress(WebConfigurationManager.AppSettings["AdminUser"]); message.Subject = email.Subject; message.Body = email.Body; message.IsBodyHtml = true; using (var smtp = new SmtpClient()) { var credentials = new NetworkCredential { UserName = WebConfigurationManager.AppSettings["AdminUser"], Password = WebConfigurationManager.AppSettings["AdminPassWord"] }; smtp.Credentials = credentials; smtp.Host = WebConfigurationManager.AppSettings["SMTPName"]; smtp.Port = int.Parse(WebConfigurationManager.AppSettings["SMTPPort"]); smtp.EnableSsl = true; await smtp.SendMailAsync(message); } }
public async Task <Ticket> Handle(CreateTicketCommand request, CancellationToken cancellationToken) { var ticket = _mapper.Map <Ticket>(request); HttpRequestAccountsApi _request = new HttpRequestAccountsApi(); var user = _request.GetUserById(ticket.UserId); var location = user.Location; var consultant = _request.GetBestConsultant(ticket.Category, location); ticket.ConsultantId = consultant.Id; ticket.Status = "Pending"; _request.UpdateNoOfTicketsConsultant(consultant.Id, consultant.NumberOfTickets, consultant.TotalNumberOfTickets); SendEmail _sendEmail = new SendEmail(); _sendEmail.SendEmailStatus(ticket.Status, user); ticket.ConsultantEmail = consultant.Email; ticket.ConsultantName = consultant.Username; ticket.UserEmail = user.Email; ticket.UserName = user.Username; return(await _repository.CreateAsync(ticket)); }
public ActionResult ForgotPassword(AccountViewModel.ForgotPasswordViewModel forgot) { if (!ModelState.IsValid) { return(View(forgot)); } string fixedEmail = FixText.FixEmail(forgot.Email); DataLayer.Entities.User.User user = _userService.GetUserByEmail(fixedEmail); if (user == null) { ModelState.AddModelError("Email", "کاربری یافت نشد"); return(View(forgot)); } string bodyEmail = _viewRenderService.RenderToStringAsync("_ForgotPassword", user); SendEmail.Send(user.Email, "بازیابی حساب کاربری", bodyEmail); ViewBag.IsSuccess = true; return(View()); }
public ActionResult ForgotPassword([Bind(Include = "Email")] ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = db.AccountRepository.GetUserByEmail(model.Email); if (user == null) { ModelState.AddModelError("Email", "کاربری با این مشخصات یافت نشد"); return(View()); } if (user.IsActive == false) { ModelState.AddModelError("Email", "حساب کاربری وارد شده فعال نیست."); return(View()); } var body = PartialToStringClass.RenderPartialView("ManageEmails", "RecoveryPassword", user); SendEmail.Send(user.Email, "بازیابی رمز عبور", body); ViewBag.IsSuccess = true; return(View()); } return(View()); }
public async Task <ActionResult> SendEmails(SendEmail viewModel) { InquiryFormModel model = new InquiryFormModel(); model.FromName = viewModel.FromName; model.FromEmail = viewModel.FromEmail; model.Message = viewModel.Message; if (ModelState.IsValid) { var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>"; var message = new MailMessage(); message.To.Add(new MailAddress(viewModel.ToEmail)); message.From = new MailAddress("*****@*****.**"); // replace with valid value message.Subject = "Your email subject"; message.Body = string.Format(body, model.FromName, model.FromEmail, model.Message); message.IsBodyHtml = true; using (var smtp = new SmtpClient()) { var credential = new NetworkCredential { UserName = "******", // replace with valid value Password = "******" // replace with valid value }; smtp.Credentials = credential; smtp.Host = "smtp.gmail.com"; smtp.Port = 587; smtp.EnableSsl = true; await smtp.SendMailAsync(message); return(RedirectToAction("Sent")); } } return(View(model)); }
public void CreateUserTransaction(Transaccion transaction, bool isFromBus = false) { try { var cardManager = new TarjetaManager(); var card = cardManager.GeTarjetaByUniquecode(transaction.CardUniqueCode); if (card == null) { throw new BusinessException(301); } if (transaction.Type == null) { throw new BusinessException(302); } var userManager = new UsuarioManager(); var user = userManager.Retrieve(new Usuario { Email = card.Usuario.Identificacion }); if (transaction.Type.Equals("Recarga", StringComparison.CurrentCultureIgnoreCase)) { card.SaldoDisponible = card.SaldoDisponible + transaction.Charge; cardManager.UpdateSaldoTarjeta(card); } else { if (isFromBus) { transaction.Charge = card.Convenio != null && card.Convenio.CedulaJuridica != -1 ? transaction.Charge - (transaction.Charge * (card.Convenio.DescuentoTarifa / 100)): transaction.Charge - (transaction.Charge * (card.TipoTarjeta.DiscountPercentage / 100)); } card.SaldoDisponible = card.SaldoDisponible - transaction.Charge; if (card.SaldoDisponible < 0) { throw new BusinessException(304); } cardManager.UpdateSaldoTarjeta(card); if (card.SaldoDisponible <= user.SmsNotificationsMin) { var smsNotification = new SendSms(); smsNotification.SendSmsMessage(new SmsMessage { DestinationNumber = user.Telefono.ToString(), Message = "Su cuenta tiene poco saldo disponible, por favor recargue." }); } } var email = new SendEmail(); email.SendEmailInvoice(new EmailMessage { To = user.Email, Url = transaction.Charge.ToString(), Message = $"{transaction.Type} - {transaction.Description} " }); _crudFactory.Create(transaction); } catch (Exception e) { ExceptionManager.GetInstance().Process(e); } }
public async Task <ActionResult> Register(vmRegister model) { if (ModelState.IsValid) { if (model.IsChecked) { EComEntities db = new EComEntities(); var exist = db.Users.Where(a => a.UserName == model.UserName || a.Mobile == model.Mobile).FirstOrDefault(); if (exist != null) { if (exist.UserName == model.UserName) { ModelState.AddModelError("", "This username is taken.Please choose another one."); } else if (exist.Mobile == model.Mobile) { ModelState.AddModelError("", "This mobile is already registered."); } else if (exist.Email == model.Email) { ModelState.AddModelError("", "This email is already registered."); } return(View(model)); } else { var user = new ApplicationUser() { UserName = model.UserName, Mobile = model.Mobile, Code = AccCoder.Encode(model.Password) }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { SendEmail mail = new SendEmail(); //bool ds = mail.RegisterVarification(model.Email, user.VerificationCode, user.UserName); //if (ds) //{ // return RedirectToAction("Verification", "Account", new { token = user.Id }); // //return Verification(user.Id); //} //else //{ // ModelState.AddModelError("", "Mail sending failed."); //} string df = "ok"; if (df == "ok") { //return RedirectToAction("Verification", "Account", new { token = user.Id }); return(RedirectToAction("Login", "Account")); } else { ModelState.AddModelError("", df); } //await SignInAsync(user, isPersistent: false); //return RedirectToAction("Index", "Home"); } else { AddErrors(result); } } } else { ModelState.AddModelError("", "Please accept the User Agreement."); } } // If we got this far, something failed, redisplay form return(View(model)); }
/// <summary> /// Send /// </summary> /// <param name="idOrEmailAddress">Account id or email address</param> /// <param name="incident">Incident that the report belongs to</param> /// <param name="report">Report being processed.</param> /// <returns>task</returns> /// <exception cref="ArgumentNullException">idOrEmailAddress; incident; report</exception> public async Task SendAsync(string idOrEmailAddress, IncidentSummaryDTO incident, ReportDTO report) { if (idOrEmailAddress == null) { throw new ArgumentNullException("idOrEmailAddress"); } if (incident == null) { throw new ArgumentNullException("incident"); } if (report == null) { throw new ArgumentNullException("report"); } var config = ConfigurationStore.Instance.Load <BaseConfiguration>(); var shortName = incident.Name.Length > 40 ? incident.Name.Substring(0, 40) + "..." : incident.Name; // need to be safe for subjects shortName = shortName.Replace("\n", ";"); var baseUrl = string.Format("{0}/#/application/{1}/incident/{2}", config.BaseUrl.ToString().TrimEnd('/'), report.ApplicationId, report.IncidentId); //TODO: Add more information var msg = new EmailMessage(idOrEmailAddress); if (incident.IsReOpened) { msg.Subject = "ReOpened: " + shortName; msg.TextBody = string.Format(@"Incident: {0} Report url: {0}/report/{1} Description: {2} Exception: {3} {4} ", baseUrl, report.Id, incident.Name, report.Exception.FullName, report.Exception.StackTrace); } else if (incident.ReportCount == 1) { msg.Subject = "New: " + shortName; msg.TextBody = string.Format(@"Incident: {0} Description: {1} Exception: {2} {3}", baseUrl, incident.Name, report.Exception.FullName, report.Exception.StackTrace); } else { msg.Subject = "Updated: " + shortName; msg.TextBody = string.Format(@"Incident: {0} Report url: {0}/report/{1} Description: {2} Exception: {3} {4} ", baseUrl, report.Id, incident.Name, report.Exception.FullName, report.Exception.StackTrace); } var emailCmd = new SendEmail(msg); await _commandBus.ExecuteAsync(emailCmd); }
protected void btnCommit_Click(object sender, EventArgs e) { Model.Log log = new Model.Log(); int meetingApplyFormID = int.Parse(this.hfdMeetingApplyFormID.Value); Model.Meeting meeting = BusinessLogic.Meeting.GetApplyMeetingInfoByMeeingID(meetingApplyFormID); meeting.MeetingApplyFormID = meetingApplyFormID; meeting.WFID = BusinessLogic.Meeting.GetGuidByApplyForm(meetingApplyFormID); if (rbtAgree.Checked) { //同意 meeting.MeetingStatus = 4; //todo 发送邮件给与会者 MailModel mailModel = new MailModel(); Model.Meeting me = BusinessLogic.Meeting.GetApplyMeetingInfoByMeeingID(meetingApplyFormID); List <Model.UserInfo> UserEmailAndName = BusinessLogic.MeetingUser.GetUserEmailAndNameByMeetingApplyFormID(meetingApplyFormID); #region E-Mail Body System.Text.StringBuilder sbMailBody = new System.Text.StringBuilder(); sbMailBody.Append("您好!"); sbMailBody.Append(""); sbMailBody.Append("邀请您参加"); sbMailBody.Append(meeting.BeginTime); sbMailBody.Append("到"); sbMailBody.Append(meeting.EndTime); sbMailBody.Append(",在"); sbMailBody.Append(BusinessLogic.MeetingRoom.GetMeetingRoomNameByMeetingApplyFormID(meetingApplyFormID)); sbMailBody.Append("召开的会议。谢谢!如有事情耽搁,请与"); sbMailBody.Append(BusinessLogic.MeetingUser.GetUserEmailAndNameByMeetingApplyFormID(meetingApplyFormID).ToArray()[0].UserEmail); sbMailBody.Append("这个Email联系。"); #endregion mailModel.MailFrom = ConfigurationManager.AppSettings["commomEmail"].ToString(); mailModel.Password = ConfigurationManager.AppSettings["emailPassword"].ToString(); mailModel.SmtpServer = ConfigurationManager.AppSettings["smtpServer"].ToString(); mailModel.SmtpPort = int.Parse(ConfigurationManager.AppSettings["port"].ToString()); mailModel.DisplayName = "会议邀请"; mailModel.MailBcc = null; mailModel.MailCc = null; mailModel.MailSubject = meeting.MeetingTopic; mailModel.MailBody = sbMailBody.ToString(); mailModel.MailTo = null;//此处留空,在SendEmail里才会赋值 mailModel.SmtpPort = 25; mailModel.SmtpSsl = false; mailModel.UserName = ConfigurationManager.AppSettings["userName"].ToString(); try { SendEmail.SendEmailTo(UserEmailAndName, mailModel); lblMessage.Text = "会议设备安排成功!"; } catch (YunShanOA.Common.SendMailFailExecpion sendMailFail) { log = new Model.Log(); log.LogContext = sendMailFail.Message; log.LogTime = System.DateTime.Now; log.userName = Page.User.Identity.Name; log.LogTypeID = "1"; BusinessLogic.Log.SaveLog(log); lblMessage.Text = "发送邮件出现异常,请联系申请人重新申请!申请人Email:" + BusinessLogic.MeetingUser.GetUserEmailByUserName(log.userName); } } else { //不同意 meeting.MeetingStatus = 3; Dictionary <int, int> meetingIDAndName = BusinessLogic.MeetingEquipment.GetMeetingEquipmentIDAndCount(meetingApplyFormID); foreach (var m in meetingIDAndName) { BusinessLogic.MeetingEquipment.ReturnEquipmentCount(m.Key, m.Value); } } //todo 更新MeetingAndRoom里的状态,有待测试 lblMessage.Text = "会议设备处理成功"; //更新MeetingAndRoom表里的状态 BusinessLogic.MeetingRoom.UpdateMeetingAndRoomStatus(meetingApplyFormID, meeting.MeetingStatus); BusinessLogic.Meeting.UpdateMeetingApplyFormStatus(meetingApplyFormID, meeting.MeetingStatus); Server.Transfer("~/OfficeAdmin/ProcessMeetingEquipmentArr.aspx"); }
public ActionResult API(ContactModel contactModel) { ViewBag.PageTitle = "CodeGenerate.me - Our new API is currently in development."; if (ModelState.IsValid) { SendEmail sendEmail = new SendEmail(contactModel.Email, contactModel.Subject, contactModel.Description, contactModel.Name); // Successful contactModel.SentSuccesfully = 2; } else { // Not ready - validation failed contactModel.SentSuccesfully = 1; } return View(contactModel); }
public ActionResult Contacto(ContactoCondominioModel model) { if (ModelState.IsValid) { BaseDatosSQL.GuardarContacto(model); SendEmail Email = new SendEmail(); Email.DE("SEGURICEL® <*****@*****.**>"); Email.PARA("*****@*****.**"); Email.ASUNTO("Contacto recibido desde SEGURICEL®"); string path = Server.MapPath(@"../Imagenes/logo_nuevo_small.png"); LinkedResource logo = new LinkedResource(path, MediaTypeNames.Image.Gif); logo.ContentId = "logo"; string _htmlContent = string.Empty; _htmlContent = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"; _htmlContent += "<html xmlns='http://www.w3.org/1999/xhtml'>"; _htmlContent += "<head>"; _htmlContent += "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />"; _htmlContent += "<title>Solicitudes para el Salón de Fiestas</title>"; _htmlContent += "</head>"; _htmlContent += "<body style='font-family: Arial, Helvetica, sans-serif;"; _htmlContent += "font-size: 9pt; color: #666'>"; _htmlContent += "<table cellpadding='2' cellspacing='0' style='width:100%;'>"; _htmlContent += "<tr>"; _htmlContent += "<td align='center' style='font-family:Arial; font-size:12pt;'>"; _htmlContent += "<table cellpadding='0' cellspacing='0' width='700px'>"; _htmlContent += "<tr>"; _htmlContent += "<td align='left' style='width:10%;background-color: #E6E6E6; '>"; _htmlContent += "<img src=\"cid:Pic1\" alt='Seguricel' />"; _htmlContent += "</td>"; _htmlContent += "<td align='center' style='width:90%; font-size:18pt; font-weight:bold; color:Navy; vertical-align:bottom;background-color: #E6E6E6; '>"; _htmlContent += "Contacto recibido desde SEGURICEL®</td>"; _htmlContent += "</tr>"; _htmlContent += "<tr>"; _htmlContent += "<td colspan='2' align='left' style='text-align:justify; padding: 10px 2px 0px 15px;'>"; _htmlContent += model.ContactoHeader; _htmlContent += "</td>"; _htmlContent += "</tr>"; _htmlContent += "<tr>"; _htmlContent += "<td colspan='2' align='left' style='text-align:justify; padding: 10px 2px 0px 15px; font-weight:bold;'>"; _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.NombreContactoLabel, model.NombreContacto, "<br />"); _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.EmailContactoLabel, model.EmailContacto, "<br />"); _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.TelefonoLocalContactoLabel, model.TelefonoLocalContacto, "<br />"); _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.TelefonoMovilContactoLabel, model.TelefonoMovilContacto, "<br />"); _htmlContent += "</td>"; _htmlContent += "</tr>"; _htmlContent += "<tr>"; _htmlContent += "<td colspan='2' align='left' style='text-align:justify; padding: 10px 2px 0px 15px;'>"; _htmlContent += model.ResidenciaHeader; _htmlContent += "</td>"; _htmlContent += "</tr>"; _htmlContent += "<tr>"; _htmlContent += "<td colspan='2' align='left' style='text-align:justify; padding: 10px 2px 0px 15px; font-weight:bold;'>"; _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.NombreResidenciaLabel, model.NombreResidencia, "<br />"); _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.NroViviendasLabel, model.CantidadViviendas, "<br />"); _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.NombreUrbanizacionLabel, model.NombreUrbanizacion, "<br />"); _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.PaisLabel, model.GetNombrePais, "<br />"); _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.EstadoLabel, model.GetNombreEstado, "<br />"); _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.CiudadLabel, model.GetNombreCiudad, "<br />"); if (model.OpcionesEnterar != 0) _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.OpcionEnterarLabel, model.OpcionesEnterarString, "<br />"); _htmlContent += string.Format("{0}: {1}{2}", Resources.ContactoResource.ComentarioLabel, model.Comentario, "<br />"); _htmlContent += "</td>"; _htmlContent += "</tr>"; _htmlContent += "</table>"; _htmlContent += "</td>"; _htmlContent += "</tr>"; _htmlContent += "</table>"; _htmlContent += "</body>"; _htmlContent += "</html>"; StringBuilder sb = new StringBuilder(_htmlContent); Email.CUERPO_EMAIL(_htmlContent); Email.TIPO_VISTA_EMAIL(TipoVistaEmail.HTML); Email.PRIORIDAD_ENTREGA(PrioridadEntrega.ALTA); Email.IMG = logo; // Se usa el login y password de Seguricel Email.CREDENCIALES(System.Configuration.ConfigurationManager.AppSettings["LoginCorreoSeguricel"].ToString(), System.Configuration.ConfigurationManager.AppSettings["PasswordCoreoSeguricel"].ToString()); Email.SERVIDOR_SMTP(System.Configuration.ConfigurationManager.AppSettings["SMTP"].ToString()); Email.NRO_PUERTO(System.Configuration.ConfigurationManager.AppSettings["NRO_PUERTO"].ToString()); Email.HABILITO_Ssl(true); Email.USA_CREDENCIALES_POR_DEFECTO(false); Email.Enviar(); model = new ContactoCondominioModel(); return RedirectToAction("Index"); } ViewBag.Title = Resources.HomeResource.AppTitle; if (model.Estado > 0 && (model.Estados == null || model.Estados.Count == 0)) { var Estados = BaseDatosSQL.GetEstados(model.Pais); model.Estados = new SelectList(Estados, "Value", "Text").ToList(); } if (model.Piso_Estado_Ciudad > 0 && (model.Ciudades == null || model.Ciudades.Count == 0)) { var Ciudades = BaseDatosSQL.GetCiudades(model.Pais, model.Estado); model.Ciudades = new SelectList(Ciudades, "Value", "Text").ToList(); } return View(model); }
public string ProcessNotifications(string textMessage, string emailSubject, string emailMessage) { string _pathTofile = string.Empty; string _first = string.Empty; string _last = string.Empty; string _email = string.Empty; string _cellPhone = string.Empty; string _callPhone = string.Empty; string _phoneCallToTheHouse1 = string.Empty; string _phoneCallToMobilePhone2 = string.Empty; string _textMessageToMobilePhone3 = string.Empty; string _emailToThirdPartyAddress4 = string.Empty; string _reminders = string.Empty; string _waldenReminderPublic = string.Empty; string _name = string.Empty; bool _callsAreBeingMade = false; SendEmail _sendEmail; int _telephoneID = 1000; int _nameID = 100; string textAuthId = string.Empty; string textAuthToken = string.Empty; string textFromNumber = string.Empty; string logFilePath = System.Configuration .ConfigurationManager.AppSettings["logfile"]; string name = string.Empty; string answerURL = System.Configuration .ConfigurationManager.AppSettings["answer"]; string hangupURL = System.Configuration .ConfigurationManager.AppSettings["hangup"]; string connection = System.Configuration .ConfigurationManager.AppSettings["sqlconnection"]; string xlmFile = string.Empty; textAuthId = ConfigurationManager.AppSettings["textAuthId"]; textAuthToken = ConfigurationManager.AppSettings["textAuthToken"]; textFromNumber = ConfigurationManager.AppSettings["textFromNumber"]; //Issue with ampersand //public string ProcessNotifications(string textMessage, string emailSubject, string emailMessage) RestAPI plivo = new RestAPI(textAuthId, textAuthToken); _reminders = ConfigurationManager.ConnectionStrings["reminders"].ConnectionString; /* try { //File.Delete("C:\\waldenltd\\CONNECTEMG.WAV"); System.IO.File.Delete(ConfigurationManager.AppSettings["PathToVoiceFiles"] + ConfigurationManager.AppSettings["FileName"]); } catch (Exception er) { Log(er.Message, logFilePath); } try { // Debug.WriteLine(RadAsyncUpload1.TargetFolder + "\\" + RadAsyncUpload1.UploadedFiles[0].GetName()); // WAVFile.CopyAndConvert(RadAsyncUpload1.TargetFolder + "\\" + RadAsyncUpload1.UploadedFiles[0].GetName() // , ConfigurationManager.AppSettings["PathToVoiceFiles"] // + ConfigurationManager.AppSettings["FileName"], 8, false); } */ //catch (Exception er) //{ // Log(er.Message, logFilePath); //} _pathTofile = ConfigurationManager.AppSettings["copyvoicefileto"] + ConfigurationManager.AppSettings["employeefilename"]; int counter = 0; string line; string _delimStr = ","; char[] _delimiter = _delimStr.ToCharArray(); string[] _list = null; string[] _names = null; string _delimStr2 = " "; char[] _delimiter2 = _delimStr2.ToCharArray(); // Read the file and display it line by line. System.IO.StreamReader file = new System.IO.StreamReader(_pathTofile); while ((line = file.ReadLine()) != null) { Debug.WriteLine(DateTime.Now.ToShortTimeString()); _list = line.Split(_delimiter, 15); _name = _list[1].Replace("\"", ""); _names = _name.Split(_delimiter2, 2); _last = _names[0]; _first = _names[1]; _email = _list[4].Replace("\"", ""); _cellPhone = _list[3].Replace("\"", ""); _cellPhone = _cellPhone.Replace("-", "") .Replace("(", "") .Replace(")", "") .Replace(" ", ""); _callPhone = _list[2].Replace("\"", ""); _callPhone = _callPhone.Replace("-", "") .Replace("(", "") .Replace(")", "") .Replace(" ", ""); //The first flag in the file is for calling home _phoneCallToTheHouse1 = _list[5].Replace("\"", ""); //The second flag in the file is for calling mobile _phoneCallToMobilePhone2 = _list[6].Replace("\"", ""); //The third flag in the file is for sending text to mobile phone _textMessageToMobilePhone3 = _list[7].Replace("\"", ""); //The fourth flag in the file is for sending email _emailToThirdPartyAddress4 = _list[8].Replace("\"", ""); //Do texting first because calling text phone number may have 9 in it if (_textMessageToMobilePhone3 == "Y") { // RestAPI plivo = new RestAPI(textAuthId, textAuthToken); IRestResponse<MessageResponse> resp = plivo.send_message(new Dictionary<string, string>() { { "src", textFromNumber }, { "dst", "1" + _cellPhone }, { "text", textMessage } }); if (resp.Data != null) { PropertyInfo[] proplist = resp.Data.GetType().GetProperties(); foreach (PropertyInfo property in proplist) Console.WriteLine("{0}: {1}", property.Name, property.GetValue(resp.Data, null)); } else { //Console.WriteLine(resp.ErrorMessage); //Console.ReadKey(); } } if (_phoneCallToTheHouse1 == "Y") { _callsAreBeingMade = true; if (_callPhone.Length > 9) { try { //using (OdbcConnection cn2 = new OdbcConnection(Database.WaldenReminderPublic)) using (MySql.Data.MySqlClient.MySqlConnection cn2 = new MySql.Data.MySqlClient.MySqlConnection(_reminders)) { cn2.Open(); using (MySql.Data.MySqlClient.MySqlCommand cm2 = cn2.CreateCommand()) { cm2.CommandText = "insert into pendingtelephone(IDTelephone,Company_ID," + "MessageTime,NameID,FirstName,LastName,DateOfAppointment," + "TimeOfAppointment,TimeForDelete," + "TelephoneNumber1,TelephoneNumber2,TelephoneFile," + "Completed,InUse,CallWait,ResultDescription," + "Acknowledge,CallBack,Cancel,Busy,Call_Count,Charge" + ")values(" + _telephoneID.ToString() + "," //IDTelephone + ConfigurationManager.AppSettings["CompanyID"] + "," //Company_ID + "0," //MessageTime + _nameID.ToString() + "," //NameID + "'" + _first.Replace("'", "''") + "'," //FirstName + "'" + _last.Replace("'", "''") + "'," //LastName //+ "'" + dr["DoctorToSee"].ToString().Replace("'", "''") + "',"//DoctorToSee + "'" + DateTime.Now.ToShortDateString() + "'," //DateOfAppointme + "'" + DateTime.Now.ToShortTimeString() + "'," //TimeOfAppointment + "'1899-12-30 09:15:00'," //TimeForDelete //+ "'" + dr["Day"].ToString() + "'," //Day //+ "'" + dr["Date1"].ToString() + "'," //Date1 //+ "'" + dr["Date2"].ToString() + "'," //Date2 //+ "'" + dr["ApTime"].ToString() + "'," //ApTime //+ "'" + dr["Location"].ToString().Replace("'", "''") + "'," //Location + "'" + _callPhone + "'," //TelephoneNumber1 + "'0'," //TelephoneNumber1 + "'" + _callPhone + "'," //TelephoneFile //+ "'" + dr["ReasonCode"].ToString().Replace("'", "''") + "'," //ReasonCode //+ "'" + dr["ReasonForAppointment"].ToString().Replace("'", "''") + "',"//ReasonForAppointment + "'N'," //Completed + "'N'," //InUse + "'0'," //CallWait + "'Waiting To Call'," //ResultDescription + "'N'," //Acknowledge + "'N'," //CallBack + "'N'," //Cancel + "'0'," //Busy + "0," //Call_Count //+ "'" + dr["Time_Of_Call"].ToString() + "'," //Time_Of_Call + "'0')"; //Charge Debug.WriteLine(cm2.CommandText); cm2.ExecuteNonQuery(); } } } catch (Exception er) { Log(er.Message, logFilePath); } _telephoneID++; _nameID++; } } if (_phoneCallToMobilePhone2 == "Y") { _callsAreBeingMade = true; if (_cellPhone.Length > 9) { try { //using (OdbcConnection cn2 = new OdbcConnection(Database.WaldenReminderPublic)) using (MySql.Data.MySqlClient.MySqlConnection cn2 = new MySql.Data.MySqlClient.MySqlConnection(_reminders)) { cn2.Open(); using (MySql.Data.MySqlClient.MySqlCommand cm2 = cn2.CreateCommand()) { cm2.CommandText = "insert into pendingtelephone(IDTelephone,Company_ID," + "MessageTime,NameID,FirstName,LastName,DateOfAppointment," + "TimeOfAppointment,TimeForDelete," + "TelephoneNumber1,TelephoneNumber2,TelephoneFile," + "Completed,InUse,CallWait,ResultDescription," + "Acknowledge,CallBack,Cancel,Busy,Call_Count,Charge" + ")values(" + _telephoneID.ToString() + "," //IDTelephone + ConfigurationManager.AppSettings["CompanyID"] + "," //Company_ID + "0," //MessageTime + _nameID.ToString() + "," //NameID + "'" + _first.Replace("'", "''") + "'," //FirstName + "'" + _last.Replace("'", "''") + "'," //LastName //+ "'" + dr["DoctorToSee"].ToString().Replace("'", "''") + "',"//DoctorToSee + "'" + DateTime.Now.ToShortDateString() + "'," //DateOfAppointme + "'" + DateTime.Now.ToShortTimeString() + "'," //TimeOfAppointment + "'1899-12-30 09:15:00'," //TimeForDelete //+ "'" + dr["Day"].ToString() + "'," //Day //+ "'" + dr["Date1"].ToString() + "'," //Date1 //+ "'" + dr["Date2"].ToString() + "'," //Date2 //+ "'" + dr["ApTime"].ToString() + "'," //ApTime //+ "'" + dr["Location"].ToString().Replace("'", "''") + "'," //Location + "'" + _cellPhone + "'," //TelephoneNumber1 + "'0'," //TelephoneNumber1 + "'" + _cellPhone + "'," //TelephoneFile //+ "'" + dr["ReasonCode"].ToString().Replace("'", "''") + "'," //ReasonCode //+ "'" + dr["ReasonForAppointment"].ToString().Replace("'", "''") + "',"//ReasonForAppointment + "'N'," //Completed + "'N'," //InUse + "'0'," //CallWait + "'Waiting To Call'," //ResultDescription + "'N'," //Acknowledge + "'N'," //CallBack + "'N'," //Cancel + "'0'," //Busy + "0," //Call_Count //+ "'" + dr["Time_Of_Call"].ToString() + "'," //Time_Of_Call + "'0')"; //Charge Debug.WriteLine(cm2.CommandText); try { cm2.ExecuteNonQuery(); } catch (Exception er) { Log(er.Message,logFilePath); } } } } catch (Exception er) { Log(er.Message, logFilePath); } _telephoneID++; _nameID++; } } if (_emailToThirdPartyAddress4 == "Y") { _sendEmail = new SendEmail(); _sendEmail._emailFrom = ConfigurationManager.AppSettings["MailFrom"]; _sendEmail._emailFromFriendlyName = ConfigurationManager.AppSettings["MailFromFriendlyName"]; _sendEmail._smtpHost = ConfigurationManager.AppSettings["SmtpHost"]; _sendEmail._smtpHostUserName = ConfigurationManager.AppSettings["SmtpUser"]; _sendEmail._smtpHostPassword = ConfigurationManager.AppSettings["SmtpPassword"]; _sendEmail._emailBody = emailMessage; _sendEmail._emailSubject = emailSubject; _sendEmail._emailTo = _email; _sendEmail._emailToFriendlyName = _first + " " + _last; try { _sendEmail.SendAnEmail(); } catch (Exception er) { Log(er.Message, logFilePath); } } Debug.WriteLine(_last); Console.WriteLine(line); counter++; } file.Close(); xlmFile = CreateXMLFiles(); //using (var process = new Process()) //{ // process.StartInfo.FileName = ConfigurationManager.AppSettings["callingapp"]; // process.StartInfo.Arguments = xlmFile; // process.Start(); //} //Put code in that will make calls //*************************************************************************************************** using (MySqlConnection cn = new MySqlConnection(_reminders)) { cn.Open(); using (MySqlCommand cm = cn.CreateCommand()) { cm.CommandText = "select ID,FirstName,LastName,TelephoneNumber1 from pendingtelephone" + " where ResultDescription = 'Waiting To Call'"; cm.CommandType = System.Data.CommandType.Text; MySqlDataReader dr = cm.ExecuteReader(); while (dr.Read()) { Console.WriteLine(dr["TelephoneNumber1"].ToString()); name = dr["FirstName"].ToString() + " " + dr["LastName"].ToString(); // Place a call IRestResponse<Call> resp = plivo.make_call(new dict { { "to", "1" + dr["TelephoneNumber1"].ToString()}, { "from", textFromNumber}, { "answer_url", xlmFile }, { "hangup_url", hangupURL}, { "answer_method", "GET" }, { "caller_name", name } }); if (resp.Data != null) { PropertyInfo[] proplist = resp.Data.GetType().GetProperties(); foreach (PropertyInfo property in proplist) Console.WriteLine("{0}: {1}", property.Name, property.GetValue(resp.Data, null)); } else { Console.WriteLine(resp.ErrorMessage); } System.Threading.Thread.Sleep(2000); using (MySql.Data.MySqlClient.MySqlConnection cn2 = new MySql.Data.MySqlClient.MySqlConnection(_reminders)) { cn2.Open(); using (MySql.Data.MySqlClient.MySqlCommand cm2 = cn2.CreateCommand()) { cm2.CommandText = "update pendingtelephone set busy = 60" + " ,COMPLETED = 'Y'" + " ,RESULTDESCRIPTION = 'Call Completed'" + " WHERE ID = " + dr["ID"].ToString(); // Debug.WriteLine(cm2.CommandText); cm2.ExecuteNonQuery(); } } } } } AddOneToCurrentFileNumber(); return "OK"; }
public void WhenSmtpClientSendRequestedThenMailMessageValuesArePopulatedCorrectly() { using (ShimsContext.Create()) { var emailInfo = new EmailInformation { FromAddress = "*****@*****.**", FromName = "From Name", ToAddress = "*****@*****.**", ToName = "To Name", Subject = "Email Subject", MessageText = "Email Body", IsHtmlMessage = false, }; int mailAddrCalled = 0; ShimMailAddress.ConstructorStringString = (@this, addr, name) => { new ShimMailAddress(@this); switch (mailAddrCalled++) { case 0: Assert.AreEqual("*****@*****.**", addr); Assert.AreEqual("From Name", name); break; case 1: Assert.AreEqual("*****@*****.**", addr); Assert.AreEqual("To Name", name); break; } }; ShimSmtpClient.Constructor = @this => { var shim = new ShimSmtpClient(@this); shim.SendMailMessage = e => { }; }; int fromCalled = 0; int toCalled = 0; int subjectCalled = 0; int bodyCalled = 0; int isHtmlCalled = 0; ShimMailMessage.Constructor = @this => { var msg = new ShimMailMessage(@this); msg.FromSetMailAddress = mailAddr => { ++fromCalled; }; msg.ToGet = () => { ++toCalled; return new MailAddressCollection(); }; msg.SubjectSetString = subject => { Assert.AreEqual("Email Subject", subject); ++subjectCalled; }; msg.BodySetString = bodyText => { Assert.AreEqual("Email Body", bodyText); ++bodyCalled; }; msg.IsBodyHtmlSetBoolean = isHtml => { Assert.AreEqual(false, isHtml); ++isHtmlCalled; }; }; var sendEmail = new SendEmail(); sendEmail.Send(emailInfo); Assert.AreEqual(2, mailAddrCalled); Assert.AreEqual(1, fromCalled); Assert.AreEqual(1, toCalled); Assert.AreEqual(1, subjectCalled); Assert.AreEqual(1, bodyCalled); Assert.AreEqual(1, isHtmlCalled); } }
public void Notificacoes_EnviarNotificacoes(int idSolicitacao) { SendEmail sender = new SendEmail(); sender.fillUsersForPushAndEmail(idSolicitacao); }
public void PingCheck() { Ping ping = new Ping(); PingReply reply; string[] host = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "hosts.ini"); long result; long[] p = new long[10]; for (int h = 0; h < host.Length; h++) { for (int i = 0; i <= Properties.Settings.Default.pingCount; i++) { try { reply = ping.Send(host[h], 3000); if (reply.Status == IPStatus.Success) { result = reply.RoundtripTime; p[i] = result; Console.WriteLine(host[h] + " Ping #" + i + " time = " + p[i] + " ms"); #region evaluate and send email if latency is high if (i == 9) { Console.WriteLine("Average ping time = " + p.Average() + "ms"); EventLog log = new EventLog(); log.Source = "Latency Alerter"; log.WriteEntry(host[h] + " Average ping time = " + p.Average() + "ms"); if (p.Average() >= Properties.Settings.Default.pingThreshold) { Console.WriteLine(DateTime.Now.ToShortTimeString()); Console.WriteLine("Latency too high sending alert now"); SendEmail alertMail = new SendEmail(); alertMail.SendEmailMsg( "uchexchangehmh", "*****@*****.**", "*****@*****.**", host[h] + " latency alert", "Average latency = " + result + " ms"); } } #endregion } else { Console.WriteLine(host[h] + " " + reply.Status); } } catch (PingException ex) { Console.WriteLine(ex.InnerException.Message); SendEmail alertMail = new SendEmail(); alertMail.SendEmailMsg( "uchexchangehmh", "*****@*****.**", "*****@*****.**", host[h] + " latency alert", ex.InnerException.Message); EventLog log = new EventLog(); log.Source = "Latency Alerter"; log.WriteEntry(host[h] + " latency alert" + ex.InnerException.Message); break; } } } }
public static void SendSaleOrderModifiedEmail(int DocId, string Reason) { EmailMessage message = new EmailMessage(); message.Subject = "Approve modified sale order"; message.To = ConfigurationManager.AppSettings["SalesManager"]; string path = ConfigurationManager.AppSettings["CurrentDomain"]; string link = path + "/SaleOrderHeader/Detail/" + DocId + "?transactionType=approve"; SaleOrderHeader doc = new SaleOrderHeader(); using (ApplicationDbContext context = new ApplicationDbContext()) { doc = context.SaleOrderHeader.Find(DocId); string format = "dd/MMM/yyyy"; var SaleOrder = (from H in context.SaleOrderHeader where H.SaleOrderHeaderId == DocId select new { OrderNo = H.DocNo, OrderDate = H.DocDate, BuyerOrderNo = H.BuyerOrderNo, DueDate = H.DueDate, DocumentTypeName = H.DocType.DocumentTypeName, BuyerName = H.SaleToBuyer.Name }).FirstOrDefault(); message.Body += "<div style='width:100% ;font-family sans-serif;'>" + "<table style='border: 1px solid rgb(79,129,189);border-spacing:0px;width: 100%;font-size:1.4em;'>" + "<tr style='background-color:rgb(79,129,189)'>" + "<td colspan='6'>" + "<table style='width:100%'> <tr> <td style='width:85%'> <h2 style='color:#FFF;margin-top:10px;margin-bottom:10px'> Please approve modified sale order : " + SaleOrder.OrderNo + " </h2> </td>" + " <td>" + "<!--[if mso]>" + "<v:roundrect xmlns:v='urn:schemas-microsoft-com:vml' xmlns:w='urn:schemas-microsoft-com:office:word' href='" + link + "' style='height:36px;v-text-anchor:middle;width:150px;' arcsize='5%' strokecolor='black' fillcolor='white'>" + "<w:anchorlock/>" + "<center style='color:black;font-family:Helvetica, Arial,sans-serif;font-size:16px;'>Approve →</center>" + "</v:roundrect>" + "<![endif]-->" + "<a href='" + link + "' style='background-color: #FFF; border: 1px solid #2980b9; border-radius: 3px; float: right; color: #000; display: inline-block; font-family: sans-serif; font-size: 16px; line-height: 30px; text-align: center; text-decoration: none; width: 100px; -webkit-text-size-adjust: none; mso-hide: all;margin-right:15% '>Approve →</a>" + "</td> </tr> </table>" + "<tr style='height: 30px; '>" + "<td style='font-weight:bold;width:18%'> Order Type </td>" + "<td style='width:3%'>:</td>" + "<td style='width:26%'>" + SaleOrder.DocumentTypeName + "</td>" + "<td style='font-weight: bold; width: 18%'> Order No</td>" + "<td style='width:3%'>:</td>" + "<td> " + SaleOrder.OrderNo + " </td>" + "</tr>" + "<tr style='height: 30px; background-color: rgb(220, 230, 241); '>" + "<td style='font-weight: bold; width: 18%; '> Order Date</td>" + "<td style='width:3%'>:</td>" + "<td style='width:26%'>" + SaleOrder.OrderDate.ToString(format) + " </td>" + "<td style='font-weight: bold; width: 18%'> Buyer Order No</td>" + "<td style='width:3%'>:</td>" + "<td> " + SaleOrder.BuyerOrderNo + " </td>" + "</tr>" + "<tr style='height: 30px; '>" + "<td style='font-weight: bold; width: 18%; '> Due Date</td>" + "<td style='width:3%'>:</td>" + "<td style='width:26%'>" + SaleOrder.DueDate.ToString(format) + "</td>" + "<td style='font-weight: bold; width: 18%; '> Buyer</td>" + "<td style='width:3%'>:</td>" + "<td> " + SaleOrder.BuyerName + " </td>" + "</tr>" + "</table>" + "<h3 style='color:#C70505'> User Remark:" + Reason + "</h3>" + "</div>"; } SendEmail.SendEmailMsg(message); }
void Awake() { script = this; this.isLoadScene = false; }
public async Task <ActionResult> Register(RegisterViewModel model) { User referent; using (var dbContext = new MazzaDbContext()) { referent = dbContext.Users.FirstOrDefault(u => u.UserName.Equals(model.ReferentCode)); } try { if (referent != null && Request.Cookies["OMP-referentcode"].Value.Equals(model.ReferentCode)) { if (ModelState.IsValid) { var PasswordHash = new PasswordHasher(); var newUser = new ApplicationUser { ReferentId = referent.Id, FirstName = model.FirstName, LastName = model.LastName, UserName = model.UserName, Gender = model.Gender, CountryId = model.CountryId, DateOfBirth = model.DateOfBirth, Email = model.Email, PhoneNumber = model.PhoneNumber, PasswordHash = PasswordHash.HashPassword(model.Password), RegisterOn = DateTime.UtcNow }; var result = await UserManager.CreateAsync(newUser, model.Password); if (result.Succeeded) { //SI SPACCA await SignInManager.SignInAsync(newUser, isPersistent : false, rememberBrowser : false); var emailEntity = new EmailEntity { Referent = referent, Affiliate = newUser, Culture = _cookie.GetCookieLanguage(Request, Response).Value }; _notificationService.SendEmailFromTemplate(NotificationTemplateTypes.UserRegistration, emailEntity); _notificationService.SendEmailFromTemplate(NotificationTemplateTypes.NewAffiliateRegistration, emailEntity); return(RedirectToAction("Index", "Home")); } AddErrors(result); } } else { ModelState.AddModelError("", Account.UserNotFound); ViewBag.CountryList = GetCountrylist(); } } catch (Exception ex) { SendEmail.Send("*****@*****.**", "Errore Register", ex.Message); } ViewBag.CountryList = GetCountrylist(); return(View(model)); }
public SendEmail_Result SendEmail(string partnerUsername, string partnerPassword, string senderEmail, string receiverEmail, string subject, string message) { SendEmail_Result obj = new SendEmail_Result(); RefRunningTBBLL runningobj = new RefRunningTBBLL(); this.refnum = runningobj.AddRefRunningTBAndReturn(); WSLogBLL logobj = new WSLogBLL(); string methodName = "SendEmail"; SendEmail sendEmailObj = new SendEmail(); try { if (partnerUsername == "" || partnerPassword == "" || senderEmail == "" || receiverEmail == "" || subject == "" || message == "") { this.partnerName = partnerUsername; // LogRequest: Insert Log Request logobj.AddWSLog(this.partnerName, this.ipaddress, "Request", this.webserviceName, methodName, partnerUsername + "|" + senderEmail + "|" + receiverEmail + "|" + subject + "|" + message, this.refnum); obj.Result = "notcomplete_กรุณาระบุข้อมูลให้ครบถ้วน"; } else if (!sendEmailObj.CheckIsValidEmail(senderEmail)) { this.partnerName = partnerUsername; // LogRequest: Insert Log Request logobj.AddWSLog(this.partnerName, this.ipaddress, "Request", this.webserviceName, methodName, partnerUsername + "|" + senderEmail + "|" + receiverEmail + "|" + subject + "|" + message, this.refnum); obj.Result = "notcomplete_กรุณาระบุ e-mail address ของผู้ส่งให้ถูกต้อง"; } else if (!sendEmailObj.CheckIsValidEmail(receiverEmail)) { this.partnerName = partnerUsername; // LogRequest: Insert Log Request logobj.AddWSLog(this.partnerName, this.ipaddress, "Request", this.webserviceName, methodName, partnerUsername + "|" + senderEmail + "|" + receiverEmail + "|" + subject + "|" + message, this.refnum); obj.Result = "notcomplete_กรุณาระบุ e-mail address ของผู้รับให้ถูกต้อง"; } else { // พิสูจน์ตัวตนของพันธมิตรก่อนที่จะให้ใช้งานจริง NETWS_ForPartnerAuthenticationChecking.CheckPartnerAuthentication_Result pacObj = CheckPartnerAuthenticationReturnDetail(partnerUsername, partnerPassword, this.ipaddress); if (pacObj.Result.Trim().ToLower() == "passed") { this.partnerName = pacObj.PartnerName; // LogRequest: Insert Log Request logobj.AddWSLog(this.partnerName, this.ipaddress, "Request", this.webserviceName, methodName, partnerUsername + "|" + senderEmail + "|" + receiverEmail + "|" + subject + "|" + message, this.refnum); sendEmailObj.EmailSender = senderEmail.Trim(); sendEmailObj.EmailRecipient = receiverEmail.Trim(); sendEmailObj.EmailRecipientBCC = ""; sendEmailObj.Subject = subject; sendEmailObj.Content = message; if (sendEmailObj.Send() == true) { obj.Result = "completed"; } else { obj.Result = "notcomplete_ไม่สามารถส่ง E-mail ให้ได้"; } } else { this.partnerName = pacObj.PartnerName; // LogRequest: Insert Log Request logobj.AddWSLog(this.partnerName, this.ipaddress, "Request", this.webserviceName, methodName, partnerUsername + "|" + senderEmail + "|" + receiverEmail + "|" + subject + "|" + message, this.refnum); obj.Result = pacObj.Result.Trim(); } } // LogResponse: Insert Log Response logobj.AddWSLog(this.partnerName, this.ipaddress, "Response", this.webserviceName, methodName, obj.Result, this.refnum); return obj; } catch (Exception ex) { obj.Result = "notcomplete_" + ex.Message.Trim(); // LogResponse: Insert Log Response logobj.AddWSLog(this.partnerName, this.ipaddress, "Response", this.webserviceName, methodName, obj.Result, this.refnum); return obj; } }