public async Task SendSingleEmail(string from, string to, string subject, string htmlContent) //temp function until all endpoints are accessible for template data { var fromEmail = new EmailAddress(from); var toEmail = new EmailAddress(to); var msg = MailHelper.CreateSingleEmail(fromEmail, toEmail, subject, null, htmlContent); await _client.SendEmailAsync(msg); }
public async Task SendAsync(Email email) { var from = new EmailAddress(email.SenderEmailAddress, email.SenderName); var to = new EmailAddress(email.RecipientEmailAddress, email.RecipientName); var msg = MailHelper.CreateSingleEmail(from, to, email.Subject, email.PlainTextContent, email.HtmlContent); await sendGridClient.SendEmailAsync(msg); }
public Task <Response> SendConfirmationEmailTo(User user) { var from = new EmailAddress(_sendGridOptions.HostEmail); var to = new EmailAddress(user.Email); var subject = _sendGridOptions.RegistrationInfo.Subject; var plainContent = _sendGridOptions.RegistrationInfo.PlainContent; var htmlContent = $"<a href='http://localhost:8080/confirm/{user.Id}/{user.VerificationToken}'>Potwierdź email.</a>"; var email = MailHelper.CreateSingleEmail(from, to, subject, plainContent, htmlContent); return(_sendGridClient.SendEmailAsync(email)); }
public async Task <ServiceResult> SendPasswordResetEmailAsync(string token, string email) { var result = new ServiceResult(); var user = await users.FindByEmailAsync(email); if (user == null) { result.Errors.Add(new ServiceResult.Error { Key = nameof(Errors.UserNotFound), Message = Errors.UserNotFound }); result.Code = 404; return(result); } // We need to encode the token since it will be used in a reset link. var encodedToken = HttpUtility.UrlEncode(token); var baseUrl = hosting.IsDevelopment() ? "https://localhost:52215" : "https://passport.slash.gg"; var link = $"{baseUrl}/password-reset?token={encodedToken}&id={user.Id}"; var model = new PasswordResetTemplateData { ResetLink = link, UserName = user.UserName }; var message = new SendGridMessage(); message.SetupNoReplyMessage(PASSWORD_RESET_TEMPLATE_ID, email, model); var response = await client.SendEmailAsync(message); if (response.StatusCode != System.Net.HttpStatusCode.Accepted) { var raw = await response.Body.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject <SendGridError>(raw); foreach (var error in data.Errors) { result.Errors.Add(new ServiceResult.Error { Key = error.Field, Message = error.Message }); } result.Code = 500; } return(result); }
private async Task <bool> SendMailTextAsync(string senderEmail, string recipientMail, string subject, string message) { var msg = new SendGridMessage(); msg.SetFrom(senderEmail); msg.AddTo(recipientMail); msg.Subject = HttpUtility.HtmlEncode(subject); msg.PlainTextContent = message; var response = await sendGridClient.SendEmailAsync(msg); return(response.StatusCode == HttpStatusCode.Accepted); }
public async Task NotifyAsync(BaseEmailTemplateModel baseEmailTemplateModel) { Guard.ArgumentNotNull(nameof(baseEmailTemplateModel), baseEmailTemplateModel); var email = await _emailBuilderRetriever.GetMessage(baseEmailTemplateModel); var response = await _sendGridClient.SendEmailAsync(email); if (response.StatusCode != HttpStatusCode.Accepted) { await _sendGridClient.SendEmailAsync(email); } }
public virtual async Task SendSingleTemplateEmail(string from, string to, string templateID, object templateData) { Require.That(templateID != null, new ErrorCode("SendgridError", 501, "Required Sengrid template ID not configured in app settings")); { var fromEmail = new EmailAddress(from); var toEmail = new EmailAddress(to); var msg = MailHelper.CreateSingleTemplateEmail(fromEmail, toEmail, templateID, templateData); var response = await _client.SendEmailAsync(msg); if (!response.IsSuccessStatusCode) { throw new Exception("Error sending sendgrid email"); } } }
private async Task <Response?> SendEmail(List <EntryModel> memories, User user, string userId, string babyName) { var msg = new SendGridMessage() { From = new EmailAddress(_configuration["MEMORIES_FROM_EMAIL"], _configuration["MEMORIES_FROM_NAME"]), Subject = $"BabyTracker - Memories {DateTime.Now.ToShortDateString()}" }; var mjml = await GetMJML(memories, userId, babyName); var html = await GetHTML(mjml); msg.AddContent(MimeType.Html, html); var userMetaData = AccountService.GetUserMetaData(user); var recipients = userMetaData?.MemoriesAddresses.Split(","); if (recipients?.Any() != true) { return(null); } foreach (var recipient in recipients) { msg.AddTo(new EmailAddress(recipient)); } var response = await _sendGridClient.SendEmailAsync(msg); return(response); }
public virtual async Task <bool> SendEmailAsync(ContactUsRequest sendEmailRequest, EmailTemplate template = null) { if (simulateEmailResponsesService.IsThisSimulationRequest(sendEmailRequest.Email)) { return(simulateEmailResponsesService.SimulateEmailResponse(sendEmailRequest.Email)); } if (template == null) { template = emailTemplateRepository.GetByTemplateName(sendEmailRequest.TemplateName); } if (template == null) { return(false); } var from = new EmailAddress(sendEmailRequest.Email, $"{sendEmailRequest.FirstName} {sendEmailRequest.LastName}"); var subject = template.Subject; var to = template.To?.Split(';').Select(toEmail => new EmailAddress(toEmail.Trim(), toEmail.Trim())).ToList(); var plainTextContent = mergeEmailContentService.MergeTemplateBodyWithContent(sendEmailRequest, template.BodyNoHtml); var htmlContent = mergeEmailContentService.MergeTemplateBodyWithContent(sendEmailRequest, template.Body); var msg = MailHelper.CreateSingleEmailToMultipleRecipients(@from, to, subject, plainTextContent, htmlContent); var clientResponse = await sendGridClient.SendEmailAsync(msg); var auditResponse = mapper.Map <SendEmailResponse>(clientResponse); var result = clientResponse.StatusCode.Equals(HttpStatusCode.Accepted); auditRepository.CreateAudit(sendEmailRequest, template, auditResponse); return(result); }
public FamSendGridEmailServiceTests() { var defaultTemplate = new EmailTemplate { To = "*****@*****.**", Body = "Body", Subject = DefaultSubject, }; fakeEmailTemplateRepository = A.Fake <IEmailTemplateRepository>(); A.CallTo(() => fakeEmailTemplateRepository.GetByTemplateName(A <string> .Ignored)).Returns(defaultTemplate); fakeMergeEmailContentService = A.Fake <IMergeEmailContent <ContactUsRequest> >(); fakeSendGridClient = A.Fake <ISendGridClient>(); var defaultResponse = new Response(HttpStatusCode.Accepted, A.Fake <HttpContent>(), null); A.CallTo(() => fakeSendGridClient.SendEmailAsync(A <SendGridMessage> .Ignored, A <CancellationToken> .Ignored)).Returns(defaultResponse); fakeSimulateEmailResponsesService = A.Fake <ISimulateEmailResponses>(); fakeAuditRepository = A.Fake <IAuditNoncitizenEmailRepository <ContactUsRequest> >(); fakeHttpClientService = A.Fake <IHttpClientService <INoncitizenEmailService <ContactUsRequest> > >(); var areaRoutingApiResponse = new AreaRoutingApiResponse { EmailAddress = EmailAddressFromAreaRouting }; var httpResponseMessage = new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(areaRoutingApiResponse), Encoding.Default, "application/json") }; A.CallTo(() => fakeHttpClientService.GetAsync(A <string> .Ignored, A <FaultToleranceType> .Ignored)).Returns(httpResponseMessage); fakeMapper = A.Fake <IMapper>(); fakeConfigurationProvider = A.Fake <IConfigurationProvider>(); fakeApplicationLogger = A.Fake <IApplicationLogger>(); }
public async Task SendEmailAsync(Reservation reservation, string userEmail) { var options = new SendGridClientOptions { ApiKey = apiKey }; client = new SendGridClient(options); var msg = new SendGridMessage() { From = new EmailAddress("*****@*****.**", "Hotel Booking"), Subject = "Reservation Confirmed", PlainTextContent = "Plain text not supported.", HtmlContent = await BuildConfirmEmailBody(reservation) }; msg.AddTo(new EmailAddress(userEmail)); Response response; try { response = await client.SendEmailAsync(msg); } catch (HttpRequestException) { Console.WriteLine("{0}", "SendEmailAsync Failed"); } }
/// <summary> /// Sends the asynchronous. /// </summary> /// <param name="sendGridMessage"><see cref="SendGridMessage" />.</param> /// <returns> /// <see cref="Task" /> /// </returns> public async Task <string> SendAsync(SendGridMessage sendGridMessage) { sendGridMessage.From = new EmailAddress(_emailSettingsModel.Email); var response = await _sendGridClient.SendEmailAsync(sendGridMessage); return(response.StatusCode.ToString()); }
public async Task SendEmailAsync(string email, string templateId, object templateData) { var message = new SendGridMessage { From = new EmailAddress(Options.Message.From.Email, Options.Message.From.Name), TemplateId = templateId, Personalizations = new List <Personalization> { new Personalization { Tos = new List <EmailAddress> { new EmailAddress(email) }, TemplateData = templateData } } }; _logger.LogInformation($"{email} message sending..."); await _client.SendEmailAsync(message); _logger.LogInformation($"{email} message sent..."); }
public async Task SendEmailAsync(MailAddressCollection to, string subject, string htmlBody, IEnumerable <System.Net.Mail.Attachment> attachments = null, CancellationToken cancellationToken = default) { var sendGridMessage = MailHelper.CreateSingleEmailToMultipleRecipients( from: new EmailAddress(_options.FromAddress, _options.FromName), tos: to.ToSendGridAddresses(), subject: subject, plainTextContent: HtmlToPlainText(htmlBody), htmlContent: htmlBody ); if (attachments != null && attachments.Any()) { await sendGridMessage.AddAttachmentsAsync(attachments, cancellationToken); } try { var response = await _sendGridClient.SendEmailAsync(sendGridMessage, cancellationToken); if (response.StatusCode != System.Net.HttpStatusCode.Accepted) { _logger.LogError($"Failed to send email to {to}. Sendgrid response: {response.Body}"); } } catch (HttpRequestException ex) { _logger.LogError(ex, $"Failed to send email to {to}."); } }
/// <summary> /// Method to send an email via SendGrid. /// </summary> /// <param name="fromEmailAddress">From <see cref="MailAddress"/>.</param> /// <param name="recipientEmailAddress">To <see cref="MailAddress"/>.</param> /// <param name="subject">The subject of the mail message.</param> /// <param name="content">The mail content.</param> /// <param name="cancellationToken">Cancellation token to cancel current request.</param> /// <returns></returns> public async Task <bool> SendAsync(MailAddress fromEmailAddress, MailAddress recipientEmailAddress, string subject, string content, CancellationToken cancellationToken) { if (fromEmailAddress is null) { throw new ArgumentNullException(nameof(fromEmailAddress)); } if (recipientEmailAddress is null) { throw new ArgumentNullException(nameof(recipientEmailAddress)); } var message = new SendGridMessage { From = new EmailAddress(fromEmailAddress.Address), Subject = subject, HtmlContent = content, }; message.AddTo(new EmailAddress(recipientEmailAddress.Address)); var response = await _client.SendEmailAsync(message, cancellationToken); return(response.IsSuccessStatusCode); }
public async Task SendDailyReminder() { var emailAddresses = await GetEmailAddresses(); if (!emailAddresses.Any()) { return; } var msg = new SendGridMessage() { From = new EmailAddress("*****@*****.**", "Novanet Julekalender"), Subject = "Daglig påminnelse om kalenderluke", ReplyTo = new EmailAddress("*****@*****.**") }; msg.AddTo(new EmailAddress("*****@*****.**")); msg.AddContent(MimeType.Html, "Ny luke på <a href=\"https://julekalender.novanet.no\">https://julekalender.novanet.no</a>. Der kan man også melde seg av påminnelsene.<br><br>Mvh<br>Novanet AS"); foreach (var emailAddress in emailAddresses) { msg.AddBcc(new EmailAddress(emailAddress)); } msg.AddBcc(new EmailAddress("*****@*****.**")); var response = await _client.SendEmailAsync(msg); }
public async Task SendEmail(string ConfirmNum, string UserEmail, string PathTo) { string body = string.Empty; using (StreamReader reader = new StreamReader(Path.Combine(_env.ContentRootPath, "Templates", PathTo))) { body = await reader.ReadToEndAsync(); } var user = await _unitOfWork.Repository <UserDetails>().Get(u => u.User.Email == UserEmail); var url = "https://theralang.azurewebsites.net"; if (_env.IsDevelopment()) { url = "http://localhost:5000"; } body = body.Replace("{EMAIL}", UserEmail); body = body.Replace("{NUMBER}", ConfirmNum); body = body.Replace("{FIRSTNAME}", user.FirstName); body = body.Replace("{URL}", url); var from = new EmailAddress(_emailSettings.Email, "UTTMM"); var to = new EmailAddress(UserEmail); var subject = "UTTMM"; var msg = MailHelper.CreateSingleEmail(from, to, subject, "", body); var response = await _emailClient.SendEmailAsync(msg); }
public async Task SendPasswordResetEmailAsync(string password, string userEmail) { var options = new SendGridClientOptions { ApiKey = apiKey }; client = new SendGridClient(options); var msg = new SendGridMessage() { From = new EmailAddress("*****@*****.**", "Hotel Booking"), Subject = "Password Reset", PlainTextContent = "Plain text not supported.", HtmlContent = BuildPasswordResetEmailBody(password) }; msg.AddTo(new EmailAddress(userEmail)); Response response; try { response = await client.SendEmailAsync(msg); } catch (HttpRequestException) { Console.WriteLine("SendEmailAsync Failed to address: {0}", userEmail);; } }
public async Task SendAsync_should_send_mail_to_the_destination() { const string? @from = "*****@*****.**"; const string? to = "*****@*****.**"; const string? subject = "my test e-mail"; const string? content = "<h1>Test e-mail</h1>"; _sendgridClient.SendEmailAsync(Arg.Any <SendGridMessage>(), Arg.Any <CancellationToken>()) .Returns(new Response(HttpStatusCode.Accepted, null, null)); var message = _mockCreator.GetSendGridMessage(from, to, subject, content); var sent = await _sender.SendAsync(message, CancellationToken.None); sent.Should().BeTrue(); await _sendgridClient.Received(1) .SendEmailAsync(Arg.Any <SendGridMessage>(), Arg.Any <CancellationToken>()); var messageSent = (SendGridMessage)_sendgridClient.ReceivedCalls().Single().GetArguments()[0] !; messageSent.From.Email.Should().Be(from); messageSent.Personalizations.Single().Tos.Single().Email.Should().Be(to); messageSent.Personalizations.Single().Subject.Should().Be(subject); messageSent.Contents.Should().AllSatisfy(c => c.Value.Should().Be(content)); }
public async Task NotifyNewUserRegistered(string userName, string userEmail, string userCity) { var now = DateTime.Now; var sendGridMessage = new SendGridMessage(); sendGridMessage.SetFrom(_appSettings.SendGridSenderEmail); sendGridMessage.AddTo(_appSettings.AdministratorEmail); sendGridMessage.SetTemplateId(_appSettings.SendGridDynamicTemplateId); sendGridMessage.SetTemplateData(new NewUserRegisteredNotification { UserName = userName, UserEmail = userEmail, UserCity = userCity, Date = now.ToString("dd.MM.yyyy"), Time = now.ToString("HH:mm") }); var response = await _sendGridClient.SendEmailAsync(sendGridMessage).ConfigureAwait(false); if (response.StatusCode == System.Net.HttpStatusCode.Accepted) { _logger.LogInformation($"Email notification on new user registration was sent via SendGrid to {_appSettings.AdministratorEmail}"); } else { var errorDetails = await response.Body.ReadAsStringAsync().ConfigureAwait(false); _logger.LogError($"Email notification via SendGrid failed with status {response.StatusCode}, error details: '{errorDetails}'"); } }
public async Task SendInvitationMessageAsync(CarReservationConfirmationMailTemplate carReservationConfirmationMailTemplate) { var emailMessage = MailHelper.CreateSingleTemplateEmail( new EmailAddress(_mailDeliveryServiceConfiguration.FromEmail), new EmailAddress(carReservationConfirmationMailTemplate.CustomerEmail), _mailDeliveryServiceConfiguration.CarReservationConfirmationTemplateId, new { customerName = carReservationConfirmationMailTemplate.CustomerName, carBrand = carReservationConfirmationMailTemplate.CarBrand, carModel = carReservationConfirmationMailTemplate.CarModel, carImageUrl = carReservationConfirmationMailTemplate.CarImageUrl, fromDate = carReservationConfirmationMailTemplate.FromDate, toDate = carReservationConfirmationMailTemplate.ToDate }); var response = await _sendGridClient.SendEmailAsync(emailMessage); if (response.StatusCode != HttpStatusCode.Accepted) { var responseContent = await response.Body.ReadAsStringAsync(); _logger.LogError($"SendGrid service returned status code {response.StatusCode} with response: {responseContent}"); } }
public async Task SendAsync(User sender, User recipient, SalesReport report) { var message = MailHelper.CreateSingleEmail( new EmailAddress(sender.Email, $"{sender.FirstName} {sender.LastName}"), new EmailAddress(recipient.Email, $"{recipient.FirstName} {recipient.LastName}"), "Raport sprzedaży", report.ToString(), report.ToHtml()); logger.Info($"Wysyłanie raportu do {recipient.FirstName} {recipient.LastName} <{recipient.Email}>..."); var response = await client.SendEmailAsync(message); if (response.StatusCode == System.Net.HttpStatusCode.Accepted) { /// ReportSent?.Invoke(this, new ReportSentEventArgs(DateTime.Now)); logger.Info($"Raport został wysłany."); } else { logger.Error($"Błąd podczas wysyłania raportu."); throw new ApplicationException("Błąd podczas wysyłania raportu."); } }
/// <inheritdoc /> public Task SendEmailAsync( string source, IEnumerable <string> destinations, string subject, string htmlBody, string textBody = default, CancellationToken cancellationToken = default) { if (IsNullOrEmpty(source)) { throw new ArgumentNullException(nameof(source)); } if (destinations == null) { throw new ArgumentNullException(nameof(destinations)); } var recipients = destinations.ToArray(); if (!recipients.Any()) { throw new ArgumentException("No recipients.", nameof(destinations)); } if (IsNullOrEmpty(subject)) { throw new ArgumentNullException(nameof(subject)); } if (IsNullOrEmpty(htmlBody)) { throw new ArgumentNullException(nameof(htmlBody)); } async Task SendEmailAsync() { var message = new SendGridMessage { From = new EmailAddress(source), Subject = subject, PlainTextContent = textBody, HtmlContent = htmlBody }; foreach (var recipient in recipients) { message.AddTo(new EmailAddress(recipient)); } // Disable click tracking. // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html message.SetClickTracking(false, false); await _sendGridClient .SendEmailAsync(message, cancellationToken) .ConfigureAwait(false); } return(SendEmailAsync()); }
public async Task SendEmailAsync(string email, string subject, string htmlMessage) { var message = SendGrid.Helpers.Mail.MailHelper.CreateSingleEmail( new SendGrid.Helpers.Mail.EmailAddress(_configuration.SourceEmail, _configuration.SourceName), new SendGrid.Helpers.Mail.EmailAddress(email), subject, null, htmlMessage ); // More information about click tracking: https://sendgrid.com/docs/ui/account-and-settings/tracking/ message.SetClickTracking(_configuration.EnableClickTracking, _configuration.EnableClickTracking); var response = await _client.SendEmailAsync(message); switch (response.StatusCode) { case System.Net.HttpStatusCode.OK: case System.Net.HttpStatusCode.Created: case System.Net.HttpStatusCode.Accepted: _logger.LogInformation($"Email: {email}, subject: {subject}, message: {htmlMessage} successfully sent"); break; default: { var errorMessage = await response.Body.ReadAsStringAsync(); _logger.LogError($"Response with code {response.StatusCode} and body {errorMessage} after sending email: {email}, subject: {subject}"); break; } } }
public async Task Send(EmailMessage email) { SendGridMessage emailRequest; try { emailRequest = BuildMessage(email); } catch (Exception ex) { _logger.LogError(ex, $"Failed to build email object"); return; } try { var response = await _sendGridClient.SendEmailAsync(emailRequest).ConfigureAwait(false); _logger.LogDebug($"SendGrid response {response.StatusCode}"); } catch (Exception ex) { _logger.LogError(ex, $"Failed to send email"); throw; } }
private async Task SendEmailAsync(string from, string to, string subject, string content, EmailAttachment[] attachments, CancellationToken cancellationToken) { string EnsureNotEmpty(string message) { // pgp signed emails have no content but attachments only; // seems to be this bug // https://github.com/sendgrid/sendgrid-nodejs/issues/435 return(string.IsNullOrEmpty(message) ? " " : message); } var mail = MailHelper.CreateSingleEmail(new EmailAddress(from), new EmailAddress(to), subject, null, EnsureNotEmpty(content)); foreach (var attachment in attachments) { mail.AddAttachment(new Attachment { ContentId = attachment.ContentId, Content = attachment.Base64Data, Filename = attachment.FileName, Type = attachment.ContentType }); } var response = await _client.SendEmailAsync(mail, cancellationToken); if (response.StatusCode != HttpStatusCode.Accepted) { var errorResponse = await response.Body.ReadAsStringAsync(); throw new BadRequestException($"Sendgrid did not accept. The response was: {response.StatusCode}." + Environment.NewLine + errorResponse); } }
public Task SendAsync(IdentityMessage message) { EmailAddress from = new EmailAddress("*****@*****.**", "Outdoor Gear Rental"); EmailAddress to = new EmailAddress(message.Destination); SendGridMessage sendGridMessage = MailHelper.CreateSingleEmail(from, to, message.Subject, Regex.Replace(message.Body, @"<(.|\n)*?>", ""), message.Body); return(_client.SendEmailAsync(sendGridMessage)); }
public async Task <IActionResult> SendEmail() { var from = new EmailAddress("*****@*****.**", "Example User"); var to = new EmailAddress("*****@*****.**", "Example User"); var msg = new SendGridMessage { From = from, Subject = "Sending with Twilio SendGrid is Fun" }; msg.AddContent(MimeType.Text, "and easy to do anywhere, even with C#"); msg.AddTo(to); var response = await _sendgridClient.SendEmailAsync(msg); return(Ok(new { response = response })); }
public Task SendAsync(IdentityMessage message) { EmailAddress from = new EmailAddress("*****@*****.**", "Coding Cookware Administrator"); EmailAddress to = new EmailAddress(message.Destination); SendGridMessage sendGridMessage = MailHelper.CreateSingleEmail(from, to, message.Subject, Regex.Replace(message.Body, @"<(.|\n)*?>", ""), message.Body); return(_client.SendEmailAsync(sendGridMessage)); }
public async Task NotifyOwnerAsync(OwnerNotificationMessage ownerNotificationMessage) { var message = CreateEmailMessage(ownerNotificationMessage); await _sendGridClient .SendEmailAsync(message) .ConfigureAwait(false); }