private static void send404Mail( string receivers, string url, string refererUrl, string redirectUrl, string userAgent, string userHostName, string userHostAddress) { var subject = Resources.Str_404EMailMessageSubject; var body = replacePlaceholders( Resources.Str_404EMailMessageBody, url, refererUrl, redirectUrl, userAgent, userHostName, userHostAddress); using (var message = new MailMessage()) { message.IsBodyHtml = true; message.Subject = subject; message.Body = body; message.From = Host.Current.ElementManager.OwnerEMailAddress; message.To.Add(receivers); MailHelper.WriteMailToFile( message, @"Zeta Producer Shop - Main_404.html"); EMailHelper.SendEMailMessage(message); } }
/// <summary> /// Dodaje pracownika do bazy danych /// </summary> /// <param name="newEmployee">Nowy pracownik</param> public IHttpActionResult Post(EmployeeAddDto newEmployee) { if (!ModelState.IsValid) { return(BadRequest()); } Employee employee = Mapper.Map <Employee>(newEmployee); var password = RandomString(15); var role = newEmployee.Role; var user = new User { UserName = GenerateUserName(employee) }; if (context.Users.Any(u => user.UserName == u.UserName)) { return(BadRequest()); } var result = userManager.Create(user, password); if (!result.Succeeded) { return(BadRequest(result.Errors.ToString())); } userManager.AddToRole(user.Id, role.ToString()); employee.User = user; context.Employees.Add(employee); context.SaveChanges(); using (var eh = new EMailHelper()) { eh.SendEmail(employee.Email, "Instant Delivery - Rejestracja", eh.RegistrationBody(employee, password)); } return(Ok(employee.Id)); }
/// <summary> /// 发送邮件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button17_Click(object sender, EventArgs e) { #region //MailAddress from = new MailAddress("*****@*****.**"); //string messageTo = "*****@*****.**"; //string messageSubject = "测试邮件"; //string body = "测试邮件内容"; //Send(from, messageTo, messageSubject, body, ""); #endregion NameValueCollection values = new NameValueCollection(); values.Add("name", "WUWEI"); values.Add("start", "2017-09-20"); values.Add("end", "2018-09-30"); values.Add("points", "10000"); string template = EmailTemplateHelper.ConstructTemplate("../EmailTemplate.txt", values); EMailHelper helper = new EMailHelper(); helper.MailSmtpServer = "smtp.aliyun.com"; helper.MailCredential = "*****@*****.**"; helper.MailCredentialPwd = "wuwei038177"; string mailFrom = "*****@*****.**"; string mailTo = "[email protected];"; string mailSubject = "模板邮件"; string mailCC = "[email protected];"; string result; helper.SendSmtpMail(mailFrom, mailTo, mailSubject, template, "", "", mailCC, out result); }
private bool SendEmail(EmailIdDTO emailIds, EventMessageDTO EventMessage, string UpdatedMessage) { SMTPDTO projectSTMPDetails = GetSMTPDetails(); if (projectSTMPDetails == null) { return(false); } SMTPDTO smtpDTO = new SMTPDTO(); smtpDTO.SMTPUserId = projectSTMPDetails.SMTPUserId; smtpDTO.SMTPPassword = projectSTMPDetails.SMTPPassword; smtpDTO.SMTPServer = projectSTMPDetails.SMTPServer; smtpDTO.Port = projectSTMPDetails.Port; smtpDTO.FromEmailId = projectSTMPDetails.FromEmailId; smtpDTO.ReplyToId = projectSTMPDetails.ReplyToId; smtpDTO.FromDisplayName = projectSTMPDetails.FromDisplayName; EmailDTO emailDTO = new EmailDTO(); emailDTO.To = emailIds.TOs; emailDTO.CC = emailIds.CCs; emailDTO.BCC = emailIds.BCCs; emailDTO.Body = UpdatedMessage; emailDTO.Subject = EventMessage.EventSubject; EMailHelper emailHelper = new EMailHelper(smtpDTO); emailHelper.SendEmail(emailDTO); return(true); }
public IHttpActionResult PostRecoveryPassword([FromUri] string email) { var user = db.Users.FirstOrDefault(x => x.Email == email); if (user == null) { return(NotFound()); } var newpass = System.Web.Security.Membership.GeneratePassword(6, 0); var emailInput = new EmailInputDto(); //var pat = db.Patients.Find(emailPostDto.appointment.PatientId); emailInput.UserName = user.FirstName + " " + user.LastName; emailInput.Email = user.Email; emailInput.Subject = "Відновлення пароля!"; emailInput.Body = "Ваш парольно змінено\nНовий пароль:\n" + newpass + "\nБудь ласка змініть свій пароль при входженні в систему"; try { EMailHelper.SendNotification(emailInput); user.Password = HashHelper.sha256_hash(newpass); db.Entry(user).State = EntityState.Modified; db.SaveChanges(); return(Ok()); } catch (Exception) { return(BadRequest()); } }
public EmailSettings(List <List <ExceptionData> > exceptionDataList) { var configuration = GetConfiguration(); var eMailContent = new EMailContent(); eMailContent.From = configuration.GetSection("EmailSettings:Email").Value; eMailContent.ToList = configuration.GetSection("EmailSettings:To").Get <List <string> >(); eMailContent.Subject = "Exception List"; string databaseName = ""; string tableContent = ""; foreach (var variable in exceptionDataList) { foreach (var item in variable) { databaseName = item.DatabaseName; tableContent += "<tr>" + $"<td>{item.Id}</td>" + $"<td>{item.Message}" + $"<td>{item.StackTrace}</td>" + $"<td>{item.CreatedDate}</td>" + "</tr>"; } eMailContent.Content += "<table border='1'>" + "<tr>" + "<td><b>Database Name</b></td>" + $"<td style='color:#FF0000' colspan='3'><b>{databaseName}</b></td>" + "</tr>" + "<tr>" + "<td><b>Exception Id</b></td>" + "<td><b>Message</b></td>" + "<td><b>Stack Trace</b></td>" + "<td><b>Created Date</b></td>" + "</tr >" + tableContent + "</ table >"; } eMailContent.Password = configuration.GetSection("EmailSettings:Password").Value; eMailContent.Port = Int32.Parse(configuration.GetSection("EmailSettings:Port").Value); eMailContent.ServerAddress = configuration.GetSection("EmailSettings:ServerAddress").Value; EMailHelper.SendEmail(eMailContent); }
public object SendMessage([FromBody] HTMLDto html) { var currentUser = db.Users.FirstOrDefault(x => x.Email == User.Identity.Name); EMailHelper.SendNotification(new EmailInputDto { Email = currentUser.Email, Body = html.HTML, Subject = "Підтвердження замовлення", UserName = currentUser.LastName + " " + currentUser.FirstName }); return(Ok()); }
/// <summary> /// Function called in order to send an asynchronous mail /// </summary> /// <param name="EMail"></param> public bool SendMailAsync(Email EMail) { bool result = false; try { result = EMailHelper.SendMail(EMail); } catch (Exception e) { result = false; Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "EMailTypeId = " + EMail.EMailTypeId + " and emailto =" + EMail.ToEmail); } return(result); }
public PreviewNewsMailViewModel GetPreviewNewsMailViewModel(string Title, string Description, UserSession user) { PreviewNewsMailViewModel model = new PreviewNewsMailViewModel(); try { if (Title == null) { Title = ""; } if (Description == null) { Description = ""; } List <Tuple <string, string> > GenericEmailContent = EMailHelper.GetGenericEmailContent(); GenericEmailContent.Add(new Tuple <string, string>("#UserFirstName#", user.FirstName)); GenericEmailContent.Add(new Tuple <string, string>("#UserFullName#", user.UserFullName)); GenericEmailContent.Add(new Tuple <string, string>("#RealUserEMail#", "")); GenericEmailContent.Add(new Tuple <string, string>("#WebSiteURL#", Utils.Website)); GenericEmailContent.Add(new Tuple <string, string>("#WatcherUrl#", FileHelper.GetStorageRoot(DefaultImage.Empty))); string BasePathFile = FileHelper.GetRootPathDefault() + @"\" + Const.BasePathTemplateEMails.Replace("~/", "\\"); string PathHeaderOnServer = BasePathFile + "\\_HeaderMail.html"; string PathFooterOnServer = BasePathFile + "\\_FooterMail.html"; string PathEndMailOnServer = BasePathFile + "\\_EndMail_en.html"; string PathTemplateOnServer = BasePathFile + "\\news_en.html"; string headerTemplate = System.IO.File.ReadAllText(PathHeaderOnServer); string bodyTemplate = System.IO.File.ReadAllText(PathTemplateOnServer); string footerTemplate = System.IO.File.ReadAllText(PathFooterOnServer); string endMailTemplate = System.IO.File.ReadAllText(PathEndMailOnServer); model.Body = headerTemplate + bodyTemplate + endMailTemplate + footerTemplate; foreach (var content in GenericEmailContent) { model.Body = model.Body.Replace(content.Item1, content.Item2); } model.Body = model.Body.Replace("#Title#", Title).Replace("#Description#", Description); } catch (Exception e) { Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Title = " + Title); } return(model); }
private async Task <IHttpActionResult> SendEmailNotification(EmailInput data) { try { EMailHelper mailHelper = new EMailHelper(EMailHelper.EMAIL_SENDER, EMailHelper.EMAIL_CREDENTIALS, EMailHelper.SMTP_CLIENT); var emailBody = String.Format(EMailHelper.EMAIL_BODY); if (mailHelper.SendEMail(data.EmailId, EMailHelper.EMAIL_SUBJECT, emailBody)) { // } } catch (Exception ex) { } return(Ok()); }
/// <summary> /// Function called in order to send an asynchronous mail /// </summary> /// <param name="EMail"></param> public void SendMailAsync(Email EMail) { try { Tuple <bool, int, int> ResultMail = EMailHelper.SendMail(EMail); if (ResultMail != null) { if (ResultMail.Item1) { InsertEMailAudit(EMail, ResultMail.Item2, ResultMail.Item3); } } } catch (Exception e) { Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "EMailTypeId = " + EMail.EMailTypeId + " and emailto =" + EMail.ToEmail); } }
private void BtnRegister_Click(object sender, RoutedEventArgs e) { string password = pwdRegisterPassword.Password.ToString(); Random random = new Random(); User currentUser = new User(); currentUser.FirstName = txtRegisterFirstName.Text; currentUser.LastName = txtRegisterLastName.Text; currentUser.EMail = txtRegisterEMail.Text; currentUser.Password = password; currentUser.ActivationCode = random.Next(1001, 9999).ToString(); currentUser.IsActive = false; try { bool result = _userService.Insert(currentUser); if (result) { result = EMailHelper.SendEMail(currentUser.EMail, currentUser.ActivationCode, currentUser.FirstName, currentUser.LastName); if (result) { MessageBox.Show(string.Format(currentUser.FirstName + " " + currentUser.LastName + "\nCheck your mail inbox for activation code")); } else { MessageBox.Show("Could not send activation mail"); _userService.Delete(currentUser); return; } lblActivation.Visibility = Visibility.Visible; txtActivationCode.Visibility = Visibility.Visible; } ShowGrid(gLogin); txtLoginEMail.Text = currentUser.EMail; pwdLoginPassword.Password = currentUser.Password; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 开启电子邮件发射之旅 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnMailSend_Click(object sender, EventArgs e) { if (lstRecipients.Items.Count <= 0) { MsgBox.Show("收件人信息不能为空。"); return; } //SMTP 服务器信息 var _server = txtSMTPServer.Text.Trim(); var _port = TypeHelper.TypeToInt32(txtSMTPPort.Text.Trim(), 25); var _user = txtSMTPUser.Text.Trim(); var _pwd = txtSMTPPwd.Text.Trim(); //服务器信息 EMailSrvInfo _srvInfo = new EMailSrvInfo(); _srvInfo.SMTPServer = _server; _srvInfo.SMTPPort = _port; _srvInfo.UserName = _user; _srvInfo.Password = _pwd; _srvInfo.DisplayName = txtMailUser.Text.Trim(); //电子邮件信息 EMailInfo _mailInfo = new EMailInfo(); foreach (string item in lstRecipients.Items) { _mailInfo.Recipient.Enqueue(item); } _mailInfo.Subject = txtMailSubject.Text.Trim(); _mailInfo.IsHTML = chkMailHtml.Checked; _mailInfo.Body = txtMailBody.Text.Trim(); EMailHelper _mailHelper = new EMailHelper(_srvInfo); _mailHelper.Send(_mailInfo); if (_mailHelper.IsSuccessful) { MsgBox.Show("电子邮件发送成功!"); } else { MsgBox.Show($"电子邮件发送失败!【原因:{_mailHelper.LastErrorMessage}】"); } }
public IHttpActionResult SendConfirmRegisterEmail(int id) { var emailInput = new EmailInputDto(); var client = db.Clients.Find(id); emailInput.UserName = client.FirstName + client.LastName; emailInput.Email = client.Email; emailInput.Subject = "Підтвердження реєстрації!"; try { EMailHelper.SendConfirmRegisterNotification(emailInput, id); } catch (Exception ex) { return(BadRequest(ex.Message)); } return(Ok()); }
public IHttpActionResult AssignPackage([FromUri] int packageId, [FromBody] int employeeId) { var package = context.Packages.Find(packageId); var employee = context.Employees.Find(employeeId); package.Status = PackageStatus.InDelivery; employee.Packages.Add(package); context.PackageEvents.Add(new PackageEvent { Employee = employee, Package = package, EventType = PackageEventType.HandedToCourier }); context.SaveChanges(); using (var eh = new EMailHelper()) { eh.SendEmail(employee.Email, "Instant Delivery - Nowe zlecenie", eh.AssignedPackageBody(employee)); } return(Ok()); }
public ActionResult Contact(ContactModel contact) { if (ModelState.IsValid) { RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper(); if (String.IsNullOrEmpty(recaptchaHelper.Response)) { ModelState.AddModelError("", "Captcha answer cannot be empty."); ViewBag.recaptchaError = "Captcha answer cannot be empty."; } RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse(); if (recaptchaResult != RecaptchaVerificationResult.Success) { ModelState.AddModelError("", "Incorrect captcha answer."); ViewBag.recaptchaError = "Incorrect captcha answer."; } else { ViewBag.pageName = "contact"; string emailBody = System.IO.File.ReadAllText(Server.MapPath("~/utils/ResetPassword.html")); emailBody = emailBody.Replace("[Name]", contact.Name); emailBody = emailBody.Replace("[Email]", contact.Email); emailBody = emailBody.Replace("[Technology]", contact.Topics); emailBody = emailBody.Replace("[Message]", contact.Message); EMailHelper.SendEmail(System.Configuration.ConfigurationManager.AppSettings["officealEmail"], System.Configuration.ConfigurationManager.AppSettings["EmailSubject"], emailBody); ViewBag.emailsent = "Thanks for contacting us. We will contact you as soon."; contact.Email = ""; contact.Message = ""; contact.Name = ""; contact.Topics = ""; } } return(View()); }
public bool AddUsersToAdAndDb(GUIReceivedUserJSONModel guiReceivedUserJSONModel, int batchId) { ADUserGraphTokenResponse aDUserGraphTokenResponse = GenerateAccessToken(); ADUserJsonModel adUserJson = new ADUserJsonModel(); GraphAddUserJSONModel graphUser = new GraphAddUserJSONModel(); HttpClient graphCRUDClient = new HttpClient(); string responseString = ""; Task.Run(async() => { graphCRUDClient.BaseAddress = new Uri("https://graph.microsoft.com/v1.0/users"); graphCRUDClient.DefaultRequestHeaders.Accept.Clear(); graphCRUDClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + aDUserGraphTokenResponse.AccessToken); graphCRUDClient.DefaultRequestHeaders.Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); //message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", aDUserGraphTokenResponse.AccessToken); Random rnd = new Random(); int num1 = rnd.Next(0, 9); int num2 = rnd.Next(0, 9); int num3 = rnd.Next(0, 9); int num4 = rnd.Next(0, 9); Models.ADModels.PasswordProfile passwordProfile = new Models.ADModels.PasswordProfile() { Password = Membership.GeneratePassword(12, 1), ForceChangePasswordNextSignIn = true }; graphUser.AccountEnabled = true; graphUser.DisplayName = guiReceivedUserJSONModel.FirstName.Replace(" ", String.Empty) + guiReceivedUserJSONModel.LastName.Replace(" ", String.Empty); graphUser.GivenName = guiReceivedUserJSONModel.FirstName.Replace(" ", String.Empty); graphUser.Surname = guiReceivedUserJSONModel.LastName.Replace(" ", String.Empty); graphUser.MobilePhone = guiReceivedUserJSONModel.PhoneNumber.Replace(" ", String.Empty); graphUser.MailNickname = guiReceivedUserJSONModel.FirstName.Replace(" ", String.Empty) + guiReceivedUserJSONModel.LastName.Substring(0, 1).Replace(" ", String.Empty); graphUser.UserPrincipalName = guiReceivedUserJSONModel.FirstName.ToLower().Replace(" ", String.Empty) + "." + guiReceivedUserJSONModel.LastName.ToLower().Replace(" ", String.Empty) + Convert.ToString(num1) + Convert.ToString(num2) + Convert.ToString(num3) + Convert.ToString(num4) + "@andresgllive764.onmicrosoft.com"; graphUser.PasswordPolicies = "DisablePasswordExpiration"; graphUser.PasswordProfile = passwordProfile; graphUser.JobTitle = "Tenant"; string postBody = JsonConvert.SerializeObject(graphUser); var content = new StringContent(postBody, Encoding.UTF8, "application/json"); HttpResponseMessage response = await graphCRUDClient.PostAsync("", content); responseString = await response.Content.ReadAsStringAsync(); }).Wait(); try { JToken parsed = JToken.Parse(responseString); adUserJson.Id = parsed["id"].Value <string>(); adUserJson.DisplayName = parsed["displayName"].Value <string>(); adUserJson.GivenName = parsed["givenName"].Value <string>(); adUserJson.JobTitle = parsed["jobTitle"].Value <string>(); adUserJson.Mail = parsed["mail"].Value <string>(); adUserJson.MobilePhone = parsed["mobilePhone"].Value <string>(); adUserJson.OfficeLocation = parsed["officeLocation"].Value <string>(); adUserJson.PreferredLanguage = parsed["preferredLanguage"].Value <string>(); adUserJson.surname = parsed["surname"].Value <string>(); adUserJson.UserPrincipalName = parsed["userPrincipalName"].Value <string>(); Contact contact = new Contact() { email = guiReceivedUserJSONModel.Email, objectId = adUserJson.Id, firstName = adUserJson.GivenName, lastName = adUserJson.surname, phoneNumber = adUserJson.MobilePhone }; db.Contacts.Add(contact); Tenant tenant = new Tenant() { housingUnitId = 0, genderId = guiReceivedUserJSONModel.GenderId, contactId = contact.contactId, batchId = batchId, hasKey = false, moveInDate = default(DateTime), hasMoved = false }; db.Tenants.Add(tenant); db.SaveChanges(); EMailHelper eMailHelper = new EMailHelper(); eMailHelper.SendMail(contact.email, "Username: "******"\n" + "Password: " + graphUser.PasswordProfile.Password); return(true); } catch { return(false); } }