private static async Task Execute() { var apiKey = "<api-key>"; var client = new SendGridClient(apiKey); var msg = new SendGridMessage(); msg.SetFrom(new EmailAddress("*****@*****.**")); msg.AddTo(new EmailAddress("*****@*****.**", "Ashirwad")); var cc_emails = new List <EmailAddress> { new EmailAddress("*****@*****.**", "test 1"), new EmailAddress("*****@*****.**", "test 2") }; msg.AddCcs(cc_emails); var bcc_emails = new List <EmailAddress> { new EmailAddress("*****@*****.**", "test 3"), new EmailAddress("*****@*****.**", "test 4") }; msg.AddBccs(bcc_emails); msg.SetTemplateId("d-3e97f42b3efc437cb23f754664d41fca"); var dynamicTemplateData = new ExampleTemplateData { Subject = "100DaysOfServerlessCode", }; msg.SetTemplateData(dynamicTemplateData); var response = await client.SendEmailAsync(msg); }
/// <summary> /// Sends out an email to multiple recipients, with a list of copies and blind copies within a non-blocking context /// </summary> /// <param name="sender">Sender alias</param> /// <param name="recipients">Primary email recipients</param> /// <param name="ccs">Copy emails</param> /// <param name="bccs">Blind copy emails</param> /// <param name="subject">Email subject</param> /// <param name="body">Email content</param> /// <returns>A callback handle providing access to the status code indicating the result of the operation</returns> public async Task <IStatus> SendEmailAsync(string sender, IList <string> recipients, IList <string> ccs, IList <string> bccs, string subject, string body) { byte[] encryptedCredentials = File.ReadAllBytes(Config.GetValue(ConfigConstants.SEND_GRID_ENCRYPTED)); byte[] symmKey = KeyStoreService.GetKey(Config.GetValue(ConfigConstants.SYMMETRIC_KEY_INDEX)); string apiKey = Encoding.UTF8.GetString(SecurityService.Decrypt(encryptedCredentials, symmKey)); List <EmailAddress> receivers = (from r in recipients select new EmailAddress(r)).ToList(); List <EmailAddress> copies = (ccs == null ? new List <EmailAddress>() : (from c in ccs select new EmailAddress(c)).ToList()); List <EmailAddress> blindCopies = (bccs == null ? new List <EmailAddress>() : (from b in bccs select new EmailAddress(b)).ToList()); EmailAddress senderAddress = new EmailAddress(sender); SendGridMessage message = new SendGridMessage(); message.Subject = subject; message.SetFrom(senderAddress); message.AddTos(receivers); message.AddCcs(copies); message.AddBccs(blindCopies); message.AddContent(MimeType.Html, body); SendGridClient client = new SendGridClient(apiKey); await client.SendEmailAsync(message); return(new Status() { IsSuccess = true, StatusMessage = "Sent" }); }
public async Task SendEmailAsync(Mail mail) { var sendGridClient = new SendGridClient(_sendGridOptions.APIKey); var sendGridMessage = new SendGridMessage(); sendGridMessage.From = new EmailAddress(mail.From); sendGridMessage.AddTos(mail.To.Select(x => new EmailAddress(x)).ToList()); if (mail.CC != null) { sendGridMessage.AddCcs(mail.CC.Select(x => new EmailAddress(x)).ToList()); } if (mail.BCC != null) { sendGridMessage.AddBccs(mail.BCC.Select(x => new EmailAddress(x)).ToList()); } sendGridMessage.Subject = mail.Subject; if (mail.IsBodyHTML) { sendGridMessage.HtmlContent = mail.Body; } else { sendGridMessage.PlainTextContent = mail.Body; } await sendGridClient.SendEmailAsync(sendGridMessage); }
public static SendGridMessage ToSendGridMessage(this MailMessageDto dto) { if (dto.Sender != null) { throw new NotSupportedException("Sender header is not supported by SendGrid."); } if ((dto.ReplyTo?.Count ?? 0) > 1) { throw new NotSupportedException("Only one Reply-To header is supported by SendGrid."); } var msg = new SendGridMessage(); // Add standard header fields msg.From = dto.From.ToEmailAddress(); if (dto.To.Any()) { msg.AddTos(dto.To.ToEmailAddress()); } if (dto.Cc.Any()) { msg.AddCcs(dto.Cc.ToEmailAddress()); } if (dto.Bcc.Any()) { msg.AddBccs(dto.Bcc.ToEmailAddress()); } msg.ReplyTo = dto.ReplyTo.FirstOrDefault().ToEmailAddress(); msg.Subject = dto.Subject; // Add custom header fields foreach (var item in dto.CustomHeaders) { msg.Headers.Add(item.Key, item.Value); } // Construct body if (!string.IsNullOrWhiteSpace(dto.BodyText)) { msg.PlainTextContent = dto.BodyText; } if (!string.IsNullOrWhiteSpace(dto.BodyHtml)) { msg.HtmlContent = dto.BodyHtml; } // Add attachments foreach (var item in dto.Attachments) { // Get stream as byte array var data = new byte[item.Stream.Length]; item.Stream.Read(data, 0, (int)item.Stream.Length); // Base64 encode var encodedData = Convert.ToBase64String(data, 0, data.Length); msg.AddAttachment(item.Name, encodedData, item.MimeType); } return(msg); }
internal async Task SendEmail(string toemail, string body, string plainTextMessage) { try { var msg = new SendGridMessage() { From = new EmailAddress(_fromEmail, _fromEmailName), Subject = _subject, HtmlContent = body, PlainTextContent = plainTextMessage }; var toEmailsList = _additionalToEmails.Select(toEmail => new EmailAddress(toEmail)).ToList(); toEmailsList.Add(new EmailAddress(toemail)); msg.AddTos(toEmailsList); var ccEmailsList = _ccEmails.Select(x => new EmailAddress(x)).ToList(); msg.AddCcs(ccEmailsList); var response = await _client.SendEmailAsync(msg); } catch (Exception ex) { log.Error(ex.Message, ex); } }
private async Task <Response> Execute(ICollection <string> sendTo, string subject, string messageBody, ICollection <string> bccTo, ICollection <string> ccTo) { if (_options.Value.ApiKey == null) { _logger.LogError($"Attempt to send email while 'appsettings.json' doesn't have 'SendGrid' directive."); return(null); } var mailFrom = new EmailAddress(_options.Value.SenderEmail, _options.Value.SenderName); var client = new SendGridClient(_options.Value.ApiKey); var mail = new SendGridMessage { From = mailFrom, Subject = subject, PlainTextContent = messageBody, HtmlContent = messageBody }; mail.AddTos(sendTo.Select(x => new EmailAddress { Email = x }).ToList()); if (ccTo != null) { mail.AddCcs(ccTo.Select(x => new EmailAddress { Email = x }).ToList()); } if (bccTo != null) { mail.AddBccs(bccTo.Select(x => new EmailAddress { Email = x }).ToList()); } var result = await client.SendEmailAsync(mail); string logString = $@" Sent From: '{mailFrom.Email}' Message Subject: '{subject}'. {(sendTo != null ? "To: " + string.Join(",", sendTo) : String.Empty)} {(ccTo != null ? " CC: " + ccTo : String.Empty)} {(bccTo != null ? " BCC: " + bccTo : String.Empty)}"; if (result.StatusCode != HttpStatusCode.Accepted) { _logger.LogError($"Unable to send email. Status code '{result.StatusCode}'. {logString}"); } else if (result.StatusCode == HttpStatusCode.Accepted) { _logger.LogInformation($"Mail has been submitted. {logString}"); } return(result); }
/// <summary> /// Add Cc emails recipients /// </summary> /// <param name="cc"></param> public IEmailRepository Cc(ICollection <string> cc) { if (cc?.Count > 0) { Message.AddCcs(cc.Select(x => new EmailAddress(x)).ToList()); } return(this); }
public async Task <string> ScheduleAsync(EmailMessage message, CancellationToken cancellationToken) { using var httpClient = CreateClient(); var sendGrid = new SendGridClient(httpClient, ClientOptions); var m = new SendGridMessage(); m.SetFrom(message.From.ToSendGridAddress()); m.SetSubject(message.Subject); if (message.To.Count > 0) { m.AddTos(message.To.Select(SendGridExtensions.ToSendGridAddress).ToList()); } if (message.Cc.Count > 0) { m.AddCcs(message.Cc.Select(SendGridExtensions.ToSendGridAddress).ToList()); } if (message.Bcc.Count > 0) { m.AddBccs(message.Bcc.Select(SendGridExtensions.ToSendGridAddress).ToList()); } foreach (var content in message.Contents) { m.AddContent(content.MediaType, content.Content); } foreach (var attachment in message.Attachments) { m.AddAttachment(attachment.Filename, Convert.ToBase64String(attachment.Data), attachment.MediaType, attachment.Disposition.ToSendGridDisposition(), attachment.ContentId); } var response = await sendGrid.SendEmailAsync(m, cancellationToken); if (response.StatusCode == HttpStatusCode.Accepted) { return(string.Empty); } if (response.StatusCode == HttpStatusCode.Created) { return(string.Empty); } using var stream = await response.Body.ReadAsStreamAsync(); var errorResponse = await JsonSerializer.DeserializeAsync <SendGridErrorResponse>(stream); if (errorResponse.Errors.Count == 0) { Logger.LogError("Sending mail has failed without an error."); return(string.Empty); // no retry } foreach (var error in errorResponse.Errors) { Logger.LogError($"SendGrid delivery error: [{error.Field} {error.ErrorId}] {error.Message}"); } return(string.Empty); }
public static async Task <bool> Sendemail() { try { string mailKey = Environment.GetEnvironmentVariable("mailkey"); var client = new SendGridClient(mailKey); var msg = new SendGridMessage(); msg.SetFrom(new EmailAddress(SendEmailNotification.From, Environment.GetEnvironmentVariable("mailfromgroupname"))); StringBuilder eMailContent = new StringBuilder(); eMailContent.Append(SendEmailNotification.eMailBody); var Toemails = SendEmailNotification.To.ToString().Split(";"); var recipients = new List <EmailAddress>(); foreach (string email in Toemails) { recipients.Add(new EmailAddress(email)); } msg.AddTos(recipients); var CCemails = SendEmailNotification.CC.ToString().Split(";"); if (SendEmailNotification.CC.Length > 0) { var CCrecipients = new List <EmailAddress>(); foreach (string ccemail in CCemails) { CCrecipients.Add(new EmailAddress(ccemail)); } msg.AddCcs(CCrecipients); } msg.SetSubject(SendEmailNotification.Subject); msg.AddContent(MimeType.Html, eMailContent.ToString().Replace("*****@*****.**", Environment.GetEnvironmentVariable("mailfromgroupid"))); var response = await client.SendEmailAsync(msg); if (response.StatusCode.ToString() != System.Net.HttpStatusCode.Accepted.ToString()) { throw new Exception("Send Grid Error out with code : " + response.StatusCode.ToString()); } } catch (Exception ex) { // Update Mail Status to Error and Log Error Message here throw ex; } return(true); }
public async Task <Response> SendEmail(SendGridRequest sendGridRequest) { var msg = new SendGridMessage(); msg.SetFrom(_options.Value.FromEmailAddress, _options.Value.FromAlias); msg.AddTos(sendGridRequest.To.ToList()); if (sendGridRequest.Cc?.Length > 0) { msg.AddCcs(sendGridRequest.Cc.ToList()); } if (sendGridRequest.Bcc?.Length > 0) { msg.AddBccs(sendGridRequest.Bcc.ToList()); } if (_options.Value.ReplyToEmailAddress != null) { msg.ReplyTo = new EmailAddress(_options.Value.ReplyToEmailAddress); } sendGridRequest.DynamicTemplateData.BaseUrl = _options.Value.BaseUrl; var dynamicTemplateDataObject = sendGridRequest.DynamicTemplateData; msg.SetTemplateData(dynamicTemplateDataObject); switch (sendGridRequest.Template) { case Enumerations.SendGridTemplateEnum.AddedToTickAddedToTicketTemplate: msg.SetTemplateId(_options.Value.AddedToTicketTemplate); break; case Enumerations.SendGridTemplateEnum.TicketUpdatedTemplate: msg.SetTemplateId(_options.Value.TicketUpdatedTemplate); break; default: throw new ArgumentOutOfRangeException(); } try { return(await _client.SendEmailAsync(msg)); } catch (Exception e) { throw e; } }
public async Task <Guid> SendEmailAsync(EmailMessage emailMessage) { var client = new SendGridClient(_smtpSettings.SendgridApiKey); var message = new SendGridMessage(); message.SetFrom(emailMessage.From.ToSendGridEmailAddress()); message.AddTos(emailMessage.Tos.Select(x => x.ToSendGridEmailAddress()).ToList()); if (emailMessage.Ccs.Any()) { message.AddCcs(emailMessage.Ccs.Select(x => x.ToSendGridEmailAddress()).ToList()); } if (emailMessage.Bccs.Any()) { message.AddBccs(emailMessage.Bccs.Select(x => x.ToSendGridEmailAddress()).ToList()); } message.Subject = emailMessage.Subject; message.PlainTextContent = emailMessage.Text; message.HtmlContent = emailMessage.Html; if (!emailMessage.Headers.ContainsKey("arragro-id")) { var arragroId = Guid.NewGuid(); emailMessage.Headers.Add("arragro-id", arragroId.ToString()); } foreach (var key in emailMessage.Headers.Keys) { message.AddHeader(key, emailMessage.Headers[key]); } foreach (var fileName in emailMessage.Attachments.Keys) { var emailAttachment = emailMessage.Attachments[fileName]; var fileBytes = emailAttachment.Stream.ToArray(); string base64Content = Convert.ToBase64String(fileBytes); message.AddAttachment(fileName, base64Content); } var response = await client.SendEmailAsync(message); if (response.StatusCode != System.Net.HttpStatusCode.Accepted) { var body = await response.Body.ReadAsStringAsync(); throw new Exception($"SendGrid responded with a {response.StatusCode} and the following message:\r\n\r\n{body}"); } return(Guid.Parse(emailMessage.Headers["arragro-id"])); }
/// <summary> /// Sends asynchronously. /// </summary> /// <param name="message">The message.</param> /// <returns> /// A task returning a boolean indicating /// whether or not the send was successful. /// </returns> public async Task SendAsync(EmailMessage message) { _logger.LogDebug($"Sending email: {JsonConvert.SerializeObject(message)}"); var to = message.To.Split(';', StringSplitOptions.RemoveEmptyEntries); var cc = string.IsNullOrWhiteSpace(message.CC) ? new List <string>() : message.CC.Split(';', StringSplitOptions.RemoveEmptyEntries).Except(to, StringComparer.OrdinalIgnoreCase).ToList(); var bcc = string.IsNullOrWhiteSpace(message.BCC) ? new List <string>() : message.BCC.Split(';', StringSplitOptions.RemoveEmptyEntries).Except(to, StringComparer.OrdinalIgnoreCase).ToList(); var sendGridMessage = new SendGridMessage(); sendGridMessage.SetFrom(string.IsNullOrWhiteSpace(message.From) ? _emailConfiguration.SupportEmail : message.From); sendGridMessage.AddTos(to.Select(t => new EmailAddress(t)).ToList()); if (cc.Count > 0) { sendGridMessage.AddCcs(cc.Select(t => new EmailAddress(t)).ToList()); } if (bcc.Count > 0) { sendGridMessage.AddBccs(bcc.Select(t => new EmailAddress(t)).ToList()); } if (message.Attachments != null && message.Attachments.Count > 0) { sendGridMessage.AddAttachments(message.Attachments.Select(attachment => new Attachment() { Filename = attachment.Key, Content = attachment.Value.ToBase64() }).ToList()); } if (message is TemplateEmailMessage templateEmailMessage) { sendGridMessage.SetTemplateId(templateEmailMessage.TemplateId); sendGridMessage.SetTemplateData(templateEmailMessage.TemplateData); } else if (message is HtmlEmailMessage htmlEmailMessage) { sendGridMessage.SetSubject(htmlEmailMessage.Subject); sendGridMessage.AddContent(MimeType.Html, htmlEmailMessage.Body); } var response = await _sendGridClient.SendEmailAsync(sendGridMessage); _logger.LogDebug($"Sendgrid response: {await response.Body?.ReadAsStringAsync()}"); if (response.StatusCode < HttpStatusCode.OK || response.StatusCode >= HttpStatusCode.Ambiguous) { throw new PasswordlessException($"Unable to send email : {await response.Body?.ReadAsStringAsync()}"); } }
public async Task <bool> SendEmail(string ToEmail, string subject, string bodyHtml, string ccEmail, string bccEmail) { try { var message = new SendGridMessage(); message.SetFrom(new EmailAddress(this._sendGridSettings.Value.SenderEmail, this._sendGridSettings.Value.fromName)); var lstRecipients = new List <EmailAddress>(); if (!string.IsNullOrEmpty(ccEmail)) { var lstCC = ccEmail.Trim(new char[] { ' ', '.', ',' }).Split(',').ToList(); foreach (var item in lstCC) { lstRecipients.Add(new EmailAddress() { Email = item }); } message.AddCcs(lstRecipients); } lstRecipients = new List <EmailAddress>(); if (!string.IsNullOrEmpty(bccEmail)) { var lstBCC = bccEmail.Trim(new char[] { ' ', '.', ',' }).Split(',').ToList(); foreach (var item in lstBCC) { lstRecipients.Add(new EmailAddress() { Email = item }); } message.AddBccs(lstRecipients); } message.SetSubject(subject); message.AddTo(new EmailAddress(ToEmail)); message.HtmlContent = bodyHtml; await SendMailDispatch(message); return(true); } catch (Exception) { throw; } }
private SendGridMessage Message(IEmailContent email) { SendGridMessage msg = MailHelper.CreateSingleEmailToMultipleRecipients( @from: new EmailAddress(email.From), tos: email.Recipients.Select(x => new EmailAddress(x)).ToList(), subject: email.Subject, plainTextContent: string.Empty, htmlContent: email.Body); if (email.Cc.Any()) { msg.AddCcs(email.Cc.Select(x => new EmailAddress(x)).ToList()); } return(msg); }
public static async Task <bool> Sendemail1() { try { // var client = new SendGridClient("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"); string mailKey = Environment.GetEnvironmentVariable("mailkey"); var client = new SendGridClient(mailKey); var msg = new SendGridMessage(); msg.SetFrom(new EmailAddress(SendEmailNotification.From, Environment.GetEnvironmentVariable("mailfromgroupname"))); var Toemails = SendEmailNotification.To.ToString().Split(";"); var recipients = new List <EmailAddress>(); foreach (string email in Toemails) { recipients.Add(new EmailAddress(email)); } msg.AddTos(recipients); var CCemails = SendEmailNotification.CC.ToString().Split(";"); var CCrecipients = new List <EmailAddress>(); foreach (string ccemail in CCemails) { CCrecipients.Add(new EmailAddress(ccemail)); } msg.AddCcs(CCrecipients); msg.SetSubject(SendEmailNotification.Subject); msg.AddContent(MimeType.Text, "This is just a simple test message!"); msg.AddContent(MimeType.Html, "<p>This is just a simple test message3!</p>"); var response = await client.SendEmailAsync(msg); } catch (Exception ex) { } return(true); }
protected override async Task SendEmailInternalAsync(EmailModel emailModel) { var msg = new SendGridMessage { From = emailModel.From != null ? new EmailAddress(emailModel.From.Email, emailModel.From.Name) : new EmailAddress(_config.EmailAddress, _config.Name), Subject = emailModel.Subject, HtmlContent = emailModel.HtmlBody, PlainTextContent = emailModel.TextBody // TODO: convert html to plain text? }; msg.AddTos(emailModel.Recipients.Select(a => new EmailAddress(a.Email, a.Name)).ToList()); if (emailModel.Cc?.Any() == true) { msg.AddCcs(emailModel.Cc.Select(a => new EmailAddress(a.Email, a.Name)).ToList()); } if (emailModel.Bcc?.Any() == true) { msg.AddBccs(emailModel.Bcc.Select(a => new EmailAddress(a.Email, a.Name)).ToList()); } if (emailModel.Attachments?.Any() == true) { msg.AddAttachments(emailModel.Attachments.Select(a => new global::SendGrid.Helpers.Mail.Attachment { Filename = a.Filename, Content = Convert.ToBase64String(a.Bytes), Type = a.ContentType, Disposition = a.ContentDisposition, ContentId = a.ContentId })); } var client = new SendGridClient(_config.Key); var response = await client.SendEmailAsync(msg); if (response.StatusCode != HttpStatusCode.OK) { var responseBody = await response.Body.ReadAsStringAsync(); throw new EmailSenderException($"SendGrid returned {response.StatusCode} status code ({responseBody})"); } }
public async Task <ResponseMessage> SendAsync(EmailMessage message) { // Message var msg = new SendGridMessage(); msg.Subject = message.Subject; msg.From = new EmailAddress(message.From); msg.PlainTextContent = message.Body; msg.AddTos(message.To.Select(s => new EmailAddress(s)).ToList()); if (message.CC.Count > 0) { msg.AddCcs(message.CC.Select(s => new EmailAddress(s)).ToList()); } if (message.BCC.Count > 0) { msg.AddBccs(message.BCC.Select(s => new EmailAddress(s)).ToList()); } if (message.Attachments != null && message.Attachments.Any()) { foreach (var attachment in message.Attachments.Where(x => x != null && x.Length > 0)) { using (var ms = new MemoryStream()) { attachment.CopyTo(ms); var fileBytes = ms.ToArray(); msg.AddAttachment(new Attachment { Filename = attachment.FileName, Content = Convert.ToBase64String(fileBytes) }); } } } // Send var client = new SendGridClient(this.settings.ApiKey); var response = await client.SendEmailAsync(msg); // Return return(new ResponseMessage(response.StatusCode.ToString())); }
//public async Task<Response> SendEmail(Email email) //{ // try // { // var client = new SendGridClient(_sendGridApiKey); // var msg = MailHelper.CreateSingleEmail( // email.From, email.To, email.Subject, email.PlainTextContent, email.HtmlContent); // var response = await client.SendEmailAsync(msg); // return response; // } // catch (Exception ex) // { // throw; // } //} public async Task<Response> SendTestEmail(List<string> recipients, List<string> Bcclist, List<string> Cclist, string subject, string bodyHtml, string sender) { try { var client = new SendGridClient(_sendGridApiKey); var from = MailHelper.StringToEmailAddress(sender); var msg = new SendGridMessage(); var tos = recipients.Select(x => MailHelper.StringToEmailAddress(x)).ToList(); msg.SetFrom(from); msg.SetGlobalSubject(subject); //use htmlcontent only if you are sending only HTML if (!string.IsNullOrEmpty(bodyHtml)) { msg.AddContent(MimeType.Html, bodyHtml); } //The AddTos method below accepts List<EmailAddress> to add multiple recipients with Personalization msg.AddTos(tos); if (Cclist != null) { if (Cclist.Count > 0) { var Ccs = Cclist.Select(x => MailHelper.StringToEmailAddress(x)).ToList(); msg.AddCcs(Ccs); } } if (Bcclist != null) { if (Bcclist.Count > 0) { var Bccs = Bcclist.Select(x => MailHelper.StringToEmailAddress(x)).ToList(); msg.AddBccs(Bccs); } } return await client.SendEmailAsync(msg); } catch (Exception ex) { throw; } }
static async Task ExecuteMessage(object dynamicTemplateData) { var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY"); // SendGrid API key set on windows environment variable Console.WriteLine("API KEY: " + apiKey); var credentials = new NetworkCredential("user", "password"); var proxy = new WebProxy("http://proxy-here", true, null, credentials); var client = new SendGridClient(proxy, apiKey); var msg = new SendGridMessage(); msg.SetFrom(new EmailAddress("*****@*****.**", "FromName")); msg.AddTo(new EmailAddress("*****@*****.**", "ToName")); var emails = new List <EmailAddress> { new EmailAddress("*****@*****.**", "Example User4"), new EmailAddress("*****@*****.**", "Example User5") }; // add a list of e-mails to send msg.AddTos(emails); // copy e-mails to send msg.AddCc(new EmailAddress("*****@*****.**", "Example User6")); emails = new List <EmailAddress> { new EmailAddress("*****@*****.**", "Example User8"), new EmailAddress("*****@*****.**", "Example User9") }; // add a list of copy e-mails to send msg.AddCcs(emails); // add Cco (blind copy) msg.AddBcc(new EmailAddress("test10example.com", "Example User10")); msg.SetTemplateId("d-1edc1791a1fd49dcbbcc9c8eae276338"); // template id from sendgrid | example.html msg.SetTemplateData(dynamicTemplateData); var response = await client.SendEmailAsync(msg); Console.WriteLine(response.StatusCode); }
public Task SendAsync(MailMessageDTO message) { var web = new SendGridClient(apiKey); var msg = new SendGridMessage() { From = ConvertMailAddress(message.From), ReplyTo = message.ReplyTo.Select(ConvertMailAddress).FirstOrDefault(), Subject = message.Subject }; msg.AddTos(message.To.Select(ConvertMailAddress).ToList()); if (message.Cc.Count > 0) { msg.AddCcs(message.Cc.Select(ConvertMailAddress).ToList()); } if (message.Bcc.Count > 0) { msg.AddBccs(message.Bcc.Select(ConvertMailAddress).ToList()); } if (message.Attachments.Count > 0) { msg.AddAttachments(message.Attachments.Select(ConvertAttachment).ToList()); } if (string.IsNullOrWhiteSpace(message.BodyHtml)) { msg.PlainTextContent = message.BodyText; } else { msg.HtmlContent = message.BodyHtml; } ProcessTemplate(msg, message.MailingTemplate); OnMessageSending(msg); return(web.SendEmailAsync(msg)); }
async Task IEmailSender.SendGridEmailWithAttachmentAsync(string emailAdd, string[] emailCC, string subject, string message, string base64string, string fileName) { //var apiKey = "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"; var client = new SendGridClient(apiKey); var msg = new SendGridMessage() { From = new EmailAddress("*****@*****.**", "iBROKA"), Subject = subject, PlainTextContent = message, HtmlContent = message }; msg.AddAttachment(fileName, base64string); msg.AddTo(new EmailAddress(emailAdd, emailAdd)); if (!string.IsNullOrEmpty(emailCC[0]) && !string.IsNullOrEmpty(emailCC[1])) { List <EmailAddress> emails = new List <EmailAddress>(); if (emailCC[0] != emailAdd && emailCC[0] != emailCC[1]) { emails.Add(new EmailAddress(emailCC[0], emailCC[0])); } if (emailCC[1] != emailAdd && emailCC[0] != emailCC[1]) { emails.Add(new EmailAddress(emailCC[1], emailCC[1])); } if (emails.Count() > 0) { msg.AddCcs(emails); } } else if (!string.IsNullOrEmpty(emailCC[0])) { if (emailCC[0] != emailAdd) { msg.AddCc(new EmailAddress(emailCC[0], emailCC[0])); } } var response = await client.SendEmailAsync(msg); }
private SendGridMessage Map(EmailMessage message) { var msg = new SendGridMessage(); msg.SetFrom(new SendGridEmailAddress(message.From.Address, message.From.DisplayName)); msg.AddTos(message.Tos.Select(x => new SendGridEmailAddress(x)).ToList()); if (message.Ccs != null && message.Ccs.Any()) { msg.AddCcs(message.Ccs.Select(x => new SendGridEmailAddress(x)).ToList()); } if (message.Bccs != null && message.Ccs.Any()) { msg.AddBccs(message.Bccs.Select(x => new SendGridEmailAddress(x)).ToList()); } msg.SetSubject(message.Subject); msg.HtmlContent = message.Body; return(msg); }
public async Task SendAsync(string from, IList <string> tos, IList <string> ccs, string subject, string htmlContent) { var client = new SendGridClient(_emailConfigs.SendGridApiKey); var msg = new SendGridMessage() { From = new EmailAddress(from, "Course Studio Team"), Subject = subject, HtmlContent = htmlContent }; msg.AddTos(tos.Select(to => new EmailAddress(to)).ToList()); if (ccs.Any()) { msg.AddCcs(ccs.Select(cc => new EmailAddress(cc)).ToList()); } var response = await client.SendEmailAsync(msg); if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { throw new BadRequestException("Failed to send email"); } }
public async Task <ResponseMessage> SendAsync(EmailMessage message) { // Message var msg = new SendGridMessage(); msg.Subject = message.Subject; msg.From = new EmailAddress(message.From); msg.PlainTextContent = message.Body; msg.AddTos(message.To.Select(s => new EmailAddress(s)).ToList()); if (message.CC.Count > 0) { msg.AddCcs(message.CC.Select(s => new EmailAddress(s)).ToList()); } if (message.BCC.Count > 0) { msg.AddBccs(message.BCC.Select(s => new EmailAddress(s)).ToList()); } if (message.Attachments.Count > 0) { msg.AddAttachments(message.Attachments.Select(s => new Attachment { Filename = s, Content = Convert.ToBase64String(System.IO.File.ReadAllBytes(s)) }).ToList()); } // Send var client = new SendGridClient(this.settings.ApiKey); var response = await client.SendEmailAsync(msg); // Return return(new ResponseMessage(response.StatusCode.ToString())); }
public async Task <Response> SendEmail(EmailAddress from, IEnumerable <EmailAddress> tos, string templateId, object dynamicTemplateData, IEnumerable <Attachment> attachments = null, IEnumerable <EmailAddress> ccList = null) { var emailMessage = new SendGridMessage(); emailMessage.SetFrom(from); emailMessage.AddTos(tos.ToList()); if (ccList != null && ccList.Count() > 0) { emailMessage.AddCcs(ccList.ToList()); } emailMessage.SetTemplateId(templateId); emailMessage.SetTemplateData(dynamicTemplateData); if (attachments != null) { emailMessage.AddAttachments(attachments); } var response = await _sendGridClient.SendEmailAsync(emailMessage); return(response); }
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); }
private SendGridMessage GetSendGridMessageFromRockEmailMessage(RockEmailMessage rockEmailMessage) { var sendGridMessage = new SendGridMessage(); // To rockEmailMessage.GetRecipients().ForEach(r => sendGridMessage.AddTo(r.To, r.Name)); if (rockEmailMessage.ReplyToEmail.IsNotNullOrWhiteSpace()) { sendGridMessage.ReplyTo = new EmailAddress(rockEmailMessage.ReplyToEmail); } sendGridMessage.From = new EmailAddress(rockEmailMessage.FromEmail, rockEmailMessage.FromName); // CC var ccEmailAddresses = rockEmailMessage .CCEmails .Where(e => e != string.Empty) .Select(cc => new EmailAddress { Email = cc }) .ToList(); if (ccEmailAddresses.Count > 0) { sendGridMessage.AddCcs(ccEmailAddresses); } // BCC var bccEmailAddresses = rockEmailMessage .BCCEmails .Where(e => e != string.Empty) .Select(cc => new EmailAddress { Email = cc }) .ToList(); if (bccEmailAddresses.Count > 0) { sendGridMessage.AddBccs(bccEmailAddresses); } // Subject sendGridMessage.Subject = rockEmailMessage.Subject; // Body (plain text) sendGridMessage.PlainTextContent = rockEmailMessage.PlainTextMessage; // Body (html) sendGridMessage.HtmlContent = rockEmailMessage.Message; // Communication record for tracking opens & clicks sendGridMessage.CustomArgs = rockEmailMessage.MessageMetaData; if (CanTrackOpens) { sendGridMessage.TrackingSettings = new TrackingSettings { ClickTracking = new ClickTracking { Enable = true }, OpenTracking = new OpenTracking { Enable = true } }; } // Attachments if (rockEmailMessage.Attachments.Any()) { foreach (var attachment in rockEmailMessage.Attachments) { if (attachment != null) { MemoryStream ms = new MemoryStream(); attachment.ContentStream.CopyTo(ms); sendGridMessage.AddAttachment(attachment.FileName, Convert.ToBase64String(ms.ToArray())); } } } return(sendGridMessage); }
///<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)); }
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.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); }