public int SendPassword(string sUsername, string sAppPath) { var ds = Dal.GetUserByUsername(sUsername); if (ds == null || ds.Tables[0].Rows.Count == 0 || ds.Tables[0].Rows[0]["Password"] == DBNull.Value) { return(0); } else { var password = ds.Tables[0].Rows[0]["Password"].ToString(); var file_name = sAppPath + Settings.Default.ForgotPswdFile; var str_subject = Utility.GetFileText(file_name, "SUBJECT"); var str_body = Utility.GetFileText(file_name, "BODY"); str_body = str_body.Replace("[p_pswd]", password); var to = new string[1]; to[0] = sUsername + "@gsa.gov"; var email = new EmailUtility(); email.Subject = str_subject; email.MessageBody = str_body; email.To = to; email.SendEmail(); return(1); } }
/// <summary> /// /// </summary> /// <param name="FIRST_NAME"></param> /// <param name="LAST_NAME"></param> /// <param name="EMAIL"></param> /// <param name="PHONE"></param> /// <param name="TRIP_REQUEST"></param> /// <returns></returns> public static async Task <DomingoBlError> CreateCrmLeadExternal(string FIRST_NAME, string LAST_NAME, string EMAIL, string PHONE, string TRIP_REQUEST) { try { // send a mail to the customer var emailUtility = new EmailUtility(); var emailParams = new Dictionary <String, String>(); emailParams.Add("UserName", FIRST_NAME); await emailUtility.SendEmail("ContactUs", EMAIL, emailParams); // create a lead in the capsule CRM var gateway = new CapsupleCrmGateway(); var crmResponse = await gateway.CreateCapsuleLead(FIRST_NAME, LAST_NAME, EMAIL, PHONE, TRIP_REQUEST); return(new DomingoBlError() { ErrorCode = 0, ErrorMessage = "" }); } catch (Exception ex) { return(new DomingoBlError() { ErrorCode = 100, ErrorMessage = ex.Message }); } }
private string SendMail(string emailid, string mailsubject, string mailcontent) { string Response = string.Empty; if (!string.IsNullOrEmpty(emailid)) { ArrayList alistEmailAddress = new ArrayList(); alistEmailAddress.Add(emailid); if (alistEmailAddress.Count > 0) { bool IsSendSuccess = EmailUtility.SendEmail(alistEmailAddress, mailsubject, mailcontent); if (IsSendSuccess) { Response = "Send email successfully."; } else { Response = "Send email failed."; } } } else { Response = "Send email failed.[Email address is empty]"; } return(Response); }
public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Don't reveal that the user does not exist or is not confirmed return(View("ForgotPasswordConfirmation")); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // send mail var emailUtility = new EmailUtility(); var emailParams = new Dictionary <String, String>(); emailParams.Add("UserName", model.Email); emailParams.Add("ResetPasswordLink", callbackUrl); await emailUtility.SendEmail("ResetPasswordEmail", model.Email, emailParams); // await DomingoUserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("ForgotPasswordConfirmation", "Account")); } // If we got this far, something failed, redisplay form return(View(model)); }
private void PrepareEmail(List <TaskDTO> emaillist) { try { foreach (var item in emaillist) { if (item.ToEmail != string.Empty) { string status = StringUtility.StatusAlive; if (item.PreviousState == (int)TaskStatusEnum.Dead) { status = StringUtility.StatusDead; } string subject = string.Format(StringUtility.EmailSubject, item.Entity, status, DateTime.UtcNow.ToString()); Task.Run(() => { EmailUtility.SendEmail(item.ToEmail, subject, StringUtility.EmailBody, _configuration); }); } } } catch (Exception ex) { _logger.LogError(ex.Message + ex.StackTrace); } }
public async Task <ActionResult> GenerateVerifyCode() { string code = await UserManager.GenerateEmailConfirmationTokenAsync(User.Identity.GetUserId()); var _regViewModel = new RegisterViewModel() { Email = User.Identity.GetUserName() }; var user = UserManager.FindByEmail(_regViewModel.Email); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); var emailUtility = new EmailUtility(); var emailParams = new Dictionary <String, String>(); emailParams.Add("UserName", _regViewModel.Email); emailParams.Add("ActivationLink", callbackUrl); await emailUtility.SendEmail("VerifiyEmail2", _regViewModel.Email, emailParams); var model = new VerifyEmailViewModel() { Mode = "codegenerated" }; return(View("Verify", model)); }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { // Attempt to register the user try { var validationGuid = Guid.NewGuid(); WebSecurity.CreateUserAndAccount( model.UserName, model.Password, new { DisplayName = model.DisplayName, ValidationToken = validationGuid, IsValid = false }); EmailUtility.SendEmail( model.UserName, model.DisplayName, "Thank you for signing up for BookSpade!", string.Format("Confirm your registration by clicking <a href=\"http://localhost:26793/Account/validate/{0}\" > here </a>", validationGuid) ); return(View("ValidateRequest")); } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } } // If we got this far, something failed, redisplay form return(View(model)); }
protected void btnSendInteraction_click(object sender, EventArgs e) { foreach (ListViewItem item in lvstudent.Items) { string InteractionDate = string.Empty; string InteractionTime = string.Empty; string AdmissionID = string.Empty; string MailFrom = string.Empty; string MailTo = string.Empty; string MailSubject = string.Empty; string MailBody = string.Empty; string FailiurReason = string.Empty; ArrayList ArrMailTo = new ArrayList(); HtmlInputCheckBox interactioncheck = (HtmlInputCheckBox)item.FindControl("interactioncheck"); if (interactioncheck.Checked) { TextBox interactiondate = (TextBox)item.FindControl("interactiondate"); InteractionDate = interactiondate.Text; TextBox interactiontime = (TextBox)item.FindControl("interactiontime"); InteractionTime = interactiontime.Text; Label communicationemail = (Label)item.FindControl("communicationemail"); HiddenField hdnAdmissionID = (HiddenField)item.FindControl("hdnAdmissionID"); AdmissionID = hdnAdmissionID.Value; MailFrom = EmailUtility.SMTPEmailAddress; MailTo = communicationemail.Text; MailSubject = GetMailSubject(); MailBody = GetMailBody(InteractionDate, InteractionTime); if (!string.IsNullOrEmpty(InteractionDate) && !string.IsNullOrEmpty(InteractionTime) && !string.IsNullOrEmpty(MailTo) && !string.IsNullOrEmpty(AdmissionID)) { ArrMailTo.Add(MailTo); bool IsSendSuccess = EmailUtility.SendEmail(ArrMailTo, MailSubject, MailBody, out FailiurReason); BAL_Admission oBAL_Admission = new BAL_Admission(); AdmissionInteraction oAdmissionInteraction = new AdmissionInteraction(); oAdmissionInteraction.AdmissionId = AdmissionID; oAdmissionInteraction.InteractionDate = InteractionDate; oAdmissionInteraction.InteractionTime = InteractionTime; oAdmissionInteraction.MailFrom = MailFrom; oAdmissionInteraction.MailTo = MailTo; oAdmissionInteraction.MailSubject = MailSubject; oAdmissionInteraction.MailBody = MailBody; oAdmissionInteraction.IsSendSuccess = IsSendSuccess; oAdmissionInteraction.FailureReasons = GetValue(FailiurReason); oAdmissionInteraction.CreatedBy = Convert.ToString(AppSessions.EmpolyeeID); oBAL_Admission.AdmissionInteraction_Insert(oAdmissionInteraction); } } } BindGrid(); mainpopup.Attributes["class"] = "overlayone"; msg.InnerHtml = "Your operation has been successfully completed."; }
public ActionResult TestEmail() { var to = new List <string>(); to.Add("*****@*****.**"); EmailUtility.SendEmail(this, "TEST NEW EMAIL SERVER3", to, "Hello World3"); new System.Threading.ManualResetEvent(false).WaitOne(500); return(View("All")); }
protected void BttnSubmit_Click(object sender, EventArgs e) { try { DataSet ds = new DataSet(); OEmployee = new Employee(); BAL_Forgetpassword = new Teacher_Dashboard_BLogic(); OEmployee.emailid = uctxtEmail.Text; ArrayList arrParameter = new ArrayList(); string subjectEmail = "Login Information"; arrParameter.Add(uctxtEmail.Text); ds = BAL_Forgetpassword.BAL_Emailid_Select(OEmployee); ViewState["PasswordData"] = ds; if (ds.Tables.Count > 0 & ds != null) { if (ds.Tables[0].Rows.Count > 0) { if (EmailUtility.SendEmail(arrParameter, subjectEmail, GenerateMailBodyForgetPassword())) { ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Password has been sent to your email successfully.');window.location ='Login.aspx';", true); ClearControls(); } else { WebMsg.Show("Email Failed"); ClearControls(); } } else if (ds.Tables[1].Rows.Count > 0) { if (EmailUtility.SendEmail(arrParameter, subjectEmail, GenerateEmailBody())) { ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Password has been sent to your email successfully.');window.location ='Login.aspx';", true); ClearControls(); } else { WebMsg.Show("Email Failed"); ClearControls(); } } else { WebMsg.Show("Invalid Email"); ClearControls(); } } else { WebMsg.Show("Invalid Email"); } } catch (Exception ex) { Response.Write(ex.Message); } }
public ActionResult AddComment(CommentIDs commentform) { try { MvcApplication.CraftsPrincipal user = (MvcApplication.CraftsPrincipal) base.HttpContext.User; if (base.ModelState.IsValid) { if (string.IsNullOrEmpty(commentform.myComment)) { return this.redirect("error=1"); } if (user.UserName == null) { return this.redirect("error"); } string safeHtmlFragment = Sanitizer.GetSafeHtmlFragment(commentform.myComment.Replace("\r\n", " ")); int commentCount = this._commentrepository.GetCommentCount(commentform.ComponentID); string data = this._commentrepository.AddComment(safeHtmlFragment, commentform.ComponentID, user.UserName, user.DISPLAYNAME); if (!data.Equals("0")) { try { IComponent componentInfo = this.GetComponentInfo(commentform.ComponentID); Models.CommentEmail model = new Models.CommentEmail { ComponentName = ((TridionItem) componentInfo).Title, ComponentID = commentform.ComponentID, User = user.UserName }; EmailUtility utility = new EmailUtility(); string toEmailAddress = ConfigurationManager.AppSettings["CommentModerationAdminEmail"]; string fromEmailAddress = ConfigurationManager.AppSettings["PasswordReminderEmailFrom"]; string emailTemplate = ConfigurationManager.AppSettings["CommentModerationAdminEmailTemplate"]; string str6 = utility.SendEmail(model, emailTemplate, fromEmailAddress, toEmailAddress); this.Logger.DebugFormat("CommnetsController : Comments received Email > result {0}", new object[] { str6 }); } catch (Exception) { this.Logger.Debug("Unable to send comments received Email to CountryAdmin."); } } if (base.Request.IsAjaxRequest()) { return base.Json(data, JsonRequestBehavior.AllowGet); } return this.redirect("commented"); } return this.redirect("error=1"); } catch (Exception exception2) { this.Logger.DebugFormat("CommentsController > AddComment exception {0}", new object[] { exception2.Message }); return this.redirect("error"); } }
/// <summary> /// M3 User mail sends /// </summary> /// <param name="userLogin"></param> /// <returns></returns> private bool SendLoginSuccessMail(string emailAddress, string userFullName) { Infra.EmailDTO emailDTO = new Infra.EmailDTO(); emailDTO.ToMail = emailAddress; emailDTO.MailSubject = Infra.BusinessConstants.MAIL_M3USER_SUBJECT; string navigationLink = string.Format(Infra.BusinessConstants.M3USER_REDIRECTION, Helper.GetConfigurationKey(BusinessConstants.SERVER_BASE_ADDRESS)); emailDTO.Body = string.Format(Infra.BusinessConstants.MAIL_M3USER_BODY, userFullName, navigationLink); emailDTO.IsBodyHtml = true; return(EmailUtility.SendEmail(emailDTO)); }
private async Task _SendWelcomeEmail(string firstName, string lastName, string email) { var emailUtility = new EmailUtility(); var emailParams = new Dictionary <String, String>(); emailParams.Add("FirstName", firstName); emailParams.Add("LastName", lastName); // create a task for sending the verification mail var blEmail = await emailUtility.SendEmail("WelcomeEmail", email, emailParams); }
public JsonResult sendEmailLogin(string email) { EmailUtility _emaUtility = new EmailUtility(_appSettings, _emailSettings); string emailBody = @"<p>Please login toIn-Service Compliance Application to start you test with following link</p> <br /> <p><a href='" + _appSettings.Value.WebBaseURL + "/Account/Login'>" + _appSettings.Value.WebBaseURL + "/Login</a></p>"; _emaUtility.SendEmail("", "Registration link for In-Service Compliance", emailBody, email.Split(",")); return(Json("Email sent successfully")); }
public static XmlDocument CreateXmlDocument() { var xmlDoc = new XmlDocument(); try { using (var sqlConnection = SqlDBUtil.GetConnection()) { sqlConnection.Open(); var sqlcmd = new SqlCommand("[maint].[__UpdateManagers]", sqlConnection); sqlcmd.CommandTimeout = 240; sqlcmd.CommandType = System.Data.CommandType.StoredProcedure; Logger.LogEvent(" Executing stored procedure..."); using (XmlReader reader = sqlcmd.ExecuteXmlReader()) { while (reader.Read()) { xmlDoc.Load(reader); } xmlDoc.Save(file); XmlDeclaration xmldecl; xmldecl = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); XmlElement root = xmlDoc.DocumentElement; xmlDoc.InsertBefore(xmldecl, root); Logger.LogEvent(" File created!"); Logger.Log.Append(DateUtility.getTime() + " Path: " + file + "\r\n"); } Logger.LogEvent(" Finished executing sp on server!"); Logger.WriteLogToFile(); } return(xmlDoc); } catch (SqlException sqlEx) { EmailUtility.SendEmail("ORMIS DB/SQL EXCEPTION: " + "\r\n" + sqlEx.Message, "Import Failed!"); Logger.LogException(sqlEx.Message); Logger.WriteLogToFile(); throw; } catch (Exception ex) { EmailUtility.SendEmail("Other ORMIS DB/SQL EXCEPTION while executing stored procedure: " + "\r\n" + ex.Message, "Import Failed!"); Logger.LogException(ex.Message); Logger.WriteLogToFile(); throw; } }
public bool SendEmail(CommonEmailVM commonEmailVM) { try { commonEmailVM.ApiKey = _config.GetSection("SEND_GRID_KEY").Value; var response = EmailUtility.SendEmail(commonEmailVM).Result; return(response.StatusCode == System.Net.HttpStatusCode.Accepted ? true : false); } catch (Exception ex) { throw ex; } }
public ActionResult <RequestResponse> PostLeaveApplication(LeaveApplications application) { var currentDate = DateTime.Now; application.CreatedOn = currentDate; application.ModifiedOn = currentDate; var result = _leaveApplicationsRepository.SaveLeaveApplication(application); if (result > 0) { if (!application.IsApproved) { //semd email notification for application to be approved var applicant = _employeeRepository.FindEmployeeById(application.EmpId); var supervisor = _employeeRepository.FindEmployeeById(application.SupervisorStaffId); TextInfo myTI = new CultureInfo("en-US", false).TextInfo; var message = @"Dear " + myTI.ToTitleCase(supervisor.FirstName.ToLower()) + ", \n\n" + myTI.ToTitleCase(applicant.FirstName.ToLower()) + " " + myTI.ToTitleCase(applicant.LastName.ToLower()) + " has applied for " + application.LeaveType.ToLower() + " leave for " + application.LeaveDays + " day(s), starting from " + application.FromDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) + " to " + application.ToDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) + ", with a return date of " + application.ReturnDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture) + "." + "\n\nKindly approve or reject the application by responding to this email to notify the HR Department. \n\nThanks,\nHuman Resource Department"; //Emu.SendEmail(supervisor.EmailId, "Leave Application", message, "*****@*****.**", applicant.EmailId); Emu.SendEmail(supervisor.EmailId, "Leave Application", message); } return(new RequestResponse { Status = "Success", Remarks = "Leave application added successfully" }); } return(new RequestResponse { Status = "Failure", Remarks = "Add new record failed" }); }
public void SendEmail_OnClick(Object sender, EventArgs e) { string name = HttpUtility.HtmlEncode(Name.Text); string email = HttpUtility.HtmlEncode(Email.Text); string message = HttpUtility.HtmlEncode(Message.Text); string body = ""; body += String.Format("Thank you for contacting us, {0}", name); body += "<p>Your Message: </p>"; body += String.Format("<p>{0}</p>", message); EmailUtility.SendEmail(email, "RoomMagnet Contact", body); }
public static void ImportManagers(XmlDocument xmlDoc) { try { Logger.LogEvent(" Checking if file exists"); string bat = ConfigurationManager.AppSettings["BAT"]; if (File.Exists(file)) { string contents = XmlUtil.BeautifyXml(xmlDoc); Logger.LogEvent(" File exists!"); Logger.LogEvent(" Starting import"); File.WriteAllText(file, contents, Encoding.UTF8); try { StringBuilder sbOut = new StringBuilder(); ExecuteImport(sbOut); } catch (Exception ex) { EmailUtility.SendEmail("Error executing Optial Data Import. " + "\r\n" + ex.Message, "Import Failed!"); Logger.LogEvent(" Error executing Optial Data Import: " + ex.Message); } if (File.Exists(bat)) { try { Logger.LogEvent(" Bat found! Starting bat execution"); Process.Start(bat); Logger.LogEvent(" Finished bat execution"); } catch (Exception ex) { Logger.LogEvent(" Error executing bat file: "); Logger.LogException(ex.Message); Logger.WriteLogToFile(); } } } Logger.Log.Append("**************** FINISHED MANAGER UPDATE ****************" + "\r\n" + "\r\n"); Logger.WriteLogToFile(); } catch (Exception e) { EmailUtility.SendEmail("Error executing import part: " + "\r\n" + e.Message, "Import Failed!"); Logger.LogException(e.Message); Logger.WriteLogToFile(); } }
private async Task SendEmail(ExportManagerQueueRecord exportManagerQueueRecord, String status) { var exportJob = await RetrieveExportJobRDO(exportManagerQueueRecord); var emailTo = exportJob[Constant.Guids.Field.ExportUtilityJob.EmailAddresses].ValueAsFixedLengthText; var jobName = exportJob[Constant.Guids.Field.ExportUtilityJob.Name].ValueAsFixedLengthText; String emailSubject = String.Format(Constant.EmailSubject, "export"); String emailBody = String.Format(Constant.EmailBody, "Export", jobName, exportManagerQueueRecord.WorkspaceName, exportManagerQueueRecord.WorkspaceArtifactId, status); if (!String.IsNullOrWhiteSpace(emailTo)) { await EmailUtility.SendEmail(AgentHelper.GetDBContext(-1), emailTo, emailSubject, emailBody, new SmtpClientSettings(AgentHelper.GetDBContext(-1), SqlQueryHelper)); } }
private async Task _SendVerificationEmail(string email, string userId) { string code = await UserManager.GenerateEmailConfirmationTokenAsync(userId); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userId, code = code }, protocol: Request.Url.Scheme); var emailUtility = new EmailUtility(); var emailParams = new Dictionary <String, String>(); emailParams.Add("UserName", email); emailParams.Add("ActivationLink", callbackUrl); // create a task for sending the verification mail var blEmail = emailUtility.SendEmail("VerifiyEmail", email, emailParams); }
public JsonResult SendEmails() { EmailUtility _emaUtility = new EmailUtility(_appSettings, _emailSettings); var emails = (from emp in _dbContext.tbl_Attendants where (emp.UserId ?? 0) == 0 select emp.Email).ToArray(); string emailBody = @"<p>Please register to In-Service Compliance Application to start you test with following link</p> <br /> <p><a href='" + _appSettings.Value.WebBaseURL + "/Account/Register'>" + _appSettings.Value.WebBaseURL + "/Register</a></p>"; _emaUtility.SendEmail("", "Registration link for In-Service Compliance", emailBody, emails); return(Json("Email sent successfully")); }
public bool SendShoppingListEmail(ShoppingListEmail email) { bool flag = false; EmailUtility utility = new EmailUtility(); try { utility.SendEmail(email, this._settings.ShoppingListEmailTemplate, this._settings.ShoppingListEmailFrom, email.EmailAddress); flag = true; } catch { throw; } return flag; }
public ActionResult ReportComment(int id) { var commentToReport = _db.Comments.Find(id); if (commentToReport != null) { // prepare report headers var commentSubverse = commentToReport.Message.Subverse; var reportTimeStamp = DateTime.Now.ToString(CultureInfo.InvariantCulture); // send the report try { var from = new MailAddress("*****@*****.**"); var to = new MailAddress("*****@*****.**"); var msg = new MailMessage(from, to) { Subject = "New comment report from " + User.Identity.Name, IsBodyHtml = false }; // format report email var sb = new StringBuilder(); sb.Append("Comment Id: " + id); sb.Append(Environment.NewLine); sb.Append("Subverse: " + commentSubverse); sb.Append(Environment.NewLine); sb.Append("Report timestamp: " + reportTimeStamp); sb.Append(Environment.NewLine); sb.Append("Comment permalink: " + "http://voat.co/v/" + commentSubverse + "/comments/" + commentToReport.MessageId + "/" + id); sb.Append(Environment.NewLine); msg.Body = sb.ToString(); EmailUtility.SendEmail(msg); } catch (Exception) { return(new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable, "Service Unavailable")); } } else { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request")); } return(new HttpStatusCodeResult(HttpStatusCode.OK, "OK")); }
public async Task <object> SendOTPToUser(string userId) { string Otp = OTPGenerator.Generate4DigitOTP(4); bool isSendEmail = false; if (await CheckandSaveUserOTP(Otp, userId)) { EmailUtility emailUtility = new EmailUtility(_config.GetSection("Creds:email:id").Value, _config.GetSection("Creds:email:password").Value); isSendEmail = await emailUtility.SendEmail(userId, "Your Passcode", string.Format(EmailTemplate.Password, Otp)); } return(new { emailSend = isSendEmail, userId }); }
public ActionResult DecideOnApplication(int id, int status) { if (id != 0 && (status == 1 || status == 0)) { var userId = _applicationRepository.updateApplicationStatus(id, status); if (userId != null) { // Send email to student var user = _userRepository.GetUser((int)userId); var isEmailSent = _emailUtility.SendEmail(user.Email, status); return(Json(new { success = true })); } } return(Json(new { success = false })); }
private static void SendDueDateReminderToReviewers(string sLoadID, string sLoadDate, string sDueDate, DataSet dsOItemsRevewers, out string sSentTo) { var sRecipients = ""; var sFileName = Settings.Default.DueDateReminderFile; var sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/docs/"); var sFullPath = sPath + sFileName; var str_subject = Utility.GetFileText(sFullPath, "SUBJECT"); str_subject = str_subject.Replace("[p_DueDate]", String.Format("{0:MMM dd, yyyy}", sDueDate)); var str_body = Utility.GetFileText(sFullPath, "BODY_REVIEWER"); str_body = str_body.Replace("[p_LoadDate]", String.Format("{0:MMM dd, yyyy}", sLoadID)); str_body = str_body.Replace("[p_DueDate]", String.Format("{0:MMM dd, yyyy}", sDueDate)); str_body = str_body.Replace("_message_body", ""); str_body = str_body.Replace("string", ""); var dt = dsOItemsRevewers.Tables[0]; foreach (DataRow dr in dt.Rows) { var items_count = (int)dr["ItemsCount"]; var current_body = str_body.Replace("[p_ItemsCount]", items_count.ToString()); var emails_arr = new string[1]; emails_arr[0] = (string)dr["Email"]; //emails_arr[0] = "*****@*****.**"; var emailobj = new EmailUtility(); emailobj.Subject = str_subject; emailobj.MessageBody = current_body; emailobj.To = emails_arr; emailobj.SendEmail(); if (sRecipients == "") { sRecipients = emails_arr[0]; } else { sRecipients = sRecipients + ", " + emails_arr[0]; } } sSentTo = sRecipients; }
public void SendEmail(string sTo, string sCc, string sSubject, string sBody, string sCurrentUserLogin) { var email = new EmailUtility(); email.Subject = sSubject; email.To = sTo.Split(new char[] { ',' }); email.Cc = sCc.Split(new char[] { ',' }); email.MessageBody = sBody; email.IsBodyHTML = false; if (sCurrentUserLogin.IndexOf("@") == -1) { email.From = sCurrentUserLogin + "@gsa.gov"; } email.SendEmail(); }
public static void commentReminderMail() { DataAccess da = new DataAccess(); DataTable dt = da.ExecuteStoredProc("getUsersToEmail"); dt.AsEnumerable().ToList().ForEach(x => EmailUtility.SendEmail( Convert.ToString(x["UserName"]), Convert.ToString(x["DisplayName"]), String.Format("{0} has sent you a message! ", Convert.ToString(x["Commentor_DisplayName"])), String.Format("{0} has sent you a message: <br/> '{1}'", Convert.ToString(x["Commentor_DisplayName"]), Convert.ToString(x["Comment"])) ) ); }
public static bool CancelTransaction(Transaction transaction) { bool success = CreateForbiddenMatch(transaction.BuyerPostId, transaction.SellerPostId) > 0 && CreateForbiddenMatch(transaction.SellerPostId, transaction.BuyerPostId) > 0; if (success) { Dictionary <string, object> updateDictionary = new Dictionary <string, object>(); updateDictionary.Add("IsDeleted", 1); UpdateTransaction(transaction.TransactionId, updateDictionary); PostHandler.updatePostState(transaction.SellerPostId, 0); PostHandler.updatePostState(transaction.BuyerPostId, 0); Profile buyer = ProfileHandler.GetProfile(transaction.BuyerId); Profile seller = ProfileHandler.GetProfile(transaction.SellerId); Textbook book = TextbookHandler.getTextbook(transaction.TextbookId); EmailUtility.SendEmail( Convert.ToString(buyer.Email), Convert.ToString(buyer.Name), "Your transaction has been cancelled", String.Format("Item: {0}</br>{1} has cancelled the transaction with you!<br/>" + "We'll try to match you with someone else for this item.", book.BookTitle, seller.Name) ); EmailUtility.SendEmail( Convert.ToString(seller.Email), Convert.ToString(seller.Name), "Your transaction has been cancelled", String.Format("Item: {0}<br/>{1} has cancelled the transaction with you!<br/>" + "We'll try to match you with someone else for this item.", book.BookTitle, buyer.Name) ); Post sellerPost = PostHandler.getPost(transaction.SellerPostId); Post buyerPost = PostHandler.getPost(transaction.BuyerPostId); Task.Run(() => QueueWorker.AddPost(sellerPost)); Task.Run(() => QueueWorker.AddPost(buyerPost)); } return(success); }
public ActionResult ClaSubmit(Cla claModel) { if (!ModelState.IsValid) { return(View("~/Views/Legal/Cla.cshtml")); } var from = new MailAddress(claModel.Email); var to = new MailAddress("*****@*****.**"); var sb = new StringBuilder(); var msg = new MailMessage(@from, to) { Subject = "New CLA Submission from " + claModel.FullName }; // format CLA email sb.Append("Full name: " + claModel.FullName); sb.Append(Environment.NewLine); sb.Append("Email: " + claModel.Email); sb.Append(Environment.NewLine); sb.Append("Mailing address: " + claModel.MailingAddress); sb.Append(Environment.NewLine); sb.Append("City: " + claModel.City); sb.Append(Environment.NewLine); sb.Append("Country: " + claModel.Country); sb.Append(Environment.NewLine); sb.Append("Phone number: " + claModel.PhoneNumber); sb.Append(Environment.NewLine); sb.Append("Corporate contributor information: " + claModel.CorpContrInfo); sb.Append(Environment.NewLine); sb.Append("Electronic signature: " + claModel.ElectronicSignature); sb.Append(Environment.NewLine); msg.Body = sb.ToString(); // send the email with CLA data if (EmailUtility.SendEmail(msg)) { msg.Dispose(); ViewBag.SelectedSubverse = string.Empty; return(View("~/Views/Legal/ClaSent.cshtml")); } ViewBag.SelectedSubverse = string.Empty; return(View("~/Views/Legal/ClaFailed.cshtml")); }
protected void grdRescheduling_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Approve") { LinkButton lb = (LinkButton)e.CommandSource; GridViewRow gvr = (GridViewRow)lb.NamingContainer; Int64 BMSSCTID = Convert.ToInt64(grdRescheduling.DataKeys[gvr.RowIndex].Values["BMSSCTID"].ToString()); Int64 ReSchedulingID = Convert.ToInt64(grdRescheduling.DataKeys[gvr.RowIndex].Values["ReSchedulingID"].ToString()); Int64 EmployeeID = Convert.ToInt64(grdRescheduling.DataKeys[gvr.RowIndex].Values["EmployeeID"].ToString()); TextBox txt1 = (TextBox)grdRescheduling.Rows[gvr.RowIndex].Cells[8].FindControl("txtStartDate"); DateTime StartDate = DateTime.ParseExact(txt1.Text, "dd-MM-yyyy", null); TextBox txt2 = (TextBox)grdRescheduling.Rows[gvr.RowIndex].Cells[9].FindControl("txtEndDate"); DateTime EndDate = DateTime.ParseExact(txt2.Text, "dd-MM-yyyy", null); string Subject = grdRescheduling.DataKeys[gvr.RowIndex].Values["Subject"].ToString(); string Standard = grdRescheduling.DataKeys[gvr.RowIndex].Values["Standard"].ToString(); string Division = grdRescheduling.DataKeys[gvr.RowIndex].Values["Division"].ToString(); string Chapter = grdRescheduling.DataKeys[gvr.RowIndex].Values["Chapter"].ToString(); string Topic = grdRescheduling.DataKeys[gvr.RowIndex].Values["Topic"].ToString(); ArrayList alistEmailAddress = GenerateEmailAddress(EmployeeID); if (alistEmailAddress.Count > 0) { string Body = GenerateEmailBody(Subject, Standard, Division, Chapter, Topic, EndDate.ToString("dd-MMM-yyyy")); EmailUtility.SendEmail(alistEmailAddress, "Rescheduling request Approval", Body); } if (IsValidDates(StartDate, EndDate)) { BLogic_SYS_Rescheduling = new SYS_Rescheduling_BLogic(); Prop_SYS_Rescheduling = new SYS_Rescheduling(); Prop_SYS_Rescheduling.ReSchedulingID = ReSchedulingID; Prop_SYS_Rescheduling.BMSSCTID = BMSSCTID; Prop_SYS_Rescheduling.EmployeeID = EmployeeID; Prop_SYS_Rescheduling.StartDate = StartDate; Prop_SYS_Rescheduling.EndDate = EndDate; BLogic_SYS_Rescheduling.BAL_SYS_Rescheduling_Update(Prop_SYS_Rescheduling); ViewState["ID"] = null; BindGridAttandance(); } else { WebMsg.Show("2 Days Difference is must"); } } }
public ActionResult Index(PasswordReminder passwordreminder) { bool flag = base.Request.IsAjaxRequest(); bool flag2 = false; bool flag3 = false; string resource = string.Empty; string str2 = string.Empty; this.Logger.Debug("PasswordReminderController > Index "); bool isValid = base.ModelState.IsValid; this.Logger.DebugFormat("PasswordReminderController > isValid {0}", new object[] { isValid }); if (isValid) { if (passwordreminder.ReminderEmailAddress != null) { try { MembershipUser user = Membership.GetUser(passwordreminder.ReminderEmailAddress, false); this.Logger.DebugFormat("PasswordReminderController > user {0}", new object[] { user == null }); if (user != null) { CoatsUserProfile profile = CoatsUserProfile.GetProfile(user.Email); this.Logger.DebugFormat("PasswordReminderController > coatsUserProfile {0}", new object[] { profile == null }); string fromEmailAddress = ConfigurationManager.AppSettings["PasswordReminderEmailFrom"]; string emailTemplate = ConfigurationManager.AppSettings["PasswordReminderEmailTemplate"]; EmailUtility utility = new EmailUtility(); if (profile != null) { string str5; flag3 = true; resource = Helper.GetResource("PasswordReminderSuccess"); if (base.Request.Url != null) { str5 = base.Request.Url.Scheme + "://" + base.Request.Url.Host + base.Url.Content(WebConfiguration.Current.Registration.AddApplicationRoot()); } else { str5 = ConfigurationManager.AppSettings["SiteUrl"] + base.Url.Content(WebConfiguration.Current.Registration.AddApplicationRoot()); } ResetPassword model = new ResetPassword { Password = profile.PASSWORD, SiteUrl = str5 }; string str6 = utility.SendEmail(model, emailTemplate, fromEmailAddress, user.Email); this.Logger.DebugFormat("PasswordReminderController > result {0}", new object[] { str6 }); if (!(!string.IsNullOrEmpty(str6) && str6.Equals("true"))) { flag3 = false; resource = Helper.GetResource("ResetPasswordFailure"); base.ModelState.AddModelError("EmailAddress", "Errors.SendEmailError"); } } } flag3 = true; resource = Helper.GetResource("PasswordReminderSuccess"); ((dynamic) base.ViewBag).MessageSent = "true"; } catch (Exception) { flag3 = false; resource = Helper.GetResource("ResetPasswordFailure"); } } else { flag3 = false; resource = Helper.GetResource("ValidEmail"); } } if (!isValid) { this.Logger.Debug("PasswordReminderController > isValid was false"); var typeArray = (from x in base.ModelState where x.Value.Errors.Count > 0 select new { Key = x.Key, Errors = x.Value.Errors }).ToArray(); flag3 = false; resource = Helper.GetResource("ValidEmail"); } if (flag) { return base.Json(new { success = flag3, allowRedirect = flag2, redirect = str2, message = resource }); } return base.View(); }
public ActionResult Index(ComponentPresentation componentPresentation, Registration model, string Stage) { bool flag = base.Request.IsAjaxRequest(); bool flag2 = false; bool flag3 = false; string errorMessage = string.Empty; string returnUrl = string.Empty; LoginForm loginForm = model.LoginForm; RegistrationForm registrationForm = model.RegistrationForm; string str3 = !string.IsNullOrWhiteSpace(base.Request["source"]) ? base.Request["source"] : string.Empty; if (loginForm != null) { if (!string.IsNullOrEmpty(loginForm.ReturnUrl)) { returnUrl = loginForm.ReturnUrl; } if (!string.IsNullOrEmpty(str3)) { returnUrl = str3; } errorMessage = Helper.GetResource("LoginFailed"); if (this.Login(loginForm)) { errorMessage = Helper.GetResource("LoginSuccess"); flag3 = true; flag2 = true; } else { ((dynamic) base.ViewBag).Stage = "register"; base.ModelState.AddModelError("LoginFailed", errorMessage); } if (flag) { return base.Json(new { success = flag3, allowRedirect = flag2, redirect = returnUrl, message = errorMessage }); } } if (registrationForm != null) { EmailUtility utility; string str4; string str5; string str6; Exception exception; if (!string.IsNullOrEmpty(registrationForm.returnUrl)) { returnUrl = registrationForm.returnUrl; } if (!string.IsNullOrEmpty(str3)) { returnUrl = str3; } errorMessage = Helper.GetResource("RegistrationFailed"); PublicasterServiceRequest request = new PublicasterServiceRequest(); switch (Stage) { case "register": errorMessage = Helper.GetResource("RegistrationFailed"); if (!this.IsProfileValid(registrationForm)) { ((dynamic) base.ViewBag).Stage = "register"; flag3 = false; errorMessage = Helper.GetResource("RegistrationFailed"); base.ModelState.AddModelError("UnableToCreateNewUser", Helper.GetResource("UnableToCreateNewUser")); break; } if (this.Register(registrationForm)) { ((dynamic) base.ViewBag).Stage = "preferences"; flag3 = true; errorMessage = Helper.GetResource("RegisteredSuccessfully"); this.Logger.InfoFormat("RegistrationController : User created: {0} - {1}", new object[] { registrationForm.CustomerDetails.DisplayName, registrationForm.CustomerDetails.EmailAddress }); try { if (!WebConfiguration.Current.CheckEmailNewsletterOption) { utility = new EmailUtility(); str4 = ConfigurationManager.AppSettings["PasswordReminderEmailFrom"]; str5 = ConfigurationManager.AppSettings["RegisterConfirmationEmailTemplate"]; str6 = utility.SendEmail(registrationForm.CustomerDetails, str5, str4, registrationForm.CustomerDetails.EmailAddress); this.Logger.DebugFormat("RegistrationController : Register Confirmation Email > result {0}", new object[] { str6 }); } } catch (Exception exception1) { exception = exception1; this.Logger.Debug("Unable to send confirmation email to user."); } } else { ((dynamic) base.ViewBag).Stage = "register"; flag3 = false; errorMessage = Helper.GetResource("UnableToCreateNewUser"); base.ModelState.AddModelError("UnableToCreateNewUser", Helper.GetResource("UnableToCreateNewUser")); } break; case "preferences": errorMessage = Helper.GetResource("PreferencesFailed"); model.RegistrationForm.returnUrl = this._settings.RegisterWelcome; if (this.Preferences(registrationForm)) { ((dynamic) base.ViewBag).Stage = "profile"; flag3 = true; errorMessage = Helper.GetResource("PreferencesSaved"); try { MvcApplication.CraftsPrincipal user = (MvcApplication.CraftsPrincipal) base.HttpContext.User; CoatsUserProfile profile = CoatsUserProfile.GetProfile(base.User.Identity.Name); utility = new EmailUtility(); str4 = ConfigurationManager.AppSettings["PasswordReminderEmailFrom"]; str5 = ConfigurationManager.AppSettings["RegisterConfirmationEmailTemplate"]; string newsletter = "No"; string interests = string.Empty; foreach (KeyValuePair<string, string> pair in registrationForm.Keywords) { interests = interests + pair.Key + ","; } if (interests.Length > 0) { interests = interests.Substring(0, interests.LastIndexOf(",") - 1); } KeyValuePair<string, string> pair2 = registrationForm.Keywords.SingleOrDefault<KeyValuePair<string, string>>(e => e.Key == WebConfiguration.Current.EmailNewsletterYes); if (pair2.Key != null) { newsletter = "yes"; } if (WebConfiguration.Current.CheckEmailNewsletterOption && (pair2.Key != null)) { newsletter = "yes"; string str9 = string.Empty; if (base.Request.Url != null) { str9 = base.Request.Url.Scheme + "://" + base.Request.Url.Host; } else { str9 = ConfigurationManager.AppSettings["SiteUrl"]; } string registerThankYou = this._settings.RegisterThankYou; string str11 = HttpUtility.UrlEncode(General.Encrypt(profile.MAIL.Trim())); str9 = registerThankYou + "?UserEmail=" + str11; registrationForm.CustomerDetails.SiteUrl = str9; registrationForm.CustomerDetails.DisplayName = profile.DISPLAYNAME; registrationForm.CustomerDetails.LastName = profile.SURNAME; registrationForm.CustomerDetails.FirstName = profile.NAME; registrationForm.CustomerDetails.EmailAddress = profile.MAIL; str6 = utility.SendEmail(registrationForm.CustomerDetails, str5, str4, profile.MAIL); this.Logger.DebugFormat("RegistrationController : Register Confirmation Email > result {0}", new object[] { str6 }); string clientIP = this.GetClientIP(); this._registrationrepository.SaveRegisterData(registrationForm.CustomerDetails.EmailAddress, clientIP, ""); request.createJsonPublicasterRequest(registrationForm.CustomerDetails.EmailAddress, registrationForm.CustomerDetails.FirstName, registrationForm.CustomerDetails.LastName, interests, registrationForm.CustomerDetails.DisplayName, newsletter); } } catch (Exception exception2) { exception = exception2; this.Logger.Debug("Unable to send confirmation email to user."); } } else { ((dynamic) base.ViewBag).Stage = "preferences"; flag3 = false; } break; case "profile": errorMessage = Helper.GetResource("PreferencesSaved"); model.RegistrationForm.returnUrl = this._settings.RegisterWelcome; if (this.Preferences(registrationForm)) { flag3 = true; errorMessage = Helper.GetResource("ProfileSaved"); base.HttpContext.Session["registrationStatus"] = ""; returnUrl = this._settings.RegisterWelcome; flag2 = true; } else { ((dynamic) base.ViewBag).Stage = "profile"; flag3 = false; } break; } } if (flag2) { returnUrl = !string.IsNullOrEmpty(returnUrl) ? returnUrl : base.Url.Content(WebConfiguration.Current.MyProfile); if (flag) { return base.Json(new { success = flag3, allowRedirect = flag2, redirect = returnUrl, message = errorMessage }); } base.HttpContext.Response.Redirect(returnUrl); } model.RegistrationForm = (registrationForm != null) ? registrationForm : new RegistrationForm(); model.LoginForm = (loginForm != null) ? loginForm : new LoginForm(); model.RegistrationForm.returnUrl = returnUrl; model.LoginForm.ReturnUrl = returnUrl; this.GetModelData(model.RegistrationForm); return base.View(model); }
public ActionResult Index(ComponentPresentation componentPresentation, UserProfile model) { this.Logger.DebugFormat("Called Update Profile >>>> ", new object[0]); try { ((dynamic) base.ViewBag).Title = componentPresentation.Component.Fields["title"].Value; } catch (Exception) { } string email = string.Empty; if (base.User.Identity.IsAuthenticated) { email = base.User.Identity.Name; } bool flag = this.IsEditModelValid(model); if (flag) { try { MembershipUser user = Membership.GetUser(); if (user == null) { flag = false; this.Logger.DebugFormat("Update Profile mUser null", new object[0]); } if (model.AddressDetails.Postcode != null) { this.FindPostcode(model); } if (model.RegistrationStatus == "postcode invalid") { flag = false; } if (flag) { this.Logger.DebugFormat("User profile start >>>>", new object[0]); CoatsUserProfile userProfile = CoatsUserProfile.GetProfile(user.Email); if (userProfile != null) { string selectedKeywords = base.Request["CraftType"]; string str3 = base.Request["email-newsletter"]; string str4 = base.Request["visibile-profile"]; PublicasterServiceRequest request = new PublicasterServiceRequest(); string newsletter = "No"; if (str3.Trim() == WebConfiguration.Current.EmailNewsletterYes.Trim()) { newsletter = "yes"; } if (((selectedKeywords != null) || (str3 != null)) || (str4 != null)) { List<TridionTcmUri> keywordsSelectListItems = GetKeywordsSelectListItems(selectedKeywords); List<TridionTcmUri> second = GetKeywordsSelectListItems(str3); List<TridionTcmUri> list3 = GetKeywordsSelectListItems(str4); IEnumerable<TridionTcmUri> enumerable = keywordsSelectListItems.Union<TridionTcmUri>(second).Union<TridionTcmUri>(list3); Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (TridionTcmUri uri in enumerable) { dictionary.Add(uri.TcmId, "tcm"); } userProfile.Keywords = dictionary; model.Keywords = dictionary; } if (!string.IsNullOrEmpty(model.NewPassword)) { if (model.NewPassword == model.VerifyNewPassword) { if (!string.IsNullOrEmpty(model.CurrentPassword)) { CoatsUserProfile profile = CoatsUserProfile.GetProfile(email); if (model.CurrentPassword == profile.PASSWORD) { model.CustomerDetails.Password = model.NewPassword; } else { flag = false; base.ModelState.AddModelError("CurrentPasswordIncorrect", Helper.GetResource("CurrentPasswordIncorrect")); } } else { flag = false; } } else { flag = false; base.ModelState.AddModelError("NewPasswordsNotMatch", Helper.GetResource("NewPasswordsNotMatch")); } } if (flag) { this.MapUserProfileForUpdate(model, userProfile); userProfile.Save(); if ((str3 != null) && WebConfiguration.Current.CheckEmailNewsletterOption) { if (str3.Trim() == WebConfiguration.Current.EmailNewsletterYes.Trim()) { EmailUtility utility = new EmailUtility(); string fromEmailAddress = ConfigurationManager.AppSettings["PasswordReminderEmailFrom"]; string emailTemplate = ConfigurationManager.AppSettings["RegisterConfirmationEmailTemplate"]; string registerThankYou = this._settings.RegisterThankYou; string str9 = HttpUtility.UrlEncode(General.Encrypt(userProfile.MAIL.Trim())); registerThankYou = registerThankYou + "?UserEmail=" + str9; model.CustomerDetails.SiteUrl = registerThankYou; model.CustomerDetails.DisplayName = userProfile.DISPLAYNAME; model.CustomerDetails.EmailAddress = userProfile.MAIL; string str10 = utility.SendEmail(model.CustomerDetails, emailTemplate, fromEmailAddress, userProfile.MAIL); this.Logger.DebugFormat("ProfileController : Register Confirmation Email > result {0}", new object[] { str10 }); request.createJsonPublicasterRequest(userProfile.MAIL, userProfile.NAME, userProfile.SURNAME, selectedKeywords, userProfile.DISPLAYNAME, newsletter); } else { request.UnSubscripePublicaster(userProfile.MAIL); } } CoatsUserProfile profile3 = CoatsUserProfile.GetProfile(userProfile.MAIL); CookieHelper.WriteFormsCookie(userProfile.MAIL, userProfile.DISPLAYNAME, userProfile.NAME, userProfile.SURNAME, userProfile.LONG, userProfile.LAT, ""); ((dynamic) base.ViewBag).profileStatus = "saved"; if (profile3 == null) { flag = false; base.ModelState.AddModelError(string.Empty, ""); this.Logger.DebugFormat("Update Profile newUser null", new object[0]); } } } } } catch (Exception exception) { this.Logger.DebugFormat("Update Profile exception {0} {1}", new object[] { exception.Message, exception.InnerException }); flag = false; } } if (base.ModelState.ContainsKey("CustomerDetails.DisplayName")) { base.ModelState["CustomerDetails.DisplayName"].Errors.Clear(); } if (base.ModelState.ContainsKey("CustomerDetails.EmailAddress")) { base.ModelState["CustomerDetails.EmailAddress"].Errors.Clear(); } if (!flag) { UserProfile profile4 = this.GetModel(); base.ModelState.AddModelError(string.Empty, ""); var typeArray = (from x in base.ModelState where x.Value.Errors.Count > 0 select new { Key = x.Key, Errors = x.Value.Errors }).ToArray(); foreach (var type in typeArray) { this.Logger.DebugFormat("Update Profile error {0}", new object[] { type }); } this.GetModelData(profile4); base.Session["feedback"] = Helper.GetResource("ProfileError"); ((dynamic) base.ViewBag).profileStatus = "error"; return base.View(profile4); } UserProfile profile5 = this.GetModel(); base.Session["feedback"] = Helper.GetResource("ProfileChangesSaved"); return base.View(profile5); }