public EmailResponse Send(EmailContract contract) { var emailMessage = new SendGridMessage() { From = new EmailAddress(contract.FromEmailAddress, contract.Alias), Subject = contract.Subject, HtmlContent = contract.Body }; List <EmailAddress> toEmails = new List <EmailAddress>(); contract.ToEmailAddress.ForEach(s => toEmails.Add(new EmailAddress(s))); emailMessage.AddTos(toEmails); if (!string.IsNullOrWhiteSpace(contract.BccEmailAddress)) { emailMessage.AddBcc(new EmailAddress(contract.BccEmailAddress)); } if (!string.IsNullOrWhiteSpace(contract.CcEmailAddress)) { emailMessage.AddBcc(new EmailAddress(contract.CcEmailAddress)); } return(ProcessResponse(_client.SendEmailAsync(emailMessage).Result)); }
public async Task Send(EmailContract contract) { var emailMessage = new SendGridMessage(); emailMessage.From = new EmailAddress(contract.FromEmailAddress, contract.Alias); emailMessage.Subject = contract.Subject; emailMessage.AddTo(new EmailAddress(contract.ToEmailAddress)); if (!string.IsNullOrWhiteSpace(contract.HtmlContent)) { emailMessage.HtmlContent = contract.HtmlContent; } if (!string.IsNullOrWhiteSpace(contract.PlainTextContent)) { emailMessage.PlainTextContent = contract.PlainTextContent; } if (!string.IsNullOrWhiteSpace(contract.BccEmailAddress)) { emailMessage.AddBcc(new EmailAddress(contract.BccEmailAddress)); } if (!string.IsNullOrWhiteSpace(contract.CcEmailAddress)) { emailMessage.AddBcc(new EmailAddress(contract.CcEmailAddress)); } var response = await _client.SendEmailAsync(emailMessage); }
public async Task <string> Send(string subject, string to, string body, string cc = null, string bcc = null) { var mailClient = new SendGridClient(apiKey); var message = new SendGridMessage() { From = new EmailAddress(fromEmail, fromEmailDisplayName), Subject = subject, HtmlContent = body }; message.AddTo(new EmailAddress(to)); if (!string.IsNullOrWhiteSpace(cc)) { message.AddBcc(new EmailAddress(cc)); } if (!string.IsNullOrWhiteSpace(bcc)) { message.AddBcc(new EmailAddress(bcc)); } var response = await mailClient.SendEmailAsync(message); return(response.StatusCode.ToString()); }
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); }
/// <summary> /// Sends out an email from the application. Returns true if successful. /// </summary> public static bool SendGridEmail(string from, List <string> to, List <string> cc, List <string> bcc, string subj, string body, string smtpUser, string smtpUserPwd) { try { //******************** CONSTRUCT EMAIL ******************************************** // Create the email object first, then add the properties. var myMessage = new SendGridMessage(); // Add message properties. myMessage.From = new MailAddress(from); myMessage.AddTo(to); if (cc != null) { foreach (string cc1 in cc) { myMessage.AddCc(cc1); } } if (bcc != null) { foreach (string bcc1 in bcc) { myMessage.AddBcc(bcc1); } } myMessage.Subject = subj; //myMessage.Html = "<p>" + body + "</p>"; myMessage.Text = body; //********************************************************************************* //********************* SEND EMAIL ************************************************ var credentials = new NetworkCredential(smtpUser, smtpUserPwd); // Create an Web transport for sending email. var transportWeb = new Web(credentials); // Send the email. transportWeb.Deliver(myMessage); return(true); } catch (Exception ex) { if (ex.InnerException != null) { db_Ref.InsertT_OE_SYS_LOG("EMAIL ERR", ex.InnerException.ToString()); } else if (ex.Message != null) { db_Ref.InsertT_OE_SYS_LOG("EMAIL ERR", ex.Message.ToString()); } else { db_Ref.InsertT_OE_SYS_LOG("EMAIL ERR", "Unknown error"); } return(false); } }
public static SendGridMessage ToSendGridMessage(this IMessage message) { var sgMessage = new SendGridMessage { From = new EmailAddress(message.From.PrettyEmail(message.FromName)), Subject = message.Subject, }; foreach (var address in message.ToAddress) { sgMessage.AddTo(address); } foreach (var address in message.Cc) { sgMessage.AddCc(address); } foreach (var address in message.Bcc) { sgMessage.AddBcc(address); } if (!string.IsNullOrEmpty(message.Html)) { sgMessage.HtmlContent = message.Html; } if (!string.IsNullOrEmpty(message.Text)) { sgMessage.PlainTextContent = message.Text; } return(sgMessage); }
public static void Send(string sender, string[] tolist, string[] ccList, string[] bccList, string subject, string body, bool iSJob = false) { try { var message = new SendGridMessage { From = new MailAddress(Utils.GetSetting(MAIL_SENDER, ""), Utils.GetSetting(MAIL_USER, ""), Encoding.UTF8) }; message.AddTo(tolist); message.AddCc(ccList); message.AddBcc(bccList); message.Subject = subject; message.Html = body; //var credentials = new NetworkCredential("ssp_system_admin", "Asdcvnmmvb"); var credentials = new NetworkCredential(Utils.GetSetting(MAIL_USER, "ssp_system_admin"), Utils.GetSetting(MAIL_PASSWORD, "Asdcvnmmvb")); // Create a Web transport for sending email. var transportWeb = new SendGrid.Web(credentials); if (iSJob) { transportWeb.DeliverAsync(message).Wait(); } else { transportWeb.DeliverAsync(message); } } catch (Exception ex) { } }
public virtual async Task <IEmailOutput> SendAsync(IEmailInput emailInput) { SendGridInformation sendGridInformation = CreateInformation(); SendGridClient client = new SendGridClient(sendGridInformation.ApiKey); SendGridMessage msg = new SendGridMessage() { From = new EmailAddress(emailInput.FromEmail, name: emailInput.FromName), Subject = emailInput.Subject, HtmlContent = emailInput.Body }; msg.AddTo(new EmailAddress(emailInput.To)); if (!string.IsNullOrEmpty(emailInput.Bcc)) { msg.AddBcc(new EmailAddress(emailInput.Bcc)); } Response result = await client.SendEmailAsync(msg); SendGridOutput sendGridOutput = new SendGridOutput { IsSuccess = result.StatusCode == System.Net.HttpStatusCode.Accepted }; return(sendGridOutput); }
public async Task <Response> Send(EmailMessageInfo messageInfo) { // Prepare the SendGrid email message var sendgridMessage = new SendGridMessage { From = new EmailAddress(messageInfo.FromEmailAddress), Subject = messageInfo.EmailSubject, HtmlContent = messageInfo.EmailBody }; // Add the "To" email address to the message sendgridMessage.AddTo(new EmailAddress(messageInfo.ToEmailAddress)); // Check if any Cc email address was specified if (!string.IsNullOrWhiteSpace(messageInfo.CcEmailAddress)) { // Add the email address for Cc to the message sendgridMessage.AddCc(new EmailAddress(messageInfo.CcEmailAddress)); } // Check if any Bcc email address was specified if (!string.IsNullOrWhiteSpace(messageInfo.BccEmailAddress)) { // Add the email address for Bcc to the message sendgridMessage.AddBcc(new EmailAddress(messageInfo.BccEmailAddress)); } // Send the message to SendGrid, and save the API response var response = await _client.SendEmailAsync(sendgridMessage); // Return the SendGrid response return(response); }
public SentStatus Send(string to, string subject, string message, string[] cc, string[] bcc, byte[] attachment, string attachmentname, string replyto) { bool status; string responseMesage = string.Empty; try { SendGridMessage msg = new SendGridMessage { From = new EmailAddress(Config.EmailAddress, Config.Name), Subject = subject, PlainTextContent = message, ReplyTo = new EmailAddress(replyto) }; msg.AddTo(new EmailAddress(to, "User")); foreach (string i in cc) { msg.AddBcc(new EmailAddress(i)); } foreach (string i in bcc) { msg.AddCc(new EmailAddress(i)); } if (attachment != null) { var file = Convert.ToBase64String(attachment); msg.AddAttachment(attachmentname, file); } Client.SendEmailAsync(msg); responseMesage = "SendGrid Send success"; status = true; } catch (Exception e) { responseMesage = "SendGrid Send Exception" + e.Message + e.StackTrace; status = false; } var plainTextBytes = Encoding.UTF8.GetBytes(message); string message64 = Convert.ToBase64String(plainTextBytes); SentStatus SentStatus = new SentStatus { Status = status.ToString(), To = to, From = Config.EmailAddress, Body = message64, ConId = Config.Id, Result = responseMesage, Recepients = new EmailRecepients { To = to, Cc = (cc == null) ? "" : string.Join(",", cc), Bcc = (bcc == null) ? "" : string.Join(",", bcc), Replyto = (replyto == null) ? "" : replyto, }, Subject = subject, AttachmentName = attachmentname }; return(SentStatus); }
public void Send(Context context) { Task.Run(() => { try { var sendGridMessage = new SendGridMessage(); sendGridMessage.From = new EmailAddress(Addresses.From(From).Address, Addresses.From(From).DisplayName); Addresses.GetEnumerable( context: context, addresses: To) .ForEach(to => sendGridMessage.AddTo(to)); Addresses.GetEnumerable( context: context, addresses: Cc) .ForEach(cc => sendGridMessage.AddCc(cc)); Addresses.GetEnumerable( context: context, addresses: Bcc) .ForEach(bcc => sendGridMessage.AddBcc(bcc)); sendGridMessage.Subject = Subject; sendGridMessage.PlainTextContent = Body; var client = new SendGridClient(Parameters.Mail.ApiKey); var response = client.SendEmailAsync(sendGridMessage); response.Wait(); } catch (Exception e) { new SysLogModel(Context, e); } }); }
public async Task Run([TimerTrigger("0 */8 * * *" #if DEBUG , RunOnStartup = true #endif )] TimerInfo myTimer, ExecutionContext context, ILogger log) { telemetryClient.TrackEvent($"{FunctionName} Azure func start"); log.LogInformation($"{FunctionName} Azure func starting at {DateTime.Now} on {Environment.MachineName}"); var mailSender = GetSenderEmail(); var admins = await GetAdminsAsync(); var allUsers = await GetAllUsersAsync(); var mailBody = new StatsToAdminMailBuilder(FunctionName, startTime /*, admins, allUsers*/).GetMailBody(); var msg = new SendGridMessage() { From = mailSender, Subject = $"MemCheck stats", HtmlContent = mailBody }; admins.ForEach(e => msg.AddTo(e.Email, e.Name)); msg.AddBcc(mailSender); msg.SetClickTracking(false, false); var response = await GetSendGridClient().SendEmailAsync(msg); log.LogInformation($"Mail sent, status code {response.StatusCode}"); log.LogInformation($"Response body: {await response.Body.ReadAsStringAsync()}"); log.LogInformation($"Function '{FunctionName}' ending, {DateTime.Now}"); }
public async Task <HttpStatusCode> SendAdminResultsAsync(ImmutableArray <string> MailsTo, string TeamName, ImmutableArray <Matchs> matchs) { GetKey(); var client = new SendGridClient(ApiKey); StringBuilder b = new StringBuilder(); b.AppendLine("Estos son los resultados de los partidos que pronosticastes!"); b.AppendLine(); b.AppendLine("----------"); b.AppendLine(); foreach (var m in matchs) { b.AppendLine(m.Team1Name + " " + m.Team1Forecast + "-" + m.Team2Forecast + " " + m.Team2Name); } var msg = new SendGridMessage() { From = new EmailAddress(FromAddres, FromName), Subject = "Tus nuevos resultados", PlainTextContent = b.ToString() }; msg.AddTo(new EmailAddress(FromAddres)); foreach (string s in MailsTo) { msg.AddBcc(new EmailAddress(s)); } var response = await client.SendEmailAsync(msg); return(response.StatusCode); }
//public EmailHelper(string toEmailAddress, string subject, string message, string attachmentPath) // : this(toEmailAddress, subject, message) //{ // this.attachmentPath = attachmentPath; //} #endregion #region Functions public void SendMessage() { SendGridMessage myMessage = new SendGridMessage(); myMessage.AddTo(toEmailAddress); myMessage.From = new MailAddress(fromEmailAddress, (string.IsNullOrEmpty(fromUserName) ? fromEmailAddress : fromUserName)); if (!string.IsNullOrEmpty(bccEmailAddress)) { myMessage.AddBcc(bccEmailAddress); } myMessage.Subject = subject; myMessage.Html = message; if (!string.IsNullOrEmpty(attachmentPath)) { myMessage.AddAttachment(attachmentPath); } var credentials = new NetworkCredential(sendGridUserName, sendGridPassword); // Create an Web transport for sending email. var transportWeb = new Web(credentials); // Send the email, which returns an awaitable task. var oRet = transportWeb.DeliverAsync(myMessage); }
/// <summary> /// Sends out an email using SendGrid. /// Note: Updated to work with SendGrid version 9.8 /// </summary> /// <returns>true if successful</returns> public async Task <bool> SendEmailUsingSendGrid(string from, string to, List <string> cc, List <string> bcc, string subj, string body, string apiKey) { try { var client = new SendGridClient(apiKey); //******************** CONSTRUCT EMAIL ******************************************** var msg = new SendGridMessage() { From = new EmailAddress(from), Subject = subj }; msg.AddContent(MimeType.Html, body); msg.AddTo(new EmailAddress(to)); foreach (string cc1 in cc ?? Enumerable.Empty <string>()) { msg.AddCc(cc1); } foreach (string bcc1 in bcc ?? Enumerable.Empty <string>()) { msg.AddBcc(bcc1); } // Disable click tracking. See https://sendgrid.com/docs/User_Guide/Settings/tracking.html msg.TrackingSettings = new TrackingSettings { ClickTracking = new ClickTracking { Enable = false } }; //******************** SEND EMAIL **************************************************** var response = await client.SendEmailAsync(msg).ConfigureAwait(false); //******************** RETURN RESPONSE *********************************************** if (response.StatusCode == HttpStatusCode.Accepted) { return(true); } else { return(false); } //************************************************************************************ } catch (Exception ex) { if (ex.InnerException != null) { _log.LogEFException(ex); } return(false); } }
private static SendGridMessage ConvertToSendGridMessage(MailMessage message) { var sgMessage = new SendGridMessage { From = new EmailAddress(message.From.Address, message.From.DisplayName) }; foreach (var addressTo in message.To) { sgMessage.AddTo(new EmailAddress(addressTo.Address)); } foreach (var addressCc in message.CC) { sgMessage.AddCc(new EmailAddress(addressCc.Address)); } foreach (var addressBcc in message.Bcc) { sgMessage.AddBcc(new EmailAddress(addressBcc.Address)); } sgMessage.Subject = message.Subject; if (message.AlternateViews.Count > 0) { foreach (var view in message.AlternateViews) { if (view.ContentStream.CanSeek) { view.ContentStream.Position = 0; } var reader = new StreamReader(view.ContentStream); switch (view.ContentType.MediaType) { case MediaTypeNames.Text.Html: sgMessage.HtmlContent = reader.ReadToEnd(); break; case MediaTypeNames.Text.Plain: sgMessage.PlainTextContent = reader.ReadToEnd(); break; } } } foreach (var attachment in message.Attachments) { sgMessage.AddAttachment(attachment.Name, ConvertToBase64(attachment.ContentStream), attachment.ContentType.MediaType); } return(sgMessage); }
public async Task <string> Send(EmailArgs args) { var apiKey = String.IsNullOrEmpty(args.ApiKey) ? ConfigurationManager.AppSettings["SendGrindApiKey"] : args.ApiKey; var fromEmail = String.IsNullOrEmpty(args.FromEmail) ? ConfigurationManager.AppSettings["FromEmail"] : args.FromEmail; var fromEmailDisplayName = String.IsNullOrEmpty(args.FromEmailDisplayName) ? ConfigurationManager.AppSettings["FromEmailDisplayName"] : args.FromEmailDisplayName; var mailClient = new SendGridClient(apiKey); var message = new SendGridMessage() { From = new EmailAddress(fromEmail, fromEmailDisplayName), Subject = args.Subject, PlainTextContent = args.Body, HtmlContent = args.Body }; if (args.To == null) { throw new UserFriendlyException("To Email Address is needed"); } string[] toArray = args.To.Split(','); List <EmailAddress> tos = toArray .ToList() .Select(s => new EmailAddress(s)) .ToList(); message.AddTos(tos); if (!string.IsNullOrWhiteSpace(args.CC)) { message.AddBcc(new EmailAddress(args.CC)); } if (!string.IsNullOrWhiteSpace(args.BCC)) { message.AddBcc(new EmailAddress(args.BCC)); } var response = await mailClient.SendEmailAsync(message); return(response.StatusCode.ToString()); }
public virtual async Task SendNotificationAsync(NotificationMessage message) { if (!CanSend(message)) { throw new ArgumentNullException(nameof(message)); } var emailNotificationMessage = message as EmailNotificationMessage; var fromAddress = new EmailAddress(emailNotificationMessage.From); var toAddress = new EmailAddress(emailNotificationMessage.To); try { var client = new SendGridClient(_emailSendingOptions.ApiKey); var mailMsg = new SendGridMessage { From = fromAddress, Subject = emailNotificationMessage.Subject, HtmlContent = emailNotificationMessage.Body, }; mailMsg.AddTo(toAddress); if (!emailNotificationMessage.CC.IsNullOrEmpty()) { foreach (var ccEmail in emailNotificationMessage.CC) { mailMsg.AddCc(ccEmail); } } if (!emailNotificationMessage.BCC.IsNullOrEmpty()) { foreach (var bccEmail in emailNotificationMessage.BCC) { mailMsg.AddBcc(bccEmail); } } var response = await client.SendEmailAsync(mailMsg); if (response.StatusCode != HttpStatusCode.Accepted) { var errorBody = await response.Body.ReadAsStringAsync(); throw new SentNotificationException(errorBody); } } catch (SmtpException ex) { throw new SentNotificationException(ex); } }
private SendGridMessage CreateSendGridMessage(TransportMessage message) { var sendGridMessage = new SendGridMessage(); sendGridMessage.From = new EmailAddress(message.From); sendGridMessage.AddTo(new EmailAddress(message.To)); sendGridMessage.Subject = message.Subject; sendGridMessage.AddCc(message.CC); sendGridMessage.AddBcc(message.Bcc); sendGridMessage.PlainTextContent = message.Body; return(sendGridMessage); }
public EmailResponse Send(EmailContact email) { var sendGridMessage = new SendGridMessage { From = new EmailAddress(email.FromEmailAddress, email.SenderName), Subject = email.Subject, HtmlContent = email.HtmlBody }; sendGridMessage.AddTo(new EmailAddress(email.ToEmailAddress)); if (!string.IsNullOrWhiteSpace(email.BccEmailAddress)) { sendGridMessage.AddBcc(new EmailAddress(email.BccEmailAddress)); } if (!string.IsNullOrWhiteSpace(email.CcEmailAddress)) { sendGridMessage.AddBcc(new EmailAddress(email.CcEmailAddress)); } return(ProcessResponse(_client.SendEmailAsync(sendGridMessage).Result)); }
public async Task SendMailAsync(string fromName, string fromEmail, string toName, string toEmail, string bcc, string subject, string templateId, object model) { var message = new SendGridMessage(); message.SetFrom(fromEmail, fromName); message.AddTo(toEmail, toName); message.AddBcc(bcc); message.SetTemplateId(templateId); message.SetTemplateData(model); var response = await _client.SendEmailAsync(message); _log.LogInformation($"Email sent. Statuscode {response.StatusCode}"); }
public async Task SendMail(string providermail) { Byte[] bytes = File.ReadAllBytes(pathToFiles); String file = Convert.ToBase64String(bytes); var apiKey = "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"; var client = new SendGridClient(apiKey); var msg = new SendGridMessage() { From = new EmailAddress("*****@*****.**", "Lagoon Hospitals"), Subject = "Hygeia Check-in Data For The Last Three Hours", HtmlContent = "<strong><span>Dear PCS</span><br/><span><p>Please find attached file for your perusal.</p> <p>It contain the Check-In data for hygeia patients as being reported on hydirect for the last three hours</p><p>Kind regards</p></span></strong>" }; //msg.AddTo(new EmailAddress(providermail, "")); msg.AddTo(new EmailAddress("*****@*****.**", "")); msg.AddBcc(new EmailAddress("*****@*****.**", "")); //msg.AddBcc(new EmailAddress("*****@*****.**", "")); //msg.AddBcc(new EmailAddress("*****@*****.**", "")); msg.AddBcc(new EmailAddress("*****@*****.**", "")); msg.AddBcc(new EmailAddress("*****@*****.**", "")); msg.AddBcc(new EmailAddress("*****@*****.**", "")); msg.AddAttachment(pathToFiles, file, "text/csv", "attachment", "banner"); var response = await client.SendEmailAsync(msg); }
public async Task SendAsync(IdentityMessage message) { var client = new SendGridClient(EmailConstants.ApiKey); var from = new EmailAddress(EmailConstants.AdminNoReplyAddress, EmailConstants.DevPodcasts); var bcc = new EmailAddress(EmailConstants.AdminEmailAddress); var msg = new SendGridMessage { From = from, Subject = message.Subject, HtmlContent = message.Body }; msg.AddTo(new EmailAddress(message.Destination)); msg.AddBcc(bcc); var response = await client.SendEmailAsync(msg); }
public async Task <SendGridFunctionResult> ExecuteEmail(IEmail Email) { try { var msg = new SendGridMessage(); msg.SetFrom(new EmailAddress(Email.FromEmail.Email, Email.FromEmail.FullName)); foreach (IEmailAddress emailAddress in Email.ToEmail) { msg.AddTo(emailAddress.Email, emailAddress.FullName); } foreach (IEmailAddress emailAddress in Email.CCEmail) { msg.AddCc(emailAddress.Email, emailAddress.FullName); } foreach (IEmailAddress emailAddress in Email.BCCEmail) { msg.AddBcc(emailAddress.Email, emailAddress.FullName); } foreach (IEmailAttachment emailAttachment in Email.Attachments) { msg.AddAttachment(emailAttachment.FileName, emailAttachment.Content); } msg.SetSubject(Email.Subject); msg.AddContent(MimeType.Html, string.Format("{0}{1}{2}", Email.Body, Environment.NewLine, Email.Footer)); msg.AddCategory(this.Database); msg.AddCategory(this.Application.ToString()); msg.SetClickTracking(true, true); msg.SetOpenTracking(true); var response = await SendGridClient.SendEmailAsync(msg); Dictionary <string, string> result = response.DeserializeResponseHeaders(response.Headers); return(new SendGridFunctionResult(response.StatusCode.ToString(), response.Body.ToString(), result["X-Message-Id"].ToString())); } catch (Exception ex) { throw ex; } }
public async Task SendEmailAsync(string email, string subject, string message) { var client = new SendGridClient(settings.SendGridKey); var senderEmail = new EmailAddress(settings.SendGridSender, settings.SendGridUser); var msg = new SendGridMessage() { From = senderEmail, Subject = subject, PlainTextContent = message, HtmlContent = message, }; msg.AddTo(new EmailAddress(email)); msg.AddBcc(new EmailAddress(settings.SendGridSender)); msg.SetClickTracking(false, false); await client.SendEmailAsync(msg); }
private SendGridMessage BuildRecordOfSalesEmail(RecordOfSales recordOfSales) { var email = new SendGridMessage(); var configuration = this.sendGridConfigurationOption.Value; email.From = new EmailAddress(configuration.ServiceEmail); email.AddTo(new EmailAddress(recordOfSales.EmailAddress)); email.TemplateId = configuration.RecordOfSalesTemplateId; email.SetTemplateData(recordOfSales); if (!string.Equals(recordOfSales.EmailAddress, configuration.RealContactEmail, StringComparison.OrdinalIgnoreCase)) { email.ReplyTo = new EmailAddress(configuration.RealContactEmail); email.AddBcc(configuration.RealContactEmail); } return(email); }
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 async Task SendNotificationAsync(NotificationMessage message) { try { var emailNotificationMessage = message as EmailNotificationMessage; if (emailNotificationMessage == null) { throw new ArgumentNullException(nameof(emailNotificationMessage)); } var fromAddress = new EmailAddress(emailNotificationMessage.From); var client = new SendGridClient(_emailSendingOptions.ApiKey); var mailMsg = new SendGridMessage { From = fromAddress, Subject = emailNotificationMessage.Subject, HtmlContent = emailNotificationMessage.Body }; mailMsg.SetReplyTo(fromAddress); if (!emailNotificationMessage.CC.IsNullOrEmpty()) { foreach (var ccEmail in emailNotificationMessage.CC) { mailMsg.AddCc(ccEmail); } } if (!emailNotificationMessage.BCC.IsNullOrEmpty()) { foreach (var bccEmail in emailNotificationMessage.BCC) { mailMsg.AddBcc(bccEmail); } } await client.SendEmailAsync(mailMsg); } catch (SmtpException ex) { throw new SentNotificationException(ex.Message, ex); } }
public override void SendEmail(EmailMessage message) { if (setting.IsEmailDisabled) { return; } try { var sendGridClient = new SendGridClient(emailAccount.ApiKey); var sendGridMessage = new SendGridMessage(); var fromAddr = message.From.FirstOrDefault(); if (fromAddr != null) { sendGridMessage.From = new SendGrid.Helpers.Mail.EmailAddress(fromAddr.Address, fromAddr.Name); } sendGridMessage.Subject = message.Subject; sendGridMessage.PlainTextContent = message.PlainTextBody; sendGridMessage.HtmlContent = message.Body; foreach (var toAddr in message.To) { sendGridMessage.AddTo(new SendGrid.Helpers.Mail.EmailAddress(toAddr.Address, toAddr.Name)); } foreach (var ccAddr in message.CC) { sendGridMessage.AddCc(new SendGrid.Helpers.Mail.EmailAddress(ccAddr.Address, ccAddr.Name)); } foreach (var bccAddr in message.Bcc) { sendGridMessage.AddBcc(new SendGrid.Helpers.Mail.EmailAddress(bccAddr.Address, bccAddr.Name)); } //disable click tracking; see https://sendgrid.com/docs/User_Guide/Settings/tracking.html sendGridMessage.SetClickTracking(false, false); sendGridClient.SendEmailAsync(sendGridMessage); } catch (Exception ex) { throw new CannotSendEmailException("Cannot Send Email." + ex.Message, ex); } }
public static async Task <Response> SendMailTask(string emailContentMessage, string emailHTMLContent) { // maybe need APPSETTING_SENDGRID_APIKEY //var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); var apiKey = WebConfigurationManager.AppSettings["SENDGRID_APIKEY"]; var client = new SendGridClient(apiKey); string emailToAddresses = WebConfigurationManager.AppSettings["emailToAddresses"]; string emailFromAddress = WebConfigurationManager.AppSettings["emailFromAddress"]; string emailBCCAddress = WebConfigurationManager.AppSettings["emailBCCAddress"]; string emailSubject = WebConfigurationManager.AppSettings["emailSubject"]; string emailBCC = WebConfigurationManager.AppSettings["emailBCCAddress"]; int isTest = Convert.ToInt32(WebConfigurationManager.AppSettings["isTest"]); var msg = new SendGridMessage() { From = new EmailAddress(emailFromAddress, "Shane's Built In Vacuums Web Form"), Subject = emailSubject, PlainTextContent = emailContentMessage, HtmlContent = emailHTMLContent }; if (isTest > 0) { } else { var splitAddresses = emailToAddresses.Split(';'); foreach (string address in splitAddresses) { msg.AddTo(new EmailAddress(address)); } } msg.AddBcc(new EmailAddress(emailBCC)); var response = await client.SendEmailAsync(msg).ConfigureAwait(false); Console.WriteLine(response.StatusCode); Console.WriteLine(response.Body.ReadAsStringAsync().Result); // The message will be here Console.WriteLine(response.Headers.ToString()); return(response); }