public static bool IsValidEmailRequest(EmailSendRequest request) { bool hasTo = request.To != null; bool hasTemplate = !string.IsNullOrWhiteSpace(request.Template); return(hasTo && hasTemplate); }
public async Task <IActionResult> SendEmail([FromBody] EmailSendRequest request) { var emailSent = await _notificationService.BuildAndSendEmail(request); if (!emailSent.Success) { return(ApiResponse.GetActionResult(ResultStatus.Error400, new Response <EmailFailureResponse>() { Data = new EmailFailureResponse() { Success = false, TrackingId = emailSent.TrackingId, Errors = emailSent.Errors } })); } return(ApiResponse.GetActionResult(ResultStatus.Ok200, new Response <EmailSuccessfullySentResponse>() { Data = new EmailSuccessfullySentResponse() { Success = true, TrackingId = emailSent.TrackingId, Message = emailSent.Message, SeSMessageId = emailSent.SesMessageId } })); }
public EmailSendResponse SendCriminalRecords(EmailSendRequest request) { var response = new EmailSendResponse(); try { if (request.Age.Minimum < 0 || request.Age.Maximum < 0 || request.Age.Maximum < request.Age.Minimum) { throw new ArgumentOutOfRangeException("Age Range Validation Error"); } if (request.Weight.Minimum < 0 || request.Weight.Maximum < 0 || request.Weight.Maximum < request.Weight.Minimum) { throw new ArgumentOutOfRangeException("Weight Range Validation Error"); } if (request.Height.Minimum < 0 || request.Height.Maximum < 0 || request.Height.Maximum < request.Height.Minimum) { throw new ArgumentOutOfRangeException("Height Range Validation Error"); } var searchResult = SQLHelper.GetFilteredResult(request.Name, request.Age, request.Height, request.Weight, request.Nationality, request.Sex); if (searchResult.Count == 0) { throw new ArgumentNullException("No Result"); } var files = PDFHelper.GeneratePdfFiles(searchResult); SendEmailTask(request.Email, files); response.Result = true; } catch (Exception ex) { //TODO: Log Exception } return(response); }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Process the email send request message described by msg. </summary> /// /// <param name="msg"> The message. </param> /// /// <returns> True if it succeeds, false if it fails. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// bool ProcessEmailSendRequestMessage(EmailSendRequest msg) { Console.WriteLine("Received Email Send Request Message"); RILogManager.Default?.SendInformation("Received Email Send Request Message"); SendEmail(msg); return(true); }
public async Task <ApiResponse> SendResetPasswordConfirmationEmail(EmailSendRequest request) { var user = request.User; var code = await _userManager.GeneratePasswordResetTokenAsync(user); var callbackUrl = GetCallbackUrl(user.Id, code, _client.ResetPasswordPath, request.ClientUrl); var emailSendingSuccess = await _emailService.SendMessageWithPurpose(new MailModel() { ToEmail = user.Email, Subject = EmailPurpose.ResetPassword.ToString(), }, EmailPurpose.ResetPassword, new ResetPasswordViewModel() { ResetPasswordUrl = callbackUrl, UserName = user.UserName, }); if (!emailSendingSuccess) { return(new ApiResponse( new ApiError() { ErrorCode = ErrorCode.EmailSendFailed, ErrorMessage = ErrorCode.EmailSendFailed.GetDescription(), })); } return(ApiResponse.Success()); }
public async Task <ApiResponse> SendResetPasswordConfirmationEmail(EmailSendRequest request) { return(new ApiResponse() { IsSuccess = SendSuccessfully }); }
public async Task Send(EmailSendRequest model) { SendGridClient client = new SendGridClient(_apiKey.SendGridAppKey.ToString()); EmailAddress sender = new EmailAddress(model.From, model.Sender); EmailAddress recipient = new EmailAddress(model.To, model.Recipient); var msg = MailHelper.CreateSingleEmail(sender, recipient, model.Subject, model.PlainTextContent, model.HtmlContent); var response = await client.SendEmailAsync(msg); }
public async Task Send(EmailSendRequest request) { if (!TryValidateModel(request)) { throw new ArgumentException(nameof(request)); } try { var partnerSmtpSettings = _partnerSmtpSettings[request.FromPartnerId, "smtp"]; var message = new MimeMessage { Subject = request.Message.Subject }; message.From.Add(new MailboxAddress(Encoding.UTF8, partnerSmtpSettings.FromDisplayName, partnerSmtpSettings.FromEmailAddress)); message.To.Add(new MailboxAddress(Encoding.UTF8, request.To.DisplayName, request.To.EmailAddress)); var bodyBuilder = new BodyBuilder { TextBody = request.Message.TextBody, HtmlBody = request.Message.HtmlBody }; if (null != request.Message.Attachments) { foreach (var attachment in request.Message.Attachments) { bodyBuilder.Attachments.Add(attachment.FileName, attachment.Content, ContentType.Parse(ParserOptions.Default, attachment.MimeType)); } } message.Body = bodyBuilder.ToMessageBody(); using (var smtpClient = new SmtpClient()) { await smtpClient.ConnectAsync(partnerSmtpSettings.SmtpHost, partnerSmtpSettings.Port ?? 0, partnerSmtpSettings.EnableSsl?SecureSocketOptions.SslOnConnect : SecureSocketOptions.Auto); await smtpClient.AuthenticateAsync(partnerSmtpSettings.UserName, partnerSmtpSettings.Password); await smtpClient.SendAsync(message); } } catch (Exception ex) { await _log.WriteFatalErrorAsync(nameof(EmailSender), nameof(Startup), nameof(Send), ex, DateTime.UtcNow); throw; } }
public static Task SendEmailPasswordResetAsync(this INotificationSender notificationSender, string email, string link) { EmailSendRequest request = new EmailSendRequest { ActionUrl = link, TextBeforeAction = "You requested for a password reset. Click the button below and choose a new password.", TextAfterAction = "Do not share your password with anyone." }; return(notificationSender.SendEmailAsync(email, "d-d0224f347d57420bb39a025787b6443a", request)); }
public async Task <IActionResult> Get([FromRoute] string id, [FromQuery(Name = "receiversToTest")] string receiversToTest = null) { bool isValidId = Guid.TryParse(id, out Guid guid); if (!isValidId) { return(new BadRequestObjectResult("The id specified had an invalid format.")); } LogEntry logEntry = await _loggingService.GetAsync(guid); bool noLogEntryFound = logEntry == null; if (noLogEntryFound) { return(new BadRequestObjectResult("No logs found for the id provided.")); } JObject content = JObject.Parse(logEntry.Content); JObject personalContent = JObject.Parse(logEntry.PersonalContent); EmailSendRequest request = new EmailSendRequest() { Content = content, PersonalContent = personalContent, Template = logEntry.Template, To = new string[0] }; OkObjectResult actionResult = await _emailPreviewController.Post(request) as OkObjectResult; EmailPreviewResponse previewResponse = (EmailPreviewResponse)actionResult.Value; string[] receiversToTestArray = RestUtility.GetArrayQueryParam(receiversToTest); bool hasReceiversToTestArray = receiversToTestArray != null && receiversToTestArray.Length > 0; bool isReceiversMatch; if (hasReceiversToTestArray) { isReceiversMatch = TestReceiversMatch(receiversToTestArray, logEntry); } else { isReceiversMatch = false; } SentEmailResponse response = SentEmailResponseFactory.Create(logEntry, previewResponse, isReceiversMatch); return(new OkObjectResult(response)); }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Executes the start action. </summary> /// /// <param name="host"> The host. This may be null. </param> /// /// <returns> True if it succeeds, false if it fails. </returns> //////////////////////////////////////////////////////////////////////////////////////////////////// public new bool OnStart([CanBeNull] HostControl host) { Start(host); Subscribe(); EmailSendRequest m = new EmailSendRequest(); m.Subject = "Test"; m.To = "*****@*****.**"; m.From = "*****@*****.**"; m.Body = "This is a test of the email microservice system"; SendEmail(m); return(true); }
public static Task SendEmailPasswordResetAsync(this INotificationSender notificationSender, string email, string link) { EmailSendRequest request = new EmailSendRequest { Subject = "LUDUSTACK - Password Reset", ActionUrl = link, ActionText = "Reset your password", TextBeforeAction = "You requested for a password reset. Click the button below and choose a new password.", TextAfterAction = "Do not share your password with anyone." }; return(notificationSender.SendEmailAsync(email, "d-e9b748bc725c48b18f00b3d1cc88c790", request)); }
public async Task RegisterEmail(string recipient, Guid token) { EmailSendRequest emailModel = new EmailSendRequest(); emailModel.From = "*****@*****.**"; emailModel.Sender = "admin"; emailModel.Subject = "Email Confirmation"; emailModel.To = recipient; emailModel.Recipient = recipient; emailModel.HtmlContent = @"<a href=""https://*****:*****@"""\>Confirm email here</a><br/>"; emailModel.PlainTextContent = "Please click the link to confirm your email"; await Send(emailModel); }
public static Task SendEmailConfirmationAsync(this INotificationSender notificationSender, string email, string link) { EmailSendRequest request = new EmailSendRequest { ActionUrl = link, ActionText = "Confirm your email", Greeting = "Hi there,", TextBeforeAction = "You just registered yourself at INDIEVISIBLE community. Now you need to confirm your email.", TextAfterAction = "After confirmation you will be able to enjoy interacting with other fellow game developers.", ByeText = "And welcome to YOUR community." }; return(notificationSender.SendEmailAsync(email, "d-186b082218114c889a72a197c6ec2fa3", request)); }
public ActionResult <SuccessResponse> SendEmail(EmailSendRequest model) { try { _emailService.Send(model); SuccessResponse resp = new SuccessResponse(); return(Ok200(resp)); } catch (Exception ex) { Logger.LogError(ex.ToString()); return(StatusCode(500, new ErrorResponse(ex.Message))); } }
public static Task SendEmailApplicationAsync(this INotificationSender notificationSender, string emailPoster, string emailApplicant, string link) { EmailSendRequest request = new EmailSendRequest { ActionUrl = link, ActionText = "Go to the job position", Greeting = "Hi there", TextBeforeAction = string.Format("We have great news! Recently you posted a job position on the INDIEVISIBLE Jobs and now someone applied to the job position you posted. The applicant's email is {0}", emailApplicant), TextAfterAction = "Log in to the INDIEVISIBLE platform to evaluate the applicants.", ByeText = "Thank you for helping the game development industry. We hope you find a good collaborator so we all can grow together." }; return(notificationSender.SendEmailAsync(emailPoster, "d-826fd97ae44d409f85408d64918c7be8", request)); }
public static Task SendEmailApplicationAsync(this INotificationSender notificationSender, string email, string emailApplicant, string link) { EmailSendRequest request = new EmailSendRequest { Subject = "LUDUSTACK - New Job Applicant", ActionUrl = link, ActionText = "Go to the job position", Greeting = "Hi there", TextBeforeAction = string.Format("We have great news! Recently you posted a job position on the LUDUSTACK Jobs and now someone applied to the job position you posted. The applicant's email is {0}", emailApplicant), TextAfterAction = "Log in to the LUDUSTACK platform to evaluate the applicants.", ByeText = "Thank you for helping the game development industry. We hope you find a good collaborator so we all can grow together." }; return(notificationSender.SendEmailAsync(email, "d-e9b748bc725c48b18f00b3d1cc88c790", request)); }
public static Task SendEmailConfirmationAsync(this INotificationSender notificationSender, string email, string link) { EmailSendRequest request = new EmailSendRequest { Subject = "LUDUSTACK - Email Verification", ActionUrl = link, ActionText = "Confirm your email", Greeting = "Hi there,", TextBeforeAction = "You just registered yourself at LUDUSTACK community. Now you need to confirm your email.", TextAfterAction = "After confirmation you will be able to enjoy interacting with other fellow game developers.", ByeText = "And welcome to YOUR community." }; return(notificationSender.SendEmailAsync(email, "d-e9b748bc725c48b18f00b3d1cc88c790", request)); }
public static Task SendGiveawayEmailConfirmationAsync(this INotificationSender notificationSender, string email, string link, string giveawayName) { EmailSendRequest request = new EmailSendRequest { Subject = string.Format("{0} - Email Verification", giveawayName), ActionUrl = link, ActionText = "Confirm your email", Greeting = "Hi there,", TextBeforeAction = string.Format("You just entered a giveaway ({0}). Now you need to confirm your email.", giveawayName), TextAfterAction = "After confirmation you receive an extra entry.", ByeText = "See you there!." }; return(notificationSender.SendEmailAsync(email, "d-e9b748bc725c48b18f00b3d1cc88c790", request)); }
public async Task <IActionResult> Get([FromQuery] EmailSendRequestRaw request) { EmailSendRequest sendRequest = EmailSendRequestFactory.Convert(request); OkObjectResult actionResult = await Post(sendRequest) as OkObjectResult; EmailPreviewResponse previewResponse = (EmailPreviewResponse)actionResult.Value; return(new ContentResult() { Content = previewResponse.Preview, ContentType = "text/html", StatusCode = 200 }); }
public void SendCriminalRecordsTest() { var request = new EmailSendRequest { Name = "", Age = new DataRange <int>(0, 2000), Height = new DataRange <decimal>(0, 3000), Weight = new DataRange <decimal>(0, 3000), Nationality = "", Sex = EmailSendRequest.SexType.All, Email = "*****@*****.**" }; var emailservice = new EmailService(); var response = emailservice.SendCriminalRecords(request); Assert.IsTrue(response.Result, "Response Is Not OK"); }
/// <summary> /// Sends an email using sendgrid based on the EmailSendRequest model provided in request /// </summary> /// <param name="request">The EmailSendRequest that contains subject, destination, and content</param> /// <returns>The HTTP status code returned from the sendgrid api</returns> public async Task <System.Net.HttpStatusCode> SendEmail(EmailSendRequest request) { try { var apiKey = _emailConfig.SendGridApiKey; var client = new SendGridClient(apiKey); var from = new EmailAddress(_emailConfig.FromAddress, _emailConfig.FromUser); var subject = request.Subject; var to = new EmailAddress(request.Recipient); var htmlContent = request.Content; var msg = MailHelper.CreateSingleEmail(from, to, subject, null, htmlContent); var response = await client.SendEmailAsync(msg); return(response.StatusCode); } catch (Exception ex) { _logger.LogError(ex, "Exception {ex.Message} encountered when trying to send email " + "with inputs Recipient: {request.Recipient}, Subject: {request.Subject}", ex.Message, request.Recipient, request.Subject); return(System.Net.HttpStatusCode.InternalServerError); } }
public async Task <SendEmailResult> BuildAndSendEmail(EmailSendRequest request) { var trackingId = Guid.NewGuid(); try { var templateData = _templatingService.BuildTemplateData(request.TemplateData); var(subject, html, plainText) = _templatingService.BuildEmailSubjectAndBody(DetermineTemplateToUse(request.TemplateChoice), templateData); var emailSent = await _emailService.BuildAndSendEmail(request.From, request.To, subject, html, plainText); emailSent.TrackingId = trackingId; return(emailSent); } catch (Exception ex) { Console.WriteLine(ex.Message, ex); throw new Exception(ex.Message, ex); } }
private EmailSendResponse SendQuery(SearchModel model) { var c = new EmailServiceClient(); var request = new EmailSendRequest { Email = User.Identity.Name, Name = model.Name, Nationality = model.Nationality, Sex = (EmailSendRequest.SexType)(int) model.Sex, Age = new DataRangeOfint { Maximum = model.MaxAge, Minimum = model.MinAge }, Height = new DataRangeOfdecimal { Maximum = model.MaxHeight, Minimum = model.MinHeight }, Weight = new DataRangeOfdecimal { Maximum = model.MaxWeight, Minimum = model.MinWeight } }; var response = c.SendCriminalRecords(request); return(response); }
public void SendEmail(EmailSendRequest emailSendRequest) { this.EmailMessageHandler.HandleEvent(emailSendRequest); }
public async Task <IActionResult> SendEmail(EmailSendRequest emailRequest) { var responseCode = await _emailSender.SendEmail(emailRequest); return(responseCode == System.Net.HttpStatusCode.Accepted ? Ok() : StatusCode(int.Parse(responseCode.ToString()))); }
public async Task <IActionResult> Post([FromBody] EmailSendRequest request) { bool isValidEmailRequest = EmailSendRequestFactory.IsValidEmailRequest(request); if (!isValidEmailRequest) { return(new BadRequestObjectResult("Invalid email payload.")); } MailAddress[] toAddresses; try { toAddresses = request.To.Select(t => new MailAddress(t)).ToArray(); } catch (Exception exception) { return(new BadRequestObjectResult($"Invalid format of recipient email {request.To}.")); } bool hasAtLeastOneEmailAddress = toAddresses.Length > 0; if (!hasAtLeastOneEmailAddress) { return(new BadRequestObjectResult("No receivers specified. Need at least one.")); } Template template = TemplateUtility.GetTemplateByName(_emailConfiguration, request.Template); bool isInvalidTemplate = template == null; if (isInvalidTemplate) { return(new BadRequestObjectResult($"A template with the name {request.Template} does not exist.")); } JObject fullContent = JsonUtility.GetMergedJson(request.Content, request.PersonalContent); EmailViewModel emailViewModel = new EmailViewModel() { TemplateName = template.Name, Content = fullContent }; string rawHtml = await _htmlGeneratorService.GetRawHtmlAsync("Email/Index", emailViewModel); bool hasNoRawHtml = rawHtml == null; if (hasNoRawHtml) { return(new BadRequestObjectResult("Internal error.")); } Email email = new Email(toAddresses, template.Subject, ContentType.TEXT_HTML, rawHtml); string emailServiceId; try { emailServiceId = await _emailService.SendEmailAsync(email); } catch (Exception e) { return(new BadRequestObjectResult("Failed to send email.")); } try { string[] receiverEmails = email.To.Select(t => t.ToString()).ToArray(); await _emailLoggingService.LogAsync(emailServiceId, receiverEmails, template.Name, request.PersonalContent, request.Content); return(new OkResult()); } catch (Exception e) { return(new BadRequestObjectResult("Email was sent successfully, but logging failed unexpectedly.")); } }
public async Task <IActionResult> Post([FromBody] EmailSendRequest request) { bool isValidEmailRequest = EmailSendRequestFactory.IsValidEmailRequest(request); if (!isValidEmailRequest) { return(new BadRequestObjectResult("Invalid email payload.")); } bool hasNoContent = request.Content == null; if (hasNoContent) { request.Content = new JObject(); } bool hasNoPersonalContent = request.PersonalContent == null; if (hasNoPersonalContent) { request.PersonalContent = new JObject(); } MailAddress[] toAddresses; try { toAddresses = request.To.Select(t => new MailAddress(t)).ToArray(); } catch (Exception exception) { return(new BadRequestObjectResult($"Invalid format of recipient email {request.To}.")); } Template template = TemplateUtility.GetTemplateByName(_emailConfiguration, request.Template); bool isInvalidTemplate = template == null; if (isInvalidTemplate) { return(new BadRequestObjectResult($"A template with the name {request.Template} does not exist.")); } JObject fullContent = JsonUtility.GetMergedJson(request.Content, request.PersonalContent); EmailViewModel emailViewModel = new EmailViewModel() { TemplateName = template.Name, Content = fullContent }; string rawHtml = await _htmlGeneratorService.GetRawHtmlAsync("Email/Index", emailViewModel); bool hasNoRawHtml = rawHtml == null; if (hasNoRawHtml) { return(new BadRequestObjectResult("Internal error.")); } Email email = new Email(toAddresses, template.Subject, ContentType.TEXT_HTML, rawHtml); EmailPreviewResponse response = EmailPreviewResponseFactory.Create(email); return(new OkObjectResult(response)); }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Sends an email. </summary> /// /// <param name="msg"> The message. </param> //////////////////////////////////////////////////////////////////////////////////////////////////// public void SendEmail(EmailSendRequest msg) { Console.WriteLine(EmailSender.Send(msg.From, msg.To, msg.Subject, msg.Body) ? "Email sent" : "Email not sent"); }