static void Main(string[] args) { //Get the items out of the command line if (args.Length < 3) { Console.WriteLine("usage: SendGrid-Test <username> <password> <email address * n>"); return; } //First item is the sendgrid username string username = args[0]; //second item it the sendgrid password string pwd = args[1]; // Create the email object first, then add the properties. var myMessage = SendGrid.GetInstance(); // Add the message properties. myMessage.From = new MailAddress("*****@*****.**"); //Get all the rest of the command line arguments as email addresses List <string> recipients = new List <string>(); for (int i = 2; i < args.Length; i++) { recipients.Add(args[i]); } myMessage.AddTo(recipients); myMessage.Subject = "Testing the SendGrid Library"; //Add the HTML and Text bodies myMessage.Html = "<p>Hello World!</p>"; myMessage.Text = "Hello World plain text!"; //myMessage.InitializeFilters(); //this doesnt need to be called // Add a footer to the message. //myMessage.EnableFooter("PLAIN TEXT FOOTER", "<p><em>HTML FOOTER</em></p>"); // true indicates that links in plain text portions of the email should also be overwritten for link tracking purposes. //myMessage.EnableClickTracking(true); // Create network credentials to access your SendGrid account. var credentials = new NetworkCredential(username, pwd); // Create a Web transport for sending email. var transportWeb = Web.GetInstance(credentials); try { // Send the email. Console.WriteLine("sending email...\n\n"); transportWeb.Deliver(myMessage); } catch (Exception ex) { Console.WriteLine(string.Format("buttnuts happened: \n{0}", ex.ToString())); } }
public string SendMail(string from, string passsword, string to, string bcc, string cc, string subject, string body, string sendgridUserName = "", string sendgridPassword = "") { string sendMailBySendGrid = string.Empty; try { //var smtp = new SmtpClient(); //smtp.Port = 25; //smtp.Host = "smtp.sendgrid.net"; SendGrid myMessage = SendGridMail.SendGrid.GetInstance(); myMessage.AddTo(to); myMessage.From = new MailAddress(from); myMessage.Subject = subject; //Add the HTML and Text bodies myMessage.Html = body; //myMessage.InitializeFilters(); var credentials = new NetworkCredential(sendgridUserName, sendgridPassword); var transportWeb = SMTP.GetInstance(credentials); // Send the email. transportWeb.Deliver(myMessage); sendMailBySendGrid = "Success"; } catch (Exception ex) { Console.WriteLine(ex.Message); } return(sendMailBySendGrid); }
/// <summary> /// Add automatic unsubscribe links to the bottom of emails. /// http://docs.sendgrid.com/documentation/apps/subscription-tracking/ /// </summary> public void EnableUnsubscribeEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (var recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Html = "This is the HTML body"; message.Text = "This is the plain text body"; //set the message subject message.Subject = "Hello World Unsubscribe Test"; //create an instance of the Web transport mechanism var transportInstance = Web.GetInstance(new NetworkCredential(_username, _password)); //enable spamcheck //or optionally, you can specify 'replace' instead of the text and html in order to //place the link wherever you want. message.EnableUnsubscribe("Please click the following link to unsubscribe: <% %>", "Please click <% here %> to unsubscribe"); //send the mail transportInstance.Deliver(message); }
/// <summary> /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies. /// http://docs.sendgrid.com/documentation/apps/footer/ /// </summary> public void EnableFooterEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>Hello World</p>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; message.Text = "Hello World plain text"; //set the message subject message.Subject = "Hello World Footer Test"; //create an instance of the Web transport mechanism var transportInstance = Web.GetInstance(new NetworkCredential(_username, _password)); //Enable Footer message.EnableFooter("PLAIN TEXT FOOTER", "<p color='blue'>HTML FOOTER TEXT</p>"); //send the mail transportInstance.Deliver(message); }
public void SendMail(string fromemail, string fromdisplay, string to, string subject, string body) { try { trycount++; SendGrid myMessage = SendGrid.GetInstance(); myMessage.From = new MailAddress(fromemail, fromdisplay); myMessage.Subject = subject; myMessage.AddTo(to); myMessage.Html = body; SendByWeb(myMessage); done = true; } catch (Exception e) { var excp = e; var str = ""; } if (!done && trycount <= 3) { SendMail(fromemail, fromdisplay, to, subject, body); } }
public void TestAddBcc() { var foo = new Mock <IHeader>(); var sg = new SendGrid(foo.Object); sg.AddBcc("*****@*****.**"); Assert.AreEqual("*****@*****.**", sg.Bcc.First().ToString(), "Single Bcc Address"); sg = new SendGrid(foo.Object); var strings = new String[2]; strings[0] = "*****@*****.**"; strings[1] = "*****@*****.**"; sg.AddBcc(strings); Assert.AreEqual("*****@*****.**", sg.Bcc[0].ToString(), "Multiple addresses, check first one"); Assert.AreEqual("*****@*****.**", sg.Bcc[1].ToString(), "Multiple addresses, check second one"); sg = new SendGrid(foo.Object); var a = new Dictionary <String, String>(); a.Add("DisplayName", "Eric"); var datastruct = new Dictionary <string, IDictionary <string, string> > { { "*****@*****.**", a } }; sg.AddBcc(datastruct); Assert.AreEqual("Eric", sg.Bcc.First().DisplayName, "Single address with args"); }
private static void SendErrorNotification(int extensionId) { try { var smtpserver = RoleEnvironment.GetConfigurationSettingValue(Constants.SmtpServer); var username = RoleEnvironment.GetConfigurationSettingValue(Constants.SmtpUsername); var password = RoleEnvironment.GetConfigurationSettingValue(Constants.SmtpPassword); var from = RoleEnvironment.GetConfigurationSettingValue(Constants.EmailFrom); var emailTo = RoleEnvironment.GetConfigurationSettingValue(Constants.EmailTo); var transportInstance = SMTP.GetInstance(new NetworkCredential(username, password), smtpserver); //create a new message object var message = SendGrid.GetInstance(); //set the message recipients message.AddTo(emailTo); //set the sender message.From = new MailAddress(from); //set the message body message.Html = string.Format("<html><p>Hello Nathan,</p><p>While processing this ({0}) package, I encountered an error!</p>" + "<p>Best regards, <br />EVS</p></html>", extensionId); //set the message subject message.Subject = "EVS has encountered an error."; //send the mail transportInstance.Deliver(message); } catch (Exception exc) { Trace.TraceError("Error while sending error notification.", exc.Message); } }
/// <summary> /// This feature wraps an HTML template around your email content. /// This can be useful for sending out newsletters and/or other HTML formatted messages. /// hhttp://docs.sendgrid.com/documentation/apps/email-templates/ /// </summary> public void EnableBypassListManagementEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>Hello World</p>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; message.Text = "Hello World plain text"; //set the message subject message.Subject = "Hello World Bypass List Management Test"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //enable bypass list management message.EnableBypassListManagement(); //send the mail transportInstance.Deliver(message); }
/// <summary> /// This feature wraps an HTML template around your email content. /// This can be useful for sending out newsletters and/or other HTML formatted messages. /// http://docs.sendgrid.com/documentation/apps/email-templates/ /// </summary> public void EnableTemplateEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (var recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>Hello World</p>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; message.Text = "Hello World plain text"; //set the message subject message.Subject = "Hello World Template Test"; //create an instance of the Web transport mechanism var transportInstance = Web.GetInstance(new NetworkCredential(_username, _password)); //enable template message.EnableTemplate("<p>My Email Template <% body %> is awesome!</p>"); //send the mail transportInstance.Deliver(message); }
/// <summary> /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies. /// http://docs.sendgrid.com/documentation/apps/google-analytics/ /// </summary> public void EnableGoogleAnalytics() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (var recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>Hello World</p>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; message.Html += "Checkout my page at <a href=\"http://microsoft.com\">Microsoft</a>"; message.Text = "Hello World plain text"; //set the message subject message.Subject = "Hello World Footer Test"; //create an instance of the Web transport mechanism var transportInstance = Web.GetInstance(new NetworkCredential(_username, _password)); //enable Google Analytics message.EnableGoogleAnalytics("SendGridTest", "EMAIL", "Sendgrid", "ad-one", "My SG Campaign"); //send the mail transportInstance.Deliver(message); }
/// <summary> /// Send a simple HTML based email /// </summary> public void SimpleHTMLEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (var recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Html = "<html><p>Hello</p><p>World</p></html>"; //set the message subject message.Subject = "Hello World HTML Test"; //create an instance of the Web transport mechanism var transportInstance = Web.GetInstance(new NetworkCredential(_username, _password)); //send the mail transportInstance.Deliver(message); }
private static void sendEmailWithSendGrid(SendGrid sendGrid, EmailMessage message) { // We want this method to use the SendGrid API (https://github.com/sendgrid/sendgrid-csharp), but as of 20 June 2014 it looks like the SendGrid Web API // does not support CC recipients! // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email. var smtpClient = new System.Net.Mail.SmtpClient("smtp.sendgrid.net", 587); try { smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Credentials = new System.Net.NetworkCredential(sendGrid.UserName, sendGrid.Password); using (var m = new System.Net.Mail.MailMessage()) { message.ConfigureMailMessage(m); try { smtpClient.Send(m); } catch (System.Net.Mail.SmtpException e) { throw new EmailSendingException("Failed to send an email message using SendGrid.", e); } } } finally { smtpClient.Dispose(); } }
/// <summary> /// The Spam Checker filter, is useful when your web application allows your end users /// to create content that is then emailed through your SendGrid account. /// http://docs.sendgrid.com/documentation/apps/spam-checker-filter/ /// </summary> public void EnableSpamCheckEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (var recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>VIAGRA!!!!!! Viagra!!! CHECKOUT THIS VIAGRA!!!! MALE ENHANCEMENT!!! </p>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; //set the message subject message.Subject = "WIN A MILLION DOLLARS TODAY! WORK FROM HOME! A NIGERIAN PRINCE WANTS YOU!"; //create an instance of the Web transport mechanism var transportInstance = Web.GetInstance(new NetworkCredential(_username, _password)); //enable spamcheck message.EnableSpamCheck(); //send the mail transportInstance.Deliver(message); }
public async Task <IActionResult> PutSendGrid([FromRoute] string id, [FromBody] SendGrid sendGrid) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != sendGrid.ID) { return(BadRequest()); } _context.Entry(sendGrid).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SendGridExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(200, sendGrid)); }
/// <summary> /// Enable the Open Tracking to track when emails are opened. /// http://docs.sendgrid.com/documentation/apps/open-tracking/ /// </summary> public void EnableOpenTrackingEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (var recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Html = "<p style='color:red';>Hello World Plain Text</p>"; //set the message subject message.Subject = "Hello World Open Tracking Test"; //create an instance of the Web transport mechanism var transportInstance = Web.GetInstance(new NetworkCredential(_username, _password)); //enable gravatar message.EnableOpenTracking(); //send the mail transportInstance.Deliver(message); }
/// <summary> /// Point the urls to Sendgrid Servers so that the clicks can be logged before /// being directed to the appropriate link /// http://docs.sendgrid.com/documentation/apps/click-tracking/ /// </summary> public void EnableClickTrackingEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (var recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body var timestamp = DateTime.Now.ToString("HH:mm:ss tt"); message.Html = "<p style='color:red';>Hello World HTML </p> <a href='http://microsoft.com'>Checkout Microsoft!!</a>"; message.Html += "<p>Sent At : " + timestamp + "</p>"; message.Text = "hello world http://microsoft.com"; //set the message subject message.Subject = "Hello World Click Tracking Test"; //create an instance of the Web transport mechanism var transportInstance = Web.GetInstance(new NetworkCredential(_username, _password)); //enable clicktracking message.EnableClickTracking(); //send the mail transportInstance.Deliver(message); }
/// <summary> /// This feature tags the message with a specific tracking category, which will have aggregated stats /// viewable from your SendGrid account page. /// </summary> public void SetCategory() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Text = "Hello World"; //set the message subject message.Subject = "Testing Categories"; var category = "vipCustomers"; message.SetCategory(category); //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //enable bypass list management message.EnableBypassListManagement(); //send the mail transportInstance.Deliver(message); }
/// <summary> /// Send a simple Plain Text email /// </summary> public void SimplePlaintextEmail() { //create a new message object var message = SendGrid.GetInstance(); //set the message recipients foreach (string recipient in _to) { message.AddTo(recipient); } //set the sender message.From = new MailAddress(_from); //set the message body message.Text = "Hello World Plain Text"; //set the message subject message.Subject = "Hello World Plain Text Test"; //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(_username, _password)); //send the mail transportInstance.Deliver(message); }
private static void SendAsync(SendGrid.SendGridMessage message) { // Create credentials, specifying your user Name and password. var username = Environment.GetEnvironmentVariable("SENDGRID_USERNAME"); var password = Environment.GetEnvironmentVariable("SENDGRID_PASSWORD"); //string apikey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); var credentials = new NetworkCredential(username, password); // Create a Web transport for sending email. var transportWeb = new SendGrid.Web(credentials); //var transportWeb2 = new SendGrid.Web(apikey); // Send the email. try { transportWeb.DeliverAsync(message).Wait(); Console.WriteLine("Email sent to " + message.To.GetValue(0)); Console.WriteLine("Press any key to continue."); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Press any key to continue."); Console.ReadKey(); } }
public async Task <IActionResult> SendGrid(SendGrid model) { if (!ModelState.IsValid) { return(View(model)); } using (var client = new HttpClient()) { var apiUrl = Url.RouteUrl( "api", new { controller = "SendGrids", action = "Update", id = Statics.SendGridKey.Value }, "https" ); var result = await client .PutAsync(apiUrl, new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json")) .Result .Content .ReadAsStringAsync(); } StatusMessage = "Your SendGrid secrets has been updated"; return(RedirectToAction(nameof(SendGrid))); }
public override DeferredProcessExitCode Execute(MessageBroker messageBroker) { try { //AddresseeClient ac = new AddresseeClient(); //Addressee a = ac.GetByPartitionAndRowKey(AddresseeClient.GetPartitionKeyForEmail(To), To); //if (a.Unsubscribed) //{ // return DeferredProcessExitCode.NothingToDo; //} SendGrid myMessage = SendGrid.GetInstance(); myMessage.From = new MailAddress(FromEmail, FromDisplay); myMessage.Subject = Subject; myMessage.AddTo(To); myMessage.Html = Body; SendByWeb(myMessage); return(DeferredProcessExitCode.Success); } catch { return(DeferredProcessExitCode.Error); } }
private void AddContentAndSend(SendGrid myMessage) { try { var lunches = LunchRepository.GetLunchesForThisWeek().ToList(); myMessage.From = new MailAddress("*****@*****.**", "Mittagessen Service"); myMessage.Subject = "Herzliche Einladung zum Mittagessen"; myMessage.AddAttachment(GetImageFile(lunches[0].CookedMeal.ImageName), "dienstag.jpg"); myMessage.AddAttachment(GetImageFile(lunches[1].CookedMeal.ImageName), "mittwoch.jpg"); myMessage.AddAttachment(GetImageFile(lunches[2].CookedMeal.ImageName), "donnerstag.jpg"); myMessage.Html = string.Format(MAIL_TEMPLATE, lunches[0].CookedMeal.Name, "cid:dienstag.jpg", GetImageUrl(lunches[0].CookedMeal.ImageName), lunches[1].CookedMeal.Name, "cid:mittwoch.jpg", GetImageUrl(lunches[1].CookedMeal.ImageName), lunches[2].CookedMeal.Name, "cid:donnerstag.jpg", GetImageUrl(lunches[2].CookedMeal.ImageName)); // Create credentials, specifying your user name and password. var credentials = new NetworkCredential( ConfigurationManager.AppSettings["MailLogin"], ConfigurationManager.AppSettings["MailPassword"]); // Create an SMTP transport for sending email. var transportSMTP = SMTP.GetInstance(credentials); // Send the email. transportSMTP.Deliver(myMessage); } catch (Exception e) { Logger.FatalException("Email exception occured", e); } }
public void Send(MailMessage mail) { var body = mail.AlternateViews[0].ContentStream.ReadToEnd(); var instance = SendGrid.GenerateInstance(mail.From, mail.To.ToArray(), mail.CC.ToArray(), mail.Bcc.ToArray(), mail.Subject, body, null, TransportType.REST); instance.Mail(credential); }
private static void SendMail(string fileId, string email) { var extensionOutput = EVSAppController.Controllers.ExtensionController.GetExtension(fileId); var smtpserver = RoleEnvironment.GetConfigurationSettingValue(Constants.SmtpServer); var username = RoleEnvironment.GetConfigurationSettingValue(Constants.SmtpUsername); var password = RoleEnvironment.GetConfigurationSettingValue(Constants.SmtpPassword); var from = RoleEnvironment.GetConfigurationSettingValue(Constants.EmailFrom); var emailTo = RoleEnvironment.GetConfigurationSettingValue(Constants.EmailTo); //create a new message object var message = SendGrid.GetInstance(); //set the message recipients message.AddTo(email); message.AddBcc(emailTo); //set the sender message.From = new MailAddress(from); //set the message body message.Html = BuildEmailBody(extensionOutput); //set the message subject message.Subject = "EVS: Review your verification results"; //build attachments var filename = extensionOutput.OriginalFileName + "_EVS_Results"; var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var xlsxFormatter = new ExtensionMessageXlsxFormatter(); var xlsxFileLocation = tempPath + filename + ".xlsx"; Stream xlsxFileStream = File.Create(xlsxFileLocation); xlsxFormatter.WriteToStream(extensionOutput.ExtensionMessages, xlsxFileStream); message.AddAttachment(xlsxFileLocation); var csvFormatter = new ExtensionMessageCsvFormatter(); var csvFileLocation = tempPath + filename + ".csv"; Stream csvFileStream = File.Create(csvFileLocation); csvFormatter.WriteToStream(extensionOutput.ExtensionMessages, csvFileStream); message.AddAttachment(csvFileLocation); var xmlFormatter = new ExtensionMessageXmlFormatter(); var xmlFileLocation = tempPath + filename + ".xml"; Stream xmlFileStream = File.Create(xmlFileLocation); xmlFormatter.WriteToStream(extensionOutput.ExtensionMessages, xmlFileStream); message.AddAttachment(xmlFileLocation); //create an instance of the SMTP transport mechanism var transportInstance = SMTP.GetInstance(new NetworkCredential(username, password), smtpserver); //send the mail transportInstance.Deliver(message); }
public static void Main(string[] args) { CloudRail.AppKey = "[Your CloudRail Key]"; int port = 8082; MailJet mailJet = new MailJet(null, "[Mailjet API Key]", "[Mailjet API Private Key]"); SendGrid sendGrid = new SendGrid(null, "[SendGrid API Key]"); GMail gmail = new GMail(new LocalReceiver(port), "[Client ID]", "[Client Secret]", "http://*****:*****@"../../cloudrail_image.jpg"); FileStream fs = new FileStream(strPhoto, FileMode.Open, FileAccess.Read); Attachment attachment = new Attachment(fs, "image/jpg", "cloudrail_image.jpg"); List <Attachment> attachments = new List <Attachment> { attachment }; List <IEmail> services = new List <IEmail> { mailJet, sendGrid, gmail }; foreach (IEmail service in services) { try { service.SendEmail(sender, "CloudRailTest", recipients, "This is cool from Cloudrail", "Hi there,\\n\\nGo ahead and try it yourself!!", "<strong>Hi there,<br/><br/>Go ahead and try it yourself!</strong><br/>Sent with " + service, null, //cc Addresses null, //bcc Addresses attachments); } catch (Exception e) { Console.WriteLine(e); } } }
public ActionResult SendMailAboutLunchesTest() { var myMessage = SendGrid.GetInstance(); myMessage.AddTo("*****@*****.**"); AddContentAndSend(myMessage); return(RedirectToAction("Index")); }
public void TestSGHeader() { var foo = new Mock <IHeader>(); var sg = new SendGrid(foo.Object); sg.Subject = "New Test Subject"; Assert.AreEqual("New Test Subject", sg.Subject, "Subject set ok"); sg.Subject = null; Assert.AreEqual("New Test Subject", sg.Subject, "null subject does not overide previous subject"); }
public void TestSetCategory() { var cat = "foo"; var mock = new Mock <IHeader>(); var sg = new SendGrid(mock.Object); sg.SetCategory(cat); mock.Verify(foo => foo.SetCategory(cat)); }
public void DisableFooter() { var header = new Header(); var sendgrid = new SendGrid(header); sendgrid.DisableFooter(); var json = header.JsonString(); Assert.AreEqual("{\"filters\" : {\"footer\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json); }
public void DisableBypassListManagement() { var header = new Header(); var sendgrid = new SendGrid(header); sendgrid.DisableBypassListManagement(); var json = header.JsonString(); Assert.AreEqual("{\"filters\" : {\"bypass_list_management\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json); }
public void TestDisableOpenTracking() { var header = new Header(); var sendgrid = new SendGrid(header); sendgrid.DisableOpenTracking(); var json = header.JsonString(); Assert.AreEqual("{\"filters\" : {\"opentrack\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json); }
private static void SendAsync(SendGrid.SendGridMessage message) { string apikey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); // Create a Web transport for sending email. var transportWeb = new SendGrid.Web(apikey); // Send the email. try { transportWeb.DeliverAsync(message).Wait(); Console.WriteLine("Email sent to " + message.To.GetValue(0)); Console.WriteLine("\n\nPress any key to continue."); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("\n\nPress any key to continue."); Console.ReadKey(); } }
private void AddCustomHeaders(SG.SendGridMessage message, IDictionary<string, string> customMessageHeaders) { message.AddUniqueArgs(customMessageHeaders); }
private void AddGlobalProperties(SG.SendGridMessage message, IMessageJobRequest messageJob) { message.From = new MailAddress(messageJob.SenderEmailAddress, messageJob.SenderName); message.Subject = messageJob.MessageTemplate.Subject; message.Text = messageJob.MessageTemplate.PlainTextVersion; message.Html = messageJob.MessageTemplate.BodyHtml; }
private void AddSubscribersInfo(SG.SendGridMessage message, IMessageJobRequest messageJob, IEnumerable<ISubscriberResponse> subscribers) { IEnumerable<string> replacementTags = this.GetReplacementTags(messageJob); // Creating Dictionary<string, List<string>> that will contain the replacement tag like {|Subscriber.Name|} and custom headers // like {|Subscriber.ResolveKey|} as keys. The value will be the list of per subscriber values in the same order as the list of // emails to send to. var substitutions = this.InitializeSubstitutions(replacementTags, messageJob.CustomMessageHeaders); // Filling in the substitutions data structure with per subscriber values. foreach (var subscriber in subscribers) { // TODO: validate subscribers email addresses // TODO: add email + recipient name as TO address. message.AddTo(subscriber.Email); var subscriberPropertiesAsDict = subscriber.ToDictionary(); this.CalculateSubstitutions(substitutions, subscriberPropertiesAsDict); } // Adding the constructed substitutions in the SendGrid message. foreach (var substitutionPair in substitutions) { message.AddSubstitution(substitutionPair.Key, substitutionPair.Value); } }
/// <summary> /// Sends the specified SendGrid <paramref name="message"/>. /// </summary> /// <param name="message">The SendGrid message to send.</param> /// <returns> /// The asynchronous task that can be awaited. The Task.Result is the Sitefinity SendResult /// that indicates the weather the sending was successful or not.</returns> public async Task<SendResult> SendAsync(SG.SendGridMessage message) { // Create credentials, specifying your user name and password. var credentials = new NetworkCredential(this.Username, this.Password); // Create a Web transport for sending email. var transportWeb = new SG.Web(credentials); try { // No need for asynchronous execution since the sender is invoked in a separate thread // dedicated to sending the messages. await transportWeb.DeliverAsync(message); return SendResult.ReturnSuccess(); } catch (HttpException ex) { // HttpExceptions are expected so we just return that the sending failed. return SendResult.ReturnFailed(ex); } catch (Exception ex) { // TODO: run those exceptions through a Notifications exception handling policy before returning the result. return SendResult.ReturnFailed(ex); } }
private static void sendEmailWithSendGrid( SendGrid sendGrid, EmailMessage message ) { // We want this method to use the SendGrid API (https://github.com/sendgrid/sendgrid-csharp), but as of 20 June 2014 it looks like the SendGrid Web API // does not support CC recipients! // We used to cache the SmtpClient object. It turned out not to be thread safe, so now we create a new one for every email. var smtpClient = new System.Net.Mail.SmtpClient( "smtp.sendgrid.net", 587 ); try { smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; smtpClient.Credentials = new System.Net.NetworkCredential( sendGrid.UserName, sendGrid.Password ); using( var m = new System.Net.Mail.MailMessage() ) { message.ConfigureMailMessage( m ); try { smtpClient.Send( m ); } catch( System.Net.Mail.SmtpException e ) { throw new EmailSendingException( "Failed to send an email message using SendGrid.", e ); } } } finally { smtpClient.Dispose(); } }
public void SendAsync(SendGrid.SendGridMessage message) { var config = SmtpConfiguration.Config; var transportWeb = new SendGrid.Web(new NetworkCredential(config.Username, config.Password)); transportWeb.DeliverAsync(message); }