/// <summary> /// Handle success notification /// </summary> /// <param name="runLevel"></param> /// <param name="renewal"></param> internal void NotifySuccess(RunLevel runLevel, Renewal renewal) { // Do not send emails when running interactively _log.Information(LogType.All, "Renewal for {friendlyName} succeeded", renewal.LastFriendlyName); if (runLevel.HasFlag(RunLevel.Unattended) && _settings.Notification.EmailOnSuccess) { _email.Send( "Certificate renewal completed", $"<p>Certificate <b>{renewal.LastFriendlyName}</b> succesfully renewed.</p> {NotificationInformation(renewal)}", MessagePriority.NonUrgent); } }
/// <summary> /// Handle success notification /// </summary> /// <param name="runLevel"></param> /// <param name="renewal"></param> internal void NotifySuccess(RunLevel runLevel, Renewal renewal) { // Do not send emails when running interactively _log.Information(true, "Renewal for {friendlyName} succeeded", renewal.LastFriendlyName); if (runLevel.HasFlag(RunLevel.Unattended) && Properties.Settings.Default.EmailOnSuccess) { _email.Send( "Certificate renewal completed", $"<p>Certificate <b>{renewal.LastFriendlyName}</b> succesfully renewed.</p> {NotificationInformation(renewal)}", MailPriority.Low); } }
private async Task NotifyCustomerOfSuccess(Customer customer, int orderId, DateTime orderEta) { var message = string.Format("Dear {0} {1}, Your order {2} has been shipped and expected to arrive at: {3}", customer.FirstName, customer.Surname, orderId, orderEta); await EmailClient.Send(customer.EmailAddress, "Order sent", message); }
public void SendPasswordNotice(string password, string changeDate) { Log.DebugWriteLine("The settings file already exists, sending the current password via email."); try { string currentDatetime = DateTime.Now.ToString("dd/MM/yyyy - HH:mm"); StringBuilder body = new StringBuilder(); body.AppendLine(string.Format("The RPIMash unit has booted at {0}\n", currentDatetime)); body.AppendLine(string.Format("The current public password is: {0}", password)); body.AppendLine(string.Format("The next change will occur at ~{0}", changeDate)); var mail = new MailMessage(MailFrom, MailTo) { Subject = string.Format("[PASS] Public Ruckus password information"), Body = body.ToString() }; EmailClient.Send(mail); } catch (Exception e) { ErrorHandler.LogError(e); } }
public HttpResult Patch(PatchMessage request) { if (request.Id <= 0) { return(new HttpResult(HttpStatusCode.NotFound, "Message was not found.")); } // Only resend e-mail supported by patch at the moment if (!request.ResendEmail) { return(new HttpResult(HttpStatusCode.NotImplemented, "Message PATCH only supports resending e-mail.")); } var ds = new DataStore(); var message = ds.GetMessage(request.Id); var client = new EmailClient(); var emailResult = client.Send(message); if (emailResult.Success) { ds.InsertMessageStatus(request.Id, 2); } else { ds.InsertMessageStatus(request.Id, 3, emailResult.Message, emailResult.SmtpException); return(new HttpResult(HttpStatusCode.OK, "Message failed to send.")); } return(new HttpResult(HttpStatusCode.OK, "Message was updated.")); }
public HttpResult Put(UpdateMessage request) { // PUT does not support create if (request.Id <= 0) { return(new HttpResult(HttpStatusCode.NotFound, "Message was not found.")); } var ds = new DataStore(); ds.UpdateMessage(request); // Resend e-mail if requested if (request.ResendEmail) { var savedMesssage = ds.GetMessage(request.Id); var client = new EmailClient(); var emailResult = client.Send(savedMesssage); if (emailResult.Success) { ds.InsertMessageStatus(request.Id, 2); } else { ds.InsertMessageStatus(request.Id, 3, emailResult.Message, emailResult.SmtpException); return(new HttpResult(HttpStatusCode.OK, "Message was updated, but e-mail failed to send.")); } } return(new HttpResult(HttpStatusCode.OK, "Message was updated.")); }
private void SendContactUsEmail() { Store store = AbleContext.Current.Store; StoreSettingsManager settings = store.Settings; MailMessage mailMessage = new MailMessage(); if (string.IsNullOrEmpty(SendTo)) { mailMessage.To.Add(settings.DefaultEmailAddress); } else { mailMessage.To.Add(SendTo); } mailMessage.From = new System.Net.Mail.MailAddress(Email.Text); mailMessage.Subject = this.Subject; mailMessage.Body += "Name: " + FirstName.Text + " " + LastName.Text + Environment.NewLine; if (!String.IsNullOrEmpty(Company.Text)) { mailMessage.Body += "Company: " + Company.Text + Environment.NewLine; } mailMessage.Body += "Email: " + Email.Text + Environment.NewLine; mailMessage.Body += "Phone: " + Phone.Text + Environment.NewLine; mailMessage.Body += "Comment: " + Environment.NewLine + Comments.Text; //Add attachments List <string> fileAttachments = (List <string>)Session["UPLOADED"]; if (fileAttachments != null) { foreach (var attachment in fileAttachments) { mailMessage.Attachments.Add(new Attachment(attachment)); } } mailMessage.BodyEncoding = System.Text.Encoding.UTF8; mailMessage.IsBodyHtml = false; mailMessage.Priority = System.Net.Mail.MailPriority.High; SmtpSettings smtpSettings = SmtpSettings.DefaultSettings; try { EmailClient.Send(mailMessage); FailureMessage.Visible = false; SuccessMessage.Visible = true; } catch (Exception exp) { Logger.Error("ContactUs Control Exception: Exp" + Environment.NewLine + exp.Message); FailureMessage.Visible = true; SuccessMessage.Visible = false; } MessagePanel.Visible = true; FAQFormPanel.Visible = false; }
static void SendEmail() { EmailClient emailClient = new EmailClient(); emailClient.ConstructEmail(new string[] { "*****@*****.**" }, "Oculus Rift Found", "GO ORDER IT NOW!"); emailClient.Send(); }
/// <summary> /// Sends a notification email about an upcoming password change. /// </summary> /// <param name="password">The password that is going to be used in the upcoming change.</param> /// <param name="changeDate">The date & time that the password will be changed.</param> /// <returns>True if the email sent successfully or false if otherwise.</returns> public bool SendPasswordWarning(string password, string changeDate) { Log.DebugWriteLine(string.Format("Password changing to {0} at {1} - sending email.", password, changeDate)); try { // Initialize a StringBuilder that will be used as the body of the email. StringBuilder body = new StringBuilder(); body.AppendLine("The public password will soon be changed, below are the new details you will require:\n"); body.AppendLine(string.Format("New Password: {0}", password)); body.AppendLine(string.Format("This password will be in effect at ~{0}", changeDate)); // Initializes the MailMessage containing the subject/body. var mail = new MailMessage(MailFrom, MailTo) { Subject = string.Format("[PASS] The public password will be changing at {0}", changeDate), Body = body.ToString() }; // Sends our email using the SMTP client configured in the constructor. EmailClient.Send(mail); return(true); } catch (Exception ex) { ErrorHandler.LogError(ex); return(false); } }
/// <summary> /// Sends a notification email about a recent password change. /// </summary> /// <param name="password">The new password that is currently in use.</param> /// <param name="changeDate">The date & time of the password change.</param> /// <returns>True if the email sent successfully or false if otherwise.</returns> public bool SendPasswordUpdate(string password, string changeDate) { Log.DebugWriteLine(string.Format("Password changed to {0}, next update at {1} - sending email.", password, changeDate)); try { string currentDatetime = DateTime.Now.ToString("dd/MM/yyyy - HH:mm"); // Initialize a StringBuilder that will be used as the body of the email. StringBuilder body = new StringBuilder(); body.AppendLine(string.Format("The public password has been changed to: {0}\n", password)); body.AppendLine(string.Format("Time of change:\t{0}", currentDatetime)); body.AppendLine(string.Format("The next change will occur at ~{0}", changeDate)); // Initializes the MailMessage containing the subject/body. var mail = new MailMessage(MailFrom, MailTo) { Subject = string.Format("[PASS] The public password has been changed to {0}", password), Body = body.ToString() }; // Sends our email using the SMTP client configured in the constructor. EmailClient.Send(mail); return(true); } catch (Exception ex) { // Logs the exception. ErrorHandler.LogError(ex); return(false); } }
public void SendEmail() { EmailClient client = CreateEmailClient(); #region Snippet:Azure_Communication_Email_Send // Create the email content var emailContent = new EmailContent("This is the subject"); emailContent.PlainText = "This is the body"; // Create the recipient list var emailRecipients = new EmailRecipients( new List <EmailAddress> { new EmailAddress( //@@ email: "<recipient email address>" //@@ displayName: "<recipient displayname>" /*@@*/ email: TestEnvironment.ToEmailAddress, /*@@*/ displayName: "Customer Name") }); // Create the EmailMessage var emailMessage = new EmailMessage( //@@ sender: "<Send email address>" // The email address of the domain registered with the Communication Services resource /*@@*/ sender: TestEnvironment.AzureManagedFromEmailAddress, emailContent, emailRecipients); SendEmailResult sendResult = client.Send(emailMessage); Console.WriteLine($"Email id: {sendResult.MessageId}"); #endregion Snippet:Azure_Communication_Email_Send Assert.False(string.IsNullOrEmpty(sendResult.MessageId)); }
private async Task NotifyCustomerOfDelay(Customer customer, Order order) { var message = string.Format("Dear {0} {1}, Your order {2} cannot be delivered - please contact customer support", customer.FirstName, customer.Surname, order.ID); await EmailClient.Send(customer.EmailAddress, "Failed delivering order", message); }
// Using this for mainly test purposes to confirm the email sending works static void Main(string[] args) { EmailClient emailClient = new EmailClient(); emailClient.ConstructEmail(new List <string>(new string[] { "*****@*****.**" }), "Hello from visual studio!", "testing this email refactor"); emailClient.Send(); }
public ActionResult NewRequest(string orgName, string email, string comment, string type) { var body = "Запрос от организации " + orgName + ", email: " + email + ", комментарий: " + comment + ", кнопка" + type; var client = new EmailClient(); client.Send("*****@*****.**", body, "Запрос с лэндинга " + DateTime.Now.ToString()); return(Json(new { isAuthorized = true, isSuccess = true })); }
protected void SendButton_Click(Object sender, EventArgs e) { try { EmailTemplate emailTemplate = EmailTemplateDataSource.Load(AbleContext.Current.Store.Settings.AbandonedBasketAlertEmailTemplateId); string fromAddress = emailTemplate.FromAddress; if (fromAddress == "merchant") { fromAddress = AbleContext.Current.Store.Settings.DefaultEmailAddress; } MailMessage mailMessage = new MailMessage(); mailMessage.To.Add(new MailAddress(ToEmail.Text)); mailMessage.From = new MailAddress(fromAddress); string[] ccAddresses = emailTemplate.CCList.Split(','); if (ccAddresses != null && ccAddresses.Length > 0) { foreach (string ccAddress in ccAddresses) { if (ValidationHelper.IsValidEmail(ccAddress)) { mailMessage.CC.Add(new MailAddress(ccAddress.Trim())); } } } string[] bccAddresses = emailTemplate.BCCList.Split(','); if (bccAddresses != null && bccAddresses.Length > 0) { foreach (string bccAddress in bccAddresses) { if (ValidationHelper.IsValidEmail(bccAddress)) { mailMessage.Bcc.Add(new MailAddress(bccAddress.Trim())); } } } mailMessage.Subject = Subject.Text; mailMessage.IsBodyHtml = emailTemplate.IsHTML; mailMessage.Body = emailTemplate.IsHTML ? HtmlMessageContents.Value : TextMessageContents.Text; EmailClient.Send(mailMessage); SendAlertPanel.Visible = false; ConfirmMessage.Text = string.Format(ConfirmMessage.Text, ToEmail.Text); ConfirmPanel.Visible = true; FinishButton.NavigateUrl += "?ReportDate=" + _basket.User.LastActivityDate.Value.ToShortDateString(); } catch (Exception ex) { ErrorMessage.Text = "Error sending message: " + ex.Message; ErrorMessage.Visible = true; Logger.Error(ex.Message, ex); } }
/// <summary> /// 发送激活邮件 /// </summary> /// <param name="userId"></param> /// <param name="subject"></param> /// <param name="emailContent"></param> /// <param name="toEmail"></param> /// <returns></returns> public OperationResult SendActiveEmail(string userId, string subject, string emailContent, string toEmail) { OperationResult result = new OperationResult(); EmailClient client = new EmailClient(); result.Success = client.Send(subject, toEmail, emailContent); return(result); }
// POST: api/MailSender public IHttpActionResult Post([FromBody] Message message) { //if (message == null) // return NotFound(); EmailClient service = new EmailClient("*****@*****.**", "123456---"); foreach (var recipient in message.Contacts) { service.Send(recipient.MailAddress, message.Subject, message.Body); } return(Ok()); }
/// <summary> /// 重置密码 /// </summary> /// <param name="model">用户信息</param> /// <returns>是否重置成功</returns> public bool ResetPassword(ResetPasswordModel model) { string tempPassword = UserExtentions.RandomPassword(); string title = "[OA]重置密码成功"; string body = "{0},你好。\r\n密码重置成功,密码为{1}。\r\n请及时修改密码。"; if (model == null || (string.IsNullOrEmpty(model.Phone) && string.IsNullOrEmpty(model.Email)) || (!string.IsNullOrEmpty(model.Email) && !model.Email.IsEmail())) { throw new Exception("Invalid reset password request."); } try { //更新用户信息 using (var dbContext = new MissionskyOAEntities()) { //1.查找用户 var entity = dbContext.Users.Where( it => (!string.IsNullOrEmpty(it.Email) && it.Email.Equals(model.Email, StringComparison.InvariantCultureIgnoreCase)) || (!string.IsNullOrEmpty(it.Phone) && it.Phone.Equals(model.Phone, StringComparison.InvariantCultureIgnoreCase))) .FirstOrDefault(); if (entity == null) { throw new KeyNotFoundException("cannot find user."); } //2.更新用户密码 entity.Password = (new MD5Cryptology()).Encrypt(tempPassword); entity.Status = (int)AccountStatus.RestPassword; dbContext.SaveChanges(); //3.发送邮件 EmailClient.Send(new List <string> { entity.Email }, null, title, string.Format(body, entity.EnglishName, tempPassword)); } return(true); } catch (Exception e) { throw e; } }
public void SendEmail_InvalidParams_Throws() { EmailClient emailClient = CreateEmailClient(); if (IsAsync) { Assert.ThrowsAsync <ArgumentNullException>(async() => await emailClient.SendAsync(null)); } else { Assert.Throws <ArgumentNullException>(() => emailClient.Send(null)); } }
public static bool SendEMail(string email, string Subject, string Content) { var msg = new MailMessage(); string bodyHtml = Content; msg.IsBodyHtml = true; msg.Body = bodyHtml; msg.Subject = Subject; msg.To.Add(email); var iSSend = EmailClient.Send(msg); return(iSSend); }
/// <summary> /// Sends a status email containing boot times and device information. /// </summary> /// <param name="devices">Devices class that contains required device methods/information.</param> /// <param name="settings">Settings class containing all required settings and parameters.</param> /// <param name="isBoot">Boolean value that indicates if this is the softwares initial launch.</param> /// <returns>True if the email sent successfully or false if otherwise.</returns> public bool SendStatusEmail(Devices devices, Settings settings, bool isBoot) { Log.DebugWriteLine(string.Format("Sending status email to {0}, [BOOT={1}]", MailTo, isBoot)); try { string currentDatetime = DateTime.Now.ToString("dd/MM/yyyy - HH:mm"); // Initialize a StringBuilder that will be used as the body of the email. StringBuilder body = new StringBuilder(); body.AppendLine(string.Format("Current time:\t{0}", currentDatetime)); body.AppendLine(string.Format("Last boot:\t\t{0}", settings.LastBootTime ?? "N/A (This appears to be the first boot)")); body.AppendLine("\n[DEVICES]:\n"); // Iterate through devices and output the information for each device. foreach (var device in devices.DeviceList) { body.AppendLine(string.Format("{0} ({1}) is {2}", device.Name, device.IP, device.IsOnline ? "online" : "OFFLINE")); } // If the current password is set, display it. if (settings.CurrentPassword != null) { body.AppendLine(string.Format("The current password is {0}", settings.CurrentPassword)); } // Initializes the MailMessage containing the subject/body. var mail = new MailMessage(MailFrom, MailTo) { Subject = isBoot ? string.Format("[BOOT] {0} has booted at {1}", settings.CurrentDeviceName, currentDatetime) : string.Format("[MASH] {0} status report", settings.CurrentDeviceName), Body = body.ToString() }; // Sends our email using the SMTP client configured in the constructor. EmailClient.Send(mail); return(true); } catch (Exception ex) { // Logs the exception. ErrorHandler.LogError(ex); return(false); } }
/// <summary> /// Sends an email containing information about a recent exception. /// </summary> /// <param name="errorLog">The errorlog of the exception.</param> public void SendExceptionDetails(StringBuilder errorLog) { Log.DebugWriteLine("Sending email containing exception information for debugging."); // Initializes the MailMessage containing the subject/body. var mail = new MailMessage(MailFrom, MailTo) { Subject = "[ERROR] An exception has occured!", Body = errorLog.ToString() }; // Sends our email using the SMTP client configured in the constructor. EmailClient.Send(mail); }
public void SendEmailWithAttachment() { EmailClient client = CreateEmailClient(); var emailContent = new EmailContent("This is the subject"); emailContent.PlainText = "This is the body"; var emailRecipients = new EmailRecipients( new List <EmailAddress> { new EmailAddress( //@@ email: "<recipient email address>" //@@ displayName: "<recipient displayname>" /*@@*/ email: TestEnvironment.ToEmailAddress, /*@@*/ displayName: "Customer Name") }); #region Snippet:Azure_Communication_Email_Send_With_Attachments // Create the EmailMessage var emailMessage = new EmailMessage( //@@ sender: "<Send email address>" // The email address of the domain registered with the Communication Services resource /*@@*/ sender: TestEnvironment.AzureManagedFromEmailAddress, emailContent, emailRecipients); #if SNIPPET var filePath = "<path to your file>"; var attachmentName = "<name of your attachment>" EmailAttachmentType attachmentType = EmailAttachmentType.Txt; #endif // Convert the file content into a Base64 string #if SNIPPET byte[] bytes = File.ReadAllBytes(filePath); string attachmentFileInBytes = Convert.ToBase64String(bytes); #else string attachmentName = "Attachment.txt"; EmailAttachmentType attachmentType = EmailAttachmentType.Txt; var attachmentFileInBytes = "VGhpcyBpcyBhIHRlc3Q="; #endif var emailAttachment = new EmailAttachment(attachmentName, attachmentType, attachmentFileInBytes); emailMessage.Attachments.Add(emailAttachment); SendEmailResult sendResult = client.Send(emailMessage); #endregion Snippet:Azure_Communication_Email_Send_With_Attachments }
/// <summary> /// Handle created notification /// </summary> /// <param name="runLevel"></param> /// <param name="renewal"></param> internal async Task NotifyCreated(Renewal renewal, IEnumerable <MemoryEntry> log) { // Do not send emails when running interactively _log.Information( LogType.All, "Certificate {friendlyName} created", renewal.LastFriendlyName); if (_settings.Notification.EmailOnSuccess) { await _email.Send( $"Certificate {renewal.LastFriendlyName} created", @$ "<p>Certificate <b>{HttpUtility.HtmlEncode(renewal.LastFriendlyName)}</b> succesfully created.</p> {NotificationInformation(renewal)} {RenderLog(log)}", MessagePriority.Normal); }
public void InvalidEmailMessage_Throws_ArgumentException(EmailMessage emailMessage, string errorMessage) { EmailClient emailClient = CreateEmailClient(HttpStatusCode.BadRequest); ArgumentException?exception = null; if (IsAsync) { exception = Assert.ThrowsAsync <ArgumentException>(async() => await emailClient.SendAsync(emailMessage)); } else { exception = Assert.Throws <ArgumentException>(() => emailClient.Send(emailMessage)); } Assert.IsTrue(exception?.Message.Contains(errorMessage)); }
protected void SendButton_Click(object sender, EventArgs e) { if (Page.IsValid) { System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage(); mailMessage.From = new System.Net.Mail.MailAddress(FromAddress.Text); mailMessage.To.Add(SendTo.Text); mailMessage.Subject = StringHelper.StripHtml(Subject.Text); mailMessage.Body = StringHelper.StripHtml(Message.Text); mailMessage.IsBodyHtml = false; EmailClient.Send(mailMessage); SentMessage.Text = String.Format(SentMessage.Text, SendTo.Text); SentMessage.Visible = true; SendTo.Text = string.Empty; } }
private void SendConfirmationEmail() { int emailTemplateId = ConfirmationEmailTemplateId; // use default if none is provided if (emailTemplateId == 0) { emailTemplateId = AbleContext.Current.Store.Settings.ContactUsConfirmationEmailTemplateId; } EmailTemplate template = EmailTemplateDataSource.Load(emailTemplateId); if (template != null) { template.Parameters.Add("user", AbleContext.Current.User); template.Parameters.Add("store", AbleContext.Current.Store); try { // populate the email for anonymous user account, it is needed for email message generation ('customer' parameter) if (AbleContext.Current.User.IsAnonymousOrGuest) { AbleContext.Current.User.Email = Email.Text; } MailMessage[] messages = template.GenerateMailMessages(); foreach (MailMessage msg in messages) { msg.To.Clear(); msg.To.Add(new MailAddress(this.Email.Text)); EmailClient.Send(msg); } FailureMessage.Visible = false; SuccessMessage.Visible = true; } catch (Exception exp) { Logger.Error("ContactUs Control Exception: " + Environment.NewLine + exp.Message); FailureMessage.Visible = true; SuccessMessage.Visible = false; } MessagePanel.Visible = true; FAQFormPanel.Visible = false; } }
private static void SendEmail(ReportModel report, UserModel receiver, UserModel ccUser, string reportPath) { if (receiver == null) { Log.Error("邮件接收人无效。"); throw new KeyNotFoundException("邮件接收人无效。"); } //发送邮件及附件 var attachments = new List <string>(); attachments.Add(reportPath); EmailClient.Send(new List <string> { receiver.Email }, (ccUser == null ? null : new List <string> { ccUser.Email }), report.Name, string.Format("生成报表{0}成功。请查看附件。", report.Name), attachments); }
public void BadRequest_ThrowsException() { EmailClient emailClient = CreateEmailClient(HttpStatusCode.BadRequest); EmailMessage emailMessage = DefaultEmailMessage(); RequestFailedException?exception = null; if (IsAsync) { exception = Assert.ThrowsAsync <RequestFailedException>(async() => await emailClient.SendAsync(emailMessage)); } else { exception = Assert.Throws <RequestFailedException>(() => emailClient.Send(emailMessage)); } Assert.AreEqual((int)HttpStatusCode.BadRequest, exception?.Status); }
private static void SendEmail(ReportModel report, string token, string reportPath) { //当前用户 UserModel user = (new UserTokenService()).GetMemberByToken(token); if (user == null) { Log.Error("找不到用户。"); throw new KeyNotFoundException("找不到用户。"); } //发送邮件及附件 var attachments = new List <string>(); attachments.Add(reportPath); EmailClient.Send(new List <string> { user.Email }, null, report.Name, string.Format("生成报表{0}成功。请查看附件。", report.Name), attachments); }