public void TestFetchFormParamsHelper(Web webApi, bool credentials) { // Test Variables const string toAddress = "*****@*****.**"; const string ccAddress = "*****@*****.**"; const string bcc1Address = "*****@*****.**"; const string bcc2Address = "*****@*****.**"; MailAddress[] bccAddresses = { new MailAddress(bcc1Address), new MailAddress(bcc2Address) }; const string fromAddress = "*****@*****.**"; const string subject = "Test Subject"; const string textBody = "Test Text Body"; const string htmlBody = "<p>Test HTML Body</p>"; const string headerKey = "headerkey"; var testHeader = new Dictionary <string, string> { { headerKey, "headervalue" } }; const string categoryName = "Example Category"; var message = new SendGridMessage(); message.AddTo(toAddress); message.AddCc(ccAddress); message.Bcc = bccAddresses; message.From = new MailAddress(fromAddress); message.Subject = subject; message.Text = textBody; message.Html = htmlBody; message.AddHeaders(testHeader); message.Header.SetCategory(categoryName); var result = webApi.FetchFormParams(message); if (credentials) { Assert.True(result.Any(r => r.Key == "api_user" && r.Value == TestUsername)); Assert.True(result.Any(r => r.Key == "api_key" && r.Value == TestPassword)); } Assert.True(result.Any(r => r.Key == "to[]" && r.Value == toAddress)); Assert.True(result.Any(r => r.Key == "cc[]" && r.Value == ccAddress)); Assert.True(result.Any(r => r.Key == "bcc[]" && r.Value == bcc1Address)); Assert.True(result.Any(r => r.Key == "bcc[]" && r.Value == bcc2Address)); Assert.True(result.Any(r => r.Key == "from" && r.Value == fromAddress)); Assert.True(result.Any(r => r.Key == "subject" && r.Value == subject)); Assert.True(result.Any(r => r.Key == "text" && r.Value == textBody)); Assert.True(result.Any(r => r.Key == "html" && r.Value == htmlBody)); Assert.True( result.Any( r => r.Key == "headers" && r.Value == String.Format("{{\"{0}\":\"{1}\"}}", headerKey, testHeader[headerKey]))); Assert.True( result.Any(r => r.Key == "x-smtpapi" && r.Value == String.Format("{{\"category\" : \"{0}\"}}", categoryName))); }
public void CreateMimeMessage() { var message = new SendGridMessage(); var attachment = Path.GetTempFileName(); var text = "this is a test"; var html = "<b>This<\b> is a better test"; var headers = new KeyValuePair <String, String>("custom", "header"); message.AddAttachment(attachment); message.Text = text; message.Html = html; message.AddTo("*****@*****.**"); message.From = new MailAddress("*****@*****.**"); message.AddHeaders(new Dictionary <string, string> { { headers.Key, headers.Value } }); message.EnableGravatar(); var mime = message.CreateMimeMessage(); var sr = new StreamReader(mime.AlternateViews[0].ContentStream); var result = sr.ReadToEnd(); Assert.AreEqual(text, result); sr = new StreamReader(mime.AlternateViews[1].ContentStream); result = sr.ReadToEnd(); Assert.AreEqual(html, result); result = mime.Headers.Get(headers.Key); Assert.AreEqual(headers.Value, result); result = mime.Headers.Get("X-Smtpapi"); var expected = "{\"filters\" : {\"gravatar\" : {\"settings\" : {\"enable\" : \"1\"}}}}"; Assert.AreEqual(expected, result); result = mime.Attachments[0].Name; Assert.AreEqual(Path.GetFileName(attachment), result); }
public void Send(EmailItem emailItem) { try { SendGridMessage message = new SendGridMessage(); emailItem.To.ForEach((cc) => message.AddTo(new EmailAddress(cc))); emailItem.CC.ForEach((cc) => message.AddCc(new EmailAddress(cc))); emailItem.BCC.ForEach((bcc) => message.AddBcc(new EmailAddress(bcc))); message.Subject = (emailItem.Subject); message.HtmlContent = emailItem.Content; var from = !string.IsNullOrEmpty(emailItem.From) ? emailItem.From : "*****@*****.**"; message.SetFrom(new EmailAddress(from)); foreach (var pair in emailItem.Attachments) { message.AddAttachment(pair.Key, pair.Value); } Dictionary <string, string> dictionary = new Dictionary <string, string>(); if (emailItem.Priority) { dictionary.Add("Priority", "Urgent"); dictionary.Add("Importance", "high"); message.AddHeaders(dictionary); } var result = this.sendGridClient.SendEmailAsync(message).GetAwaiter().GetResult(); Logger.Info($"StatusCode={result.StatusCode};Body={JsonConvert.SerializeObject(result.DeserializeResponseBodyAsync(result.Body))}"); } catch (Exception exception) { Logger.Error(exception); throw; } }
public async Task Send(TerminalMailerDO mailer) { if (mailer == null) { throw new ArgumentNullException("mailer"); } if (mailer.Email == null) { throw new ArgumentException(@"This envelope has no Email.", nameof(mailer)); } if (!mailer.Email.GetToRecipients().Any()) { throw new ArgumentException(@"This envelope has no recipients.", nameof(mailer)); } var email = mailer.Email; try { var fromName = email.From.Name; var mailMessage = new SendGridMessage { From = new MailAddress(email.From.Address, fromName) }; if (!String.IsNullOrWhiteSpace(email.From.Address)) { mailMessage.ReplyTo = new[] { new MailAddress(email.From.Address, fromName) }; } mailMessage.To = email.GetToRecipients().Select(toEmail => new MailAddress(toEmail.Address, toEmail.Name ?? toEmail.Address)).ToArray(); mailMessage.Subject = email.Subject; if ((email.HTMLText == null) && string.IsNullOrEmpty(mailer.TemplateName)) { throw new ArgumentException( "Trying to send an email that doesn't have both an HTML and plain text body"); } if (email.HTMLText == null) { mailMessage.Html = "<html></html>"; mailMessage.Text = ""; } else { mailMessage.Html = email.HTMLText; } var headers = new Dictionary <String, String>(); if (headers.Any()) { mailMessage.AddHeaders(headers); } if (mailer.Footer.Any()) { mailMessage.EnableFooter(null, mailer.Footer); } if (!string.IsNullOrEmpty(mailer.TemplateName)) { mailMessage.EnableTemplateEngine(mailer.TemplateName); //Now TemplateName will be TemplateId on Sendgrid. if (mailer.MergeData != null) { //Now, we need to do some magic. //Basically - we need the length of each substitution to match the length of recipients //In our case, most of the time, all the substitutions are the same, except for token-related fields //To make it easier to use, we attempt to pad out the substition arrays if they lengths don't match //We only do that if we're given a string value. In any other case, we allow sengrid to fail. var subs = new Dictionary <String, List <String> >(); foreach (var pair in mailer.MergeData) { var arrayType = pair.Value as JArray; List <String> listVal; if (arrayType != null) { listVal = arrayType.Select(a => a.ToString()).ToList(); } else { listVal = new List <string>(); for (var i = 0; i < email.GetToRecipients().Count(); i++) //Pad out the substitution { listVal.Add(pair.Value == null ? String.Empty : pair.Value.ToString()); } } subs.Add(pair.Key, listVal); } foreach (var sub in subs) { mailMessage.AddSubstitution(sub.Key, sub.Value); } } } try { await _transport.DeliverAsync(mailMessage); OnEmailSent(email.Id); } catch (Exception ex) { OnEmailRejected(ex.Message, email.Id); } } catch (Exception ex) { OnEmailCriticalError(-1, "Unhandled exception.", ex.Message, email.Id); } }
private async Task <SendGridMessage> BuildSendGridMessage(IFluentEmail email) { var mailMessage = new SendGridMessage(); mailMessage.SetSandBoxMode(_sandBoxMode); mailMessage.SetFrom(ConvertAddress(email.Data.FromAddress)); if (email.Data.ToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { mailMessage.AddTos(email.Data.ToAddresses.Select(ConvertAddress).ToList()); } if (email.Data.CcAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { mailMessage.AddCcs(email.Data.CcAddresses.Select(ConvertAddress).ToList()); } if (email.Data.BccAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { mailMessage.AddBccs(email.Data.BccAddresses.Select(ConvertAddress).ToList()); } if (email.Data.ReplyToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { // SendGrid does not support multiple ReplyTo addresses mailMessage.SetReplyTo(email.Data.ReplyToAddresses.Select(ConvertAddress).First()); } mailMessage.SetSubject(email.Data.Subject); if (email.Data.Headers.Any()) { mailMessage.AddHeaders(email.Data.Headers.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)); } if (email.Data.Tags != null && email.Data.Tags.Any()) { mailMessage.Categories = email.Data.Tags.ToList(); } if (email.Data.IsHtml) { mailMessage.HtmlContent = email.Data.Body; } else { mailMessage.PlainTextContent = email.Data.Body; } switch (email.Data.Priority) { case Priority.High: // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api mailMessage.AddHeader("Priority", "Urgent"); mailMessage.AddHeader("Importance", "High"); // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab mailMessage.AddHeader("X-Priority", "1"); mailMessage.AddHeader("X-MSMail-Priority", "High"); break; case Priority.Normal: // Do not set anything. // Leave default values. It means Normal Priority. break; case Priority.Low: // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api mailMessage.AddHeader("Priority", "Non-Urgent"); mailMessage.AddHeader("Importance", "Low"); // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab mailMessage.AddHeader("X-Priority", "5"); mailMessage.AddHeader("X-MSMail-Priority", "Low"); break; } if (email.Data.Attachments.Any()) { foreach (var attachment in email.Data.Attachments) { var sendGridAttachment = await ConvertAttachment(attachment); mailMessage.AddAttachment(sendGridAttachment.Filename, sendGridAttachment.Content, sendGridAttachment.Type, sendGridAttachment.Disposition, sendGridAttachment.ContentId); } } return(mailMessage); }
public async Task <SendResponse> SendAsync(IFluentEmail email, CancellationToken?token = null) { var sendGridClient = new SendGridClient(_apiKey); var mailMessage = new SendGridMessage(); mailMessage.SetSandBoxMode(_sandBoxMode); mailMessage.SetFrom(ConvertAddress(email.Data.FromAddress)); if (email.Data.ToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { mailMessage.AddTos(email.Data.ToAddresses.Select(ConvertAddress).ToList()); } if (email.Data.CcAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { mailMessage.AddCcs(email.Data.CcAddresses.Select(ConvertAddress).ToList()); } if (email.Data.BccAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { mailMessage.AddBccs(email.Data.BccAddresses.Select(ConvertAddress).ToList()); } mailMessage.SetSubject(email.Data.Subject); if (email.Data.Headers.Any()) { mailMessage.AddHeaders(email.Data.Headers); } if (email.Data.IsHtml) { mailMessage.HtmlContent = email.Data.Body; } else { mailMessage.PlainTextContent = email.Data.Body; } switch (email.Data.Priority) { case Priority.High: // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api mailMessage.AddHeader("Priority", "Urgent"); mailMessage.AddHeader("Importance", "High"); // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab mailMessage.AddHeader("X-Priority", "1"); mailMessage.AddHeader("X-MSMail-Priority", "High"); break; case Priority.Normal: // Do not set anything. // Leave default values. It means Normal Priority. break; case Priority.Low: // https://stackoverflow.com/questions/23230250/set-email-priority-with-sendgrid-api mailMessage.AddHeader("Priority", "Non-Urgent"); mailMessage.AddHeader("Importance", "Low"); // https://docs.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab mailMessage.AddHeader("X-Priority", "5"); mailMessage.AddHeader("X-MSMail-Priority", "Low"); break; } if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody)) { mailMessage.PlainTextContent = email.Data.PlaintextAlternativeBody; } if (email.Data.Attachments.Any()) { foreach (var attachment in email.Data.Attachments) { var sendGridAttachment = await ConvertAttachment(attachment); mailMessage.AddAttachment(sendGridAttachment.Filename, sendGridAttachment.Content, sendGridAttachment.Type, sendGridAttachment.Disposition, sendGridAttachment.ContentId); } } var sendGridResponse = await sendGridClient.SendEmailAsync(mailMessage, token.GetValueOrDefault()); var sendResponse = new SendResponse(); if (IsHttpSuccess((int)sendGridResponse.StatusCode)) { return(sendResponse); } sendResponse.ErrorMessages.Add($"{sendGridResponse.StatusCode}"); var messageBodyDictionary = await sendGridResponse.DeserializeResponseBodyAsync(sendGridResponse.Body); if (messageBodyDictionary.ContainsKey("errors")) { var errors = messageBodyDictionary["errors"]; foreach (var error in errors) { sendResponse.ErrorMessages.Add($"{error}"); } } return(sendResponse); }
///<inheritdoc/> public async Task <SendMailResult> SendMailAsync(IMessage message, CancellationToken cancellationToken = default) { SendGridMessage msg = new SendGridMessage() { From = new EmailAddress(message.From.Email, message.From.Name), Subject = message.Subject }; if (message.ReplyTo != null) { msg.ReplyTo = new EmailAddress(message.ReplyTo.Email, message.ReplyTo.Name); } if (message.Headers.Count > 0) { msg.AddHeaders(message.Headers.ToDictionary(k => k.Key, v => v.Value)); } if (message.EnableHtml) { msg.HtmlContent = message.Content; } else { msg.PlainTextContent = message.Content; } msg.AddTos(message.To.Select(s => new EmailAddress(s.Email, s.Name)).ToList()); if (message.Cc.Count > 0) { msg.AddCcs(message.Cc.Select(s => new EmailAddress(s.Email, s.Name)).ToList()); } if (message.Bcc.Count > 0) { msg.AddBccs(message.Bcc.Select(s => new EmailAddress(s.Email, s.Name)).ToList()); } if (message.Files.Count > 0) { msg.Attachments = message.Files.Select(s => new Attachment() { Filename = s.Filename, Type = s.Type, Content = s.Content, Disposition = "attachment" }).ToList(); } IDictionary <string, string> errors = new Dictionary <string, string>(); Response response = await _client.SendEmailAsync(msg, cancellationToken); bool success = (response.StatusCode == HttpStatusCode.Accepted); if (!success) { string errorMessage = string.Empty; string body = await response.Body.ReadAsStringAsync(); _logger.LogWarning("Fail to send e-mail in SendGrid Service, Response Status Code: {SendGridStatusCode}, Response Body: {SendGridStatusResponseBody}", response.StatusCode, body.AsJson()); if (!string.IsNullOrWhiteSpace(body)) { SendGridError sendGridResult = JsonSerializer.Deserialize <SendGridError>(body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); errorMessage = string.Join('|', sendGridResult.Errors.Select(x => x.Message)); } else { errorMessage = response.StatusCode.ToString(); } errors.Add("Email", $"Failed to send email => {errorMessage}"); } return(new SendMailResult(success, errors)); }
public async Task <SendResponse> SendAsync(IFluentEmail email, CancellationToken?token = null) { var sendGridClient = new SendGridClient(_apiKey); var mailMessage = new SendGridMessage(); mailMessage.SetSandBoxMode(_sandBoxMode); mailMessage.SetFrom(ConvertAddress(email.Data.FromAddress)); if (email.Data.ToAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { mailMessage.AddTos(email.Data.ToAddresses.Select(ConvertAddress).ToList()); } if (email.Data.CcAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { mailMessage.AddCcs(email.Data.CcAddresses.Select(ConvertAddress).ToList()); } if (email.Data.BccAddresses.Any(a => !string.IsNullOrWhiteSpace(a.EmailAddress))) { mailMessage.AddBccs(email.Data.BccAddresses.Select(ConvertAddress).ToList()); } mailMessage.SetSubject(email.Data.Subject); if (email.Data.Headers.Any()) { mailMessage.AddHeaders(email.Data.Headers); } if (email.Data.IsHtml) { mailMessage.HtmlContent = email.Data.Body; } else { mailMessage.PlainTextContent = email.Data.Body; } if (!string.IsNullOrEmpty(email.Data.PlaintextAlternativeBody)) { mailMessage.PlainTextContent = email.Data.PlaintextAlternativeBody; } if (email.Data.Attachments.Any()) { foreach (var attachment in email.Data.Attachments) { var sendGridAttachment = await ConvertAttachment(attachment); mailMessage.AddAttachment(sendGridAttachment.Filename, sendGridAttachment.Content, sendGridAttachment.Type, sendGridAttachment.Disposition, sendGridAttachment.ContentId); } } var sendGridResponse = await sendGridClient.SendEmailAsync(mailMessage, token.GetValueOrDefault()); var sendResponse = new SendResponse(); if (IsHttpSuccess((int)sendGridResponse.StatusCode)) { return(sendResponse); } sendResponse.ErrorMessages.Add($"{sendGridResponse.StatusCode}"); var messageBodyDictionary = await sendGridResponse.DeserializeResponseBodyAsync(sendGridResponse.Body); if (messageBodyDictionary.ContainsKey("errors")) { var errors = messageBodyDictionary["errors"]; foreach (var error in errors) { sendResponse.ErrorMessages.Add($"{error}"); } } return(sendResponse); }