/// <summary> /// /// <para>BroadcastEmail:</para> /// /// <para>Sends an e-mail to given addresses with given body</para> /// /// <para>Check <seealso cref="IBMailServiceInterface.BroadcastEmail"/> for detailed documentation</para> /// /// </summary> public bool BroadcastEmail( List <BMailServicerReceiverStruct> _Receivers, string _Subject, string _PlainText, string _HtmlText, Action <string> _ErrorMessageAction = null) { if (_Receivers.Count == 0) { return(false); } try { var Receivers = new List <EmailAddress>(); foreach (var Receiver in _Receivers) { Receivers.Add(new EmailAddress(Receiver.ReceiverEmail, Receiver.ReceiverName)); } var SGMessage = MailHelper.CreateSingleEmailToMultipleRecipients(SenderInfo, Receivers, _Subject, _PlainText, _HtmlText); using (var SendEmailTask = SGClient.SendEmailAsync(SGMessage)) { SendEmailTask.Wait(); } } catch (Exception e) { _ErrorMessageAction?.Invoke("BMailServiceSendGrid->BroadcastEmail: " + e.Message + ", Trace: " + e.StackTrace); return(false); } return(true); }
public async Task <string> SendConfirmationEmail(GuestBook Guest) { try { var body = string.Format(@"<h3>Thank you for contacting Elizabeth and Brian!</h3> <p>{0}, <br/>We appreciate you reaching out to us. One of us will be getting back to you shortly. <br/><br/>Please see the message you sent to us through our website,<a href="www.harneyhall.com">HarneyHall.com</a>: <br/> Name: {1} <br/>Email: {2} <br/>Phone: {3} <br/>Message: {4}</p><br/><br/>Call Brian at (630)849-6948 or Elizabeth at (708)310-5765", Guest.Name, Guest.Name, Guest.Email, Guest.Phone, Guest.Message); var recipients = new List <EmailAddress>() { new EmailAddress(_config["MailService:Receiver1Name"], _config["MailService:Receiver1"]), new EmailAddress(_config["MailService:Receiver2Name"], _config["MailService:Receiver2"]), new EmailAddress(Guest.Email) }; var from = new EmailAddress("HarneyHall RSVP", _config["MailService:RsvpFrom"]); var subject = "Secret Wedding Message Sent!"; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, recipients, subject, null, body); var client = new SendGridClient(_config["MailService:ApiKey"]); var response = await client.SendEmailAsync(msg); return("successfully sent email"); } catch (Exception e) { return(e.Message); } }
private async Task SendSendGridMessage(string From, string EmailDisplayName, List <EmailAddress> tos, string Subject, string HTMLContent) { var client = new SendGridClient(_email.SendGridApiKey); var from = new EmailAddress(From, EmailDisplayName); var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, Subject, "", HTMLContent, false); var response = await client.SendEmailAsync(msg).ConfigureAwait(false); }
public static void PioneerUnitIssueMessage(ProductionUnit currentProductionUnit, string note, string details) { var dbLog = new ApplicationDbContext(); try { var client = new SendGridClient(MailSendGridAPIKey); var from = new EmailAddress("*****@*****.**", "Myfood Hub Bot"); var pioneerName = string.Format("{0} #{1}", currentProductionUnit.owner.pioneerCitizenName, currentProductionUnit.owner.pioneerCitizenNumber); List <EmailAddress> tos = new List <EmailAddress> { new EmailAddress("*****@*****.**", pioneerName) }; var subject = string.Empty; var htmlContent = string.Empty; if (currentProductionUnit.owner != null && currentProductionUnit.owner.language != null) { switch (currentProductionUnit.owner.language.description) { case "fr": subject = string.Format("[myfood] Incident enregistré chez {0} #{1}", currentProductionUnit.owner.pioneerCitizenName, currentProductionUnit.owner.pioneerCitizenNumber); htmlContent = string.Format("Bonjour, </br></br>" + "La serre {0} #{1} vient d'enregistrer un incident critique.</br>" + "Detail : {2} {3}</br></br>" + "Bien à vous,", currentProductionUnit.owner.pioneerCitizenName, currentProductionUnit.owner.pioneerCitizenNumber, note, details); break; default: subject = string.Format("[myfood] Issue recorded at {0} #{1}", currentProductionUnit.owner.pioneerCitizenName, currentProductionUnit.owner.pioneerCitizenNumber); htmlContent = string.Format("Hi {0}, </br></br>" + "The greenhouse {0} #{1} has met a critical issue.</br>" + "Detail : {2} {3}</br></br>" + "Have a nice day,", currentProductionUnit.owner.pioneerCitizenName, currentProductionUnit.owner.pioneerCitizenNumber, note, details); break; } } else { subject = string.Format("[myfood] Issue recorded at {0} #{1}", currentProductionUnit.owner.pioneerCitizenName, currentProductionUnit.owner.pioneerCitizenNumber); htmlContent = string.Format("Hi {0}, </br></br>" + "The greenhouse {0} #{1} has met a critical issue.</br>" + "Detail : {2} {3}</br></br>" + "Have a nice day,", currentProductionUnit.owner.pioneerCitizenName, currentProductionUnit.owner.pioneerCitizenNumber, note, details); } var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, "", htmlContent, false); msg.AddCc("*****@*****.**"); var response = client.SendEmailAsync(msg); } catch (Exception ex) { dbLog.Logs.Add(Log.CreateErrorLog(String.Format("Error with Mail Notification"), ex)); dbLog.SaveChanges(); } }
public static void Run(string myBlob, string filename, Order ordersRow, TraceWriter log, out SendGridMessage message) { var email = ordersRow.Email; log.Info($"Order from Email: {email}\n License file name: {filename} "); var byteText = System.Text.Encoding.UTF8.GetBytes(myBlob); var initiator = new EmailAddress("*****@*****.**", "Paycor"); var attachments = new List <SendGrid.Helpers.Mail.Attachment> { new SendGrid.Helpers.Mail.Attachment { Content = System.Convert.ToBase64String(byteText), Type = "text/plain", Filename = "license.lic", Disposition = "attachment", ContentId = "License File" } }; var recipientEmailAddresses = new List <EmailAddress> { new EmailAddress(email, "Ashif Anwar") }; message = MailHelper.CreateSingleEmailToMultipleRecipients(initiator, recipientEmailAddresses, "Thank you for your order", "Your license file is attached", "Your license file is attached"); message.AddAttachments(attachments); }
public virtual async Task SendAsync(Message message) { #region SendGridClient var client = new SendGridClient(_settings.Value.ApiKey); var from = new EmailAddress(_settings.Value.UserName); var subject = message.Subject; var htmlContent = message.Body.Replace("\r\n", "<br />").Replace("\n", "<br />"); var toAdresses = message.To.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).Select(address => new EmailAddress(address)).ToList(); var mailMessage = MailHelper.CreateSingleEmailToMultipleRecipients(from, toAdresses, subject, message.Body, htmlContent); if (message.Attachments != null) { mailMessage.Attachments = new List <Attachment>(); foreach (var att in message.Attachments) { mailMessage.Attachments.Add(new Attachment() { Content = Convert.ToBase64String(att.Content), Filename = att.Filename, Type = att.Type }); } } await client.SendEmailAsync(mailMessage); #endregion }
public async Task <Response> SendMail(EmailParameters model) { MailSendingModel emailmodel; try { emailmodel = await PrepareEmail(model); } catch (ArgumentNullException ex) { await AddLogInfo(string.Empty, ex.Message); throw new ArgumentNullException(ex.Message, ex); } var msg = MailHelper.CreateSingleEmailToMultipleRecipients(emailmodel.From, emailmodel.To, emailmodel.Subject, emailmodel.PlainTextContent, emailmodel.HtmlContent); var response = await _client.SendEmailAsync(msg); if (response.StatusCode != System.Net.HttpStatusCode.Accepted) { await AddLogInfo(response.StatusCode.ToString(), $"Email send is failed for DeviceID:{model.UDID}"); throw new ArgumentException(response.StatusCode.ToString()); } await AddLogInfo(response.StatusCode.ToString(), $"Email Sent for DeviceID:{model.UDID}"); return(response); }
/// <summary> /// Sends notification emails to all HR users who are members of specified company. /// </summary> /// <param name="companyId"></param> private async void SendNotifications(int companyId) { // Get API key var apiKey = _config.GetSection("SendGridAPIKey").Value; // Create SendGrid client var client = new SendGridClient(apiKey); var from = new EmailAddress("*****@*****.**", "HR Web Application"); // Get users assigned to given compnay var users = await _context.Users.Where(m => m.CompanyId.HasValue && m.CompanyId == companyId).ToListAsync(); // Craete email list List <EmailAddress> tos = new List <EmailAddress>(); // Populate with data foreach (var user in users) { tos.Add(new EmailAddress(user.EmailAddress, user.FirstName + user.LastName)); } var subject = "You received new application"; var htmlContent = "<strong>Hello you have new application waiting for you!</strong>"; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, "", htmlContent, false); _ = client.SendEmailAsync(msg); }
public void SendBulkEmail(String toEmailList, String subject, String contents) { List <EmailAddress> tolist = new List <EmailAddress>(); String[] list = toEmailList.Split('|'); foreach (String s in list) { tolist.Add(new EmailAddress(s, "")); } if (tolist.Count > 0) { var client = new SendGridClient(API_KEY); var from = new EmailAddress("*****@*****.**", "New offer for jetwing hotels"); var plainTextContent = contents; var htmlContent = "<p>" + contents + "</p>"; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tolist, subject, plainTextContent, htmlContent); string filePath = HttpContext.Current.Request.MapPath("~/Utils/documents/details.pdf"); var bytes = File.ReadAllBytes(filePath); var file = Convert.ToBase64String(bytes); msg.AddAttachment("details.pdf", file); var response = client.SendEmailAsync(msg); } }
public async Task <bool> Send(EmailViewModel email) { var apiKey = _settings.SendGridApiKey; var client = new SendGridClient(apiKey); var from = new EmailAddress(_settings.SenderAddress, _settings.SenderName); var tos = new List <EmailAddress>(); foreach (var recipient in email.To.Split(',')) { tos.Add(new EmailAddress(email.To)); } var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, email.Subject, email.Text, null); try { var response = await client.SendEmailAsync(msg); // TODO: need to log the error when the response status is not 200 return(response.StatusCode == HttpStatusCode.OK); } catch (Exception ex) { // TODO: log the error message either physically or Azure table storage return(false); } }
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}."); } }
public static void SendErrorEmail(string subject, string content) { try { var apiKey = ConfigHelper.GetSendGridAPIKey(); var client = new SendGridClient(apiKey); List <EmailAddress> emailTos = new List <EmailAddress>(); var tos = ConfigHelper.GetEmailErrorTo(); foreach (var to in tos) { emailTos.Add(new EmailAddress(to)); } EmailAddress emailFrom = new EmailAddress(ConfigHelper.GetEmailErrorFrom()); var message = MailHelper.CreateSingleEmailToMultipleRecipients(emailFrom, emailTos, subject, content, String.Empty); if (message != null) { message.SetBypassListManagement(true); client.SendEmailAsync(message); } } catch (Exception e) { } }
public async Task <bool> SendEmail(EmailDetails email, TelemetryClient telelemtry, CancellationToken cancellationToken) { try { var client = new SendGridClient(ApiKey); var from = new EmailAddress(email.Sender); var to = email.Recipients .Select(x => new EmailAddress(x)) .ToList(); var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, email.Subject, plainTextContent: email.Body, // currently not supporting plain text htmlContent: email.Body); var response = await client.SendEmailAsync(msg, cancellationToken); return(response.StatusCode == System.Net.HttpStatusCode.Accepted); } catch (Exception e) { telelemtry.TrackException(e, new Dictionary <string, string> { [this.GetType().Name] = email.Subject }); return(false); } }
/// <summary> /// SendEmailAsync /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task <SendMailResponse> SendEmailAsync(ISendMailRequest request) { var response = new SendMailResponse(); try { if (_client == null) { _client = new SendGridClient(_clientConfig.ApiKey); } var recipientList = request.Recipients.Select(recipient => new EmailAddress(recipient)).ToList(); var from = new EmailAddress(request.From, request.FromName); var plainTextContent = HtmlText.ConvertHtml(request.Message); var htmlContent = request.Message; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, recipientList, request.Subject, plainTextContent, htmlContent); await _client.SendEmailAsync(msg); } catch (Exception ex) { response.ErrorMessage = ex.Message; response.IsSuccess = false; } return(response); }
public async Task SendAsync(String toEmail, String subject, String contents, String FP, String cc) { var client = new SendGridClient(API_KEY); var from = new EmailAddress("*****@*****.**"); var to = new List <EmailAddress> { new EmailAddress(cc, ""), new EmailAddress(toEmail, ""), }; var plainTextContent = contents; var htmlContent = "<p>" + contents + "</p>"; var showAllRecipients = false; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, subject, plainTextContent, htmlContent, showAllRecipients); if (FP != null) { string fullPath = Path.Combine("/Users/PX Hao/source/repos/WebApplication2/File Saved", FP); string fileName = Path.GetFileName(fullPath); string type = Path.GetExtension(fullPath); var bytes = File.ReadAllBytes(fullPath); var file02 = Convert.ToBase64String(bytes); msg.AddAttachment(fileName, file02, type); } var response = await client.SendEmailAsync(msg); }
public static async Task SendEmails(CloudBlobContainer cloudBlobContainer, AudioFileName audioFile, CloudBlockBlob distBlockBlob) { var emailBlobReference = cloudBlobContainer.GetBlockBlobReference("emails"); var emailList = (await emailBlobReference.DownloadTextAsync().ConfigureAwait(false)).Split('\n'); var apiKey = Environment.GetEnvironmentVariable("SendGrid.ApiKey", EnvironmentVariableTarget.Process); var client = new SendGridClient(apiKey); var fromEmail = emailList.First().Split(','); var from = new EmailAddress(fromEmail[0], fromEmail[1]); var subject = $"{audioFile.Masechta.ToUppercaseWords()} Daf {audioFile.Daf}"; var plainTextContent = $"{audioFile.Masechta.ToUppercaseWords()} Daf {audioFile.Daf} is now available. https://torahis.life/#/shiurim(daf-yomi&shabbos)"; var htmlContent = $"<a href=\"https://torahis.life/#/shiurim(daf-yomi&shabbos)\">{audioFile.Masechta.ToUppercaseWords()} Daf {audioFile.Daf}</a> is now available."; var groupedRecipients = emailList.Skip(1) .Select(line => line.Split(',')) .Select(lineParts => (bool.Parse(string.IsNullOrWhiteSpace(lineParts[2]) ? bool.FalseString : lineParts[2]), new EmailAddress(lineParts[0], lineParts[1]))) .ToLookup(r => r.Item1); if (groupedRecipients.Contains(false)) { var to = groupedRecipients[false].Select(recipient => recipient.Item2).ToList(); var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, subject, plainTextContent, htmlContent); var response = await client.SendEmailAsync(msg); } if (groupedRecipients.Contains(true)) { var to = groupedRecipients[true].Select(recipient => recipient.Item2).ToList(); var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, to, subject, plainTextContent, htmlContent); var bytes = new byte[distBlockBlob.Properties.Length]; await distBlockBlob.DownloadToByteArrayAsync(bytes, 0).ConfigureAwait(false); msg.AddAttachment($"{audioFile.Masechta.ToUppercaseWords()} Daf {audioFile.Daf}", Convert.ToBase64String(bytes)); var response = await client.SendEmailAsync(msg); } }
public async Task PostMessage(string subjectTxt, string emailContent, string toSend, string name) { var apiKey = _configuration.GetSection("SENDGRID_API_KEY").Value; var client = new SendGridClient(apiKey); List <EmailAddress> tos = new List <EmailAddress> { new EmailAddress(toSend, name) }; var subject = subjectTxt; var htmlContent = emailContent; var displayRecipients = false; // set this to true if you want recipients to see each others mail id var msg = MailHelper.CreateSingleEmailToMultipleRecipients(From, tos, subject, "", htmlContent, false); /*var banner2 = new Attachment() * { * Content = Convert.ToBase64String(), * Type = "image/png", * Filename = "banner2.png", * Disposition = "inline", * ContentId = "Banner 2" * };*/ //msg.AddAttachment(banner2); /*msg.SetFooterSetting( * true, * "Some Footer HTML", * "<strong>Some Footer Text</strong>");*/ //msg.SetClickTracking(true); var response = await client.SendEmailAsync(msg); }
public static async Task <Response> SendSingleEmailToMultipleRecipients(IConfiguration configuration, EmailOptions options) { var settings = MailSettings(configuration); var client = new SendGridClient(settings.ApiKey); var from = new EmailAddress(settings.FromEmail, settings.FromName); List <EmailAddress> tos = options.ToMailsList.Select(t => new EmailAddress(t.Email, t.Name)).ToList(); var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, options.Subject, options.PlainBody, options.HtmlBody, false); msg.AddCc(options.CcMail.Email, options.CcMail.Name); if (options.Attachments != null && options.Attachments.Any()) { msg.Attachments = options.Attachments.Select(a => new SendGrid.Helpers.Mail.Attachment { Content = Convert.ToBase64String(a.Content), Filename = a.Name, Type = a.ContentType }).ToList(); } var response = await client.SendEmailAsync(msg); return(response); }
public void SendBulkEmail(List <String> emailList, String subject, String contents, String letterPath) { var client = new SendGridClient(API_KEY); var from = new EmailAddress("*****@*****.**", "Be Our Guest"); var tos = new List <EmailAddress>(); foreach (String email in emailList) { tos.Add(new EmailAddress(email, "")); } var plainTextContent = contents; var htmlContent = "<p>" + contents + "</p>"; var showAllRecipients = false; // Set to true if you want the recipients to see each others email addresses var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, plainTextContent, htmlContent, showAllRecipients ); var bytes = File.ReadAllBytes(letterPath); var file = Convert.ToBase64String(bytes); msg.AddAttachment("Newsletter.jpeg", file); var response = client.SendEmailAsync(msg); }
public static async Task <bool> EnviarEmailAsync(Mensageria menssagem, string email) { //Quem enviar a mensagem var sender = new EmailAddress("*****@*****.**"); var client = new SendGridClient(apiKey); var destinatarios = new List <EmailAddress>(); destinatarios.Add(new EmailAddress(email)); //para esta montando a mensagem remetente, destino, assunto, mensagem, string vazia, false var msg = MailHelper.CreateSingleEmailToMultipleRecipients(sender, destinatarios, menssagem.Assunto, "", menssagem.Mensagem, false); try { if (!String.IsNullOrEmpty(menssagem.Mensagem) && !String.IsNullOrEmpty(menssagem.Assunto)) { var response = await client.SendEmailAsync(msg); return((int)response.StatusCode <= 203 ? true : false); } return(false); } catch (Exception e) { return(false); } }
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 async Task KirimNotifikasi(string namafile) { var apiKey = "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"; //EmailHelpers.SendridAPI; var client = new SendGridClient(apiKey); var from = new EmailAddress("*****@*****.**", "Admin Yakkum"); List <EmailAddress> tos = new List <EmailAddress>() { new EmailAddress { Email = "*****@*****.**" }, new EmailAddress { Email = "*****@*****.**" }, new EmailAddress { Email = "*****@*****.**" } }; var subject = "Notifikasi Dokumen Sudah Terupload"; var htmlContent = $"<p>File dengan nama {namafile} berhasil diupload </p>"; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, "", htmlContent, false); var response = await client.SendEmailAsync(msg); }
public async Task SendEmailAsync(Email email, CancellationToken cancellationToken = default) { // To not send emails from dev environments, don't store an apikey password in the local secrets if (string.IsNullOrWhiteSpace(ApiKey) || ApiKey == "x") { return; } var from = new SendGrid.Helpers.Mail.EmailAddress(Constants.TrashMobEmailAddress, Constants.TrashMobEmailName); var tos = new List <SendGrid.Helpers.Mail.EmailAddress>(); foreach (var address in email.Addresses) { tos.Add(new SendGrid.Helpers.Mail.EmailAddress(address.Email, address.Name)); } try { var client = new SendGridClient(ApiKey); var message = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, email.Subject, email.Message, email.HtmlMessage); var response = await client.SendEmailAsync(message, cancellationToken).ConfigureAwait(false); Console.WriteLine(response); } catch (Exception ex) { Console.WriteLine(ex); } }
public void Send(EmailTemplate template, params string[] recipients) { if (template == null) { throw new ArgumentNullException(nameof(template)); } if (recipients == null) { throw new ArgumentNullException(nameof(recipients)); } if (recipients.Length == 0) { throw new ArgumentException(@"Value cannot be an empty collection.", nameof(recipients)); } var client = new SendGridClient(_settings.ApiKey); var msg = MailHelper.CreateSingleEmailToMultipleRecipients( new EmailAddress(_from), recipients.Select(x => new EmailAddress(x)).ToList(), template.Subject, !template.IsHtml ? template.GetBody() : null, template.IsHtml ? template.GetBody() : null, true); client.SendEmailAsync(msg).Wait(); }
public async Task SendEmail(string subject, string content) { using (AsyncScopedLifestyle.BeginScope(container)) { var configuration = container.GetInstance <IConfiguration>(); var employeeRepository = container.GetInstance <IEmployeeRepository>(); var apiKey = configuration.GetSection("SENDGRID_API_KEY").Value; var client = new SendGridClient(apiKey); var from = new EmailAddress("*****@*****.**", "Example User 1"); var employees = await employeeRepository.GetEmployees(); List <EmailAddress> tos = new List <EmailAddress>(); foreach (Employee employee in employees) { var role = await _userManager.GetRolesAsync(employee.User); if (role.FirstOrDefault() == "Manager" || role.FirstOrDefault() == "Finance") { tos.Add(new EmailAddress(employee.User.Email)); } } var htmlContent = content; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, "", htmlContent); var response = await client.SendEmailAsync(msg); } }
/// <summary> /// メールを送信する /// </summary> /// <param name="mailInfo">メール情報</param> /// <returns>メール送信結果(HTTPステータスコードとレスポンスボディ)</returns> public async Task <KeyValuePair <HttpStatusCode, string> > SendMail(MailInfo mailInfo) { _logger.EnterJson("{0}", new { mailInfo }); int code = 0; string body = null; try { var client = new SendGridClient(_appSettings.SendGridApiKey); var from = new EmailAddress(mailInfo.MailAddressFrom); var tos = new List <EmailAddress>(); foreach (var address in mailInfo.MailAddressTo.Split(",")) { tos.Add(new EmailAddress(address)); } string mailText = string.Format( _appSettings.MailTextFormat, mailInfo.CustomerNumber.ToString(), mailInfo.CustomerName, mailInfo.EquipmentSerialNumber, mailInfo.EquipmentNumber, mailInfo.EquipmentName, mailInfo.TypeCode, mailInfo.ErrorCode, mailInfo.AlarmLevel.ToString(), mailInfo.EventDate, mailInfo.AlarmDescription); var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, mailInfo.MailSubject, mailText, string.Empty, true); Response response = null; await _sendGridPolly.ExecuteAsync(async() => { response = await client.SendEmailAsync(msg); return(response); }); code = (int)response.StatusCode; body = await response.Body?.ReadAsStringAsync(); if (code < 200 || code > 299) { throw new RmsException(string.Format("status error. (StatusCode = {0})", code)); } return(new KeyValuePair <HttpStatusCode, string>(response.StatusCode, body)); } catch (Exception e) { throw new RmsException(string.Format("メール送信の要求に失敗しました。(StatusCode = {0}, ResponseBody = {1})", code, body), e); } finally { _logger.LeaveJson("{0}", new { code, body }); } }
/// <summary> /// Makes a call to the Sendgrid API in order to send an email with the specified recipient(s), /// subject, html content, and attachement. If the attachment is null, it is ignored. /// Otherwise a check if performed to ensure that the file exists, and it is attached if it exists. /// Otherwise method returns without sending. /// /// </summary> /// <param name="from"></param> /// <param name="recipients"></param> /// <param name="subject"></param> /// <param name="htmlContent"></param> /// <param name="file"></param> /// <returns>Task representing this request to Sendgrid API</returns> private static async Task SendEmailHelper(EmailAddress from, List <EmailAddress> recipients, string subject, string htmlContent, FileInfo file) { var plainTextContent = "Workplace-Futurists"; var showAllRecipients = false; // Set to true if you want the recipients to see each others email addresses var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, recipients, subject, plainTextContent, htmlContent, showAllRecipients ); if (file != null) { if (!File.Exists(file.FullName)) { Console.WriteLine(">\t" + file.Name + " does not exists"); return; } var bytes = File.ReadAllBytes(file.FullName); var content = Convert.ToBase64String(bytes); msg.AddAttachment("attachment.txt", content); } await sendGridClient.SendEmailAsync(msg); }
private bool SendGridEmail(string subject, string message) { // using SendGrid's C# Library // https://github.com/sendgrid/sendgrid-csharp // https://app.sendgrid.com/settings/api_keys if (string.IsNullOrEmpty(_sendGridApiKey) | string.IsNullOrEmpty(_toEmail) | string.IsNullOrEmpty(_fromEmail)) { _log.LogInformation("sendgridemail:not configured"); return(false); } message = ScrubResults(message); SendGridClient client = new SendGridClient(_sendGridApiKey); EmailAddress from = new EmailAddress(_fromEmail, null); List <EmailAddress> tos = new List <EmailAddress>(); foreach (string address in _toEmail.Split(';')) { tos.Add(new EmailAddress(address, null)); } string plainTextContent = message; string htmlContent = $"<body>{message}</body>"; SendGridMessage msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, plainTextContent, htmlContent); Response response = client.SendEmailAsync(msg).Result; _log.LogInformation($"sendgrid response: {JsonConvert.SerializeObject(response, Formatting.Indented)}"); return(true); }
static async Task Main(string[] args) { DotNetEnv.Env.Load(".env"); var apiKey = Environment.GetEnvironmentVariable("API_KEY"); var tos = Environment.GetEnvironmentVariable("TOS").Split(',').Select(to => new EmailAddress(to)).ToList(); var from = new EmailAddress(Environment.GetEnvironmentVariable("FROM"), "送信者名"); var subject = "[sendgrid-c#-example] フクロウのお名前はfullnameさん"; var plainTextContent = "familyname さんは何をしていますか?\r\n 彼はplaceにいます。"; var htmlContent = "<strong> familyname さんは何をしていますか?</strong><br />彼はplaceにいます。"; var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, plainTextContent, htmlContent); msg.AddSubstitutions(new Dictionary <string, string> { { "fullname", "田中 太郎" }, { "familyname", "田中" }, { "place", "中野" } }, 0); msg.AddSubstitutions(new Dictionary <string, string> { { "fullname", "佐藤 次郎" }, { "familyname", "佐藤" }, { "place", "目黒" } }, 1); msg.AddSubstitutions(new Dictionary <string, string> { { "fullname", "鈴木 三郎" }, { "familyname", "鈴木" }, { "place", "中野" } }, 2); msg.AddCategory("category1"); msg.AddHeader("X-Sent-Using", "SendGrid-API"); var image = Convert.ToBase64String(File.ReadAllBytes("gif.gif")); msg.AddAttachment("owl.gif", image, "image/gif", "attachment"); var client = new SendGridClient(apiKey); var response = await client.SendEmailAsync(msg); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Headers); Console.WriteLine(response.Body.ReadAsStringAsync().Result); }
/// <inheritdoc cref="NotificationProvider.Send(MessageParameterCollection)"/> public override async Task <NotificationResult> Send(MessageParameterCollection messageParameters) { var sgMessage = new SendGridMessage(messageParameters); var from = new EmailAddress(sgMessage.FromAddress); var tos = sgMessage.ToAddresses.Select(to => new EmailAddress(to)).ToList(); var subject = sgMessage.Subject; var plainTextContent = sgMessage.PlainContent; var htmlContent = sgMessage.HtmlContent; var message = MailHelper.CreateSingleEmailToMultipleRecipients(from, tos, subject, plainTextContent, htmlContent); var client = new SendGridClient(_sendGridOptions.Apikey); var response = await client.SendEmailAsync(message); if (response.StatusCode == System.Net.HttpStatusCode.Accepted) { return(new NotificationResult(true)); } var respBody = await response.Body.ReadAsStringAsync(); return(new NotificationResult(new List <string> { respBody })); }