public static bool SendCurrentIncidentInvoiceEmail(Incident incident, ApiServices Services) { IncidentInfo invoiceIncident = new IncidentInfo(incident); if (invoiceIncident.PaymentAmount < invoiceIncident.ServiceFee) { SendGridMessage invoiceMessage = new SendGridMessage(); invoiceMessage.From = SendGridHelper.GetAppFrom(); invoiceMessage.AddTo(invoiceIncident.IncidentUserInfo.Email); invoiceMessage.Html = " "; invoiceMessage.Text = " "; invoiceMessage.Subject = "StrandD Invoice - Payment for Service Due"; invoiceMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_InvoiceTemplateID"]); invoiceMessage.AddSubstitution("%invoicestub%", new List<string> { invoiceIncident.IncidentGUID.Substring(0, 5).ToUpper() }); invoiceMessage.AddSubstitution("%incidentguid%", new List<string> { invoiceIncident.IncidentGUID }); invoiceMessage.AddSubstitution("%name%", new List<string> { invoiceIncident.IncidentUserInfo.Name }); invoiceMessage.AddSubstitution("%phone%", new List<string> { invoiceIncident.IncidentUserInfo.Phone }); invoiceMessage.AddSubstitution("%email%", new List<string> { invoiceIncident.IncidentUserInfo.Email }); invoiceMessage.AddSubstitution("%jobdescription%", new List<string> { invoiceIncident.JobCode }); invoiceMessage.AddSubstitution("%servicefee%", new List<string> { (invoiceIncident.ServiceFee - invoiceIncident.PaymentAmount).ToString() }); invoiceMessage.AddSubstitution("%datesubmitted%", new List<string> { DateTime.Now.ToShortDateString() }); invoiceMessage.AddSubstitution("%datedue%", new List<string> { (DateTime.Now.AddDays(30)).ToShortTimeString() }); invoiceMessage.AddSubstitution("%servicepaymentlink%", new List<string> { (WebConfigurationManager.AppSettings["RZ_ServiceBaseURL"].ToString() + "/view/customer/incidentpayment/" + invoiceIncident.IncidentGUID) }); // Create an Web transport for sending email. var transportWeb = new Web(SendGridHelper.GetNetCreds()); // Send the email. try { transportWeb.Deliver(invoiceMessage); Services.Log.Info("Incident Invoice Email Sent to [" + invoiceIncident.IncidentUserInfo.Email + "]"); return true; } catch (InvalidApiRequestException ex) { for (int i = 0; i < ex.Errors.Length; i++) { Services.Log.Error(ex.Errors[i]); return false; } } return false; } else { return false; } }
static void Main(string[] args) { Dictionary <string, string> users = new Dictionary <string, string>(); users.Add("*****@*****.**", "Vadym Ivashyn"); users.Add("*****@*****.**", "Second Vadym"); var myMessage = new SendGrid.SendGridMessage(); myMessage.From = new MailAddress("*****@*****.**", "Title"); foreach (var u in users) { myMessage.AddTo(u.Key); } List <string> userNames = users.Values.ToList(); myMessage.AddSubstitution("%user%", userNames); myMessage.AddSubstitution("%title%", new List <string> { "Hello from title" }); myMessage.AddSubstitution("%body%", new List <string> { "Some text from body" }); myMessage.EnableTemplateEngine("57ece6c2-b625-4bd6-92e7-2def1a3b0693"); myMessage.Html = "Email content here"; myMessage.Subject = "Email subject here"; NetworkCredential nc = new NetworkCredential("*****@*****.**", "KPgZDZiM7c8hXHz"); var transportWeb = new SendGrid.Web(nc); transportWeb.DeliverAsync(myMessage).Wait(); Console.WriteLine("Good"); Console.ReadLine(); }
private static SendGridMessage BuildEmail(string name, string email, string link, string otherName) { var msg = new SendGridMessage(); msg.EnableTemplateEngine("5f7c4376-3b0c-4972-9049-ee13ef5b59af"); msg.DisableClickTracking(); msg.From = new MailAddress("*****@*****.**", "OkBoba 邮件"); msg.To = new MailAddress[] { new MailAddress(email, name) }; msg.Subject = string.Format(i18n.Messaging_Notification_Subject, otherName); msg.Html = string.Format(i18n.Messaging_Notification_Body, otherName); msg.AddSubstitution("-link-", new List<string>() { link }); return msg; }
// this code is used for the SMTPAPI examples private static void Main() { // Create the email object first, then add the properties. var myMessage = new SendGridMessage(); myMessage.AddTo("*****@*****.**"); myMessage.From = new MailAddress("*****@*****.**", "John Smith"); myMessage.Subject = "Testing the SendGrid Library"; myMessage.Text = "Hello World! %tag%"; var subs = new List<String> { "私はラーメンが大好き" }; myMessage.AddSubstitution("%tag%",subs); SendAsync(myMessage); Console.ReadLine(); }
/// <summary> /// Sends the mail batch using the SendGrid API /// </summary> /// <param name="mail">The mail.</param> /// <param name="recipients">The recipients.</param> /// <param name="onlyTestDontSendMail">if set to <c>true</c> [only test dont send mail].</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public override bool SendMailBatch(MailInformation mail, IEnumerable<JobWorkItem> recipients, bool onlyTestDontSendMail) { var settings = GetSettings(); if (recipients == null || recipients.Any() == false) throw new ArgumentException("No workitems", "recipients"); if (recipients.Count() > 1000) throw new ArgumentOutOfRangeException("recipients", "SendGrid supports maximum 1000 recipients per batch send."); var msg = new SendGridMessage(); msg.From = new MailAddress(mail.From); msg.Subject = mail.Subject; msg.Html = mail.BodyHtml; msg.Text = mail.BodyText; // Add recipinets to header, to hide other recipients in to field. List<string> addresses = recipients.Select(r => r.EmailAddress).ToList(); msg.Header.SetTo(addresses); msg.AddSubstitution("%recipient%", addresses); // To send message we need to have a to address, set that to from msg.To = new MailAddress[] { msg.From }; if (mail.EnableTracking) { // true indicates that links in plain text portions of the email // should also be overwritten for link tracking purposes. msg.EnableClickTracking(true); msg.EnableOpenTracking(); } if(mail.CustomProperties.ContainsKey("SendGridCategory")) { string category = mail.CustomProperties["SendGridCategory"] as string; if (string.IsNullOrEmpty(category) == false) msg.SetCategory(category); } var credentials = new NetworkCredential(settings.Username, settings.Password); // Create an Web transport for sending email. var transportWeb = new Web(credentials); transportWeb.Deliver(msg); return true; }
/// <summary> /// Generates a SendGrid-specific message from the given email message. /// </summary> /// <param name="message">The relevant email message to be converted to a SendGrid-specific message.</param> /// <returns></returns> private SendGridMessage GenerateMessage(EmailBase message) { var sender = new EmailAddress(message.SenderAddress, message.SenderName); var recipient = new EmailAddress(message.RecipientAddress, message.RecipientName); var sendGridMessage = new SendGridMessage(); sendGridMessage.SetFrom(sender); sendGridMessage.AddTo(recipient); sendGridMessage.SetTemplateId(message.TemplateId); foreach (var substitution in message.Substitutions) { sendGridMessage.AddSubstitution(substitution.Key, substitution.Value); } return(sendGridMessage); }
public async Task SendEmailMessageAsync(string toAddress, string fromAddress, string fromName, string subject, string template, EmailSendSuccessDelegate onSuccess, IDictionary<string, List<string>> substitutions, Action<string, IDictionary<string, string>> logIssue) { var myMessage = new SendGridMessage(); myMessage.AddTo(toAddress); myMessage.From = new MailAddress(fromAddress, fromName); myMessage.Subject = subject; myMessage.EnableTemplateEngine(template); if (default(IDictionary<string, List<string>>) != substitutions) { foreach (var substitutionsKvp in substitutions) myMessage.AddSubstitution(substitutionsKvp.Key, substitutionsKvp.Value); } // Create credentials, specifying your user name and password. var credentials = new NetworkCredential(username, password); // Create an Web transport for sending email. var transportWeb = new global::SendGrid.Web(credentials); // Send the email, which returns an awaitable task. try { await transportWeb.DeliverAsync(myMessage); } catch (InvalidApiRequestException ex) { var details = new StringBuilder(); details.Append("ResponseStatusCode: " + ex.ResponseStatusCode + ". "); for (int i = 0; i < ex.Errors.Count(); i++) { details.Append(" -- Error #" + i.ToString() + " : " + ex.Errors[i]); } throw new ApplicationException(details.ToString(), ex); } onSuccess.Invoke(toAddress); }
/// <summary> /// This feature allows you to create a message template, and specify different replacement /// strings for each specific recipient /// </summary> public void AddSubstitutionValues() { //create a new message object var message = new SendGridMessage(); //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.Text = "Hi %name%! Pleased to meet you!"; //set the message subject message.Subject = "Testing Substitution Values"; //This replacement key must exist in the message body var replacementKey = "%name%"; //There should be one value for each recipient in the To list var substitutionValues = new List<String> { "Mr Foo", "Mrs Raz" }; message.AddSubstitution(replacementKey, substitutionValues); //create an instance of the SMTP transport mechanism var transportInstance = new Web(new NetworkCredential(_username, _password)); //enable bypass list management message.EnableBypassListManagement(); //send the mail transportInstance.DeliverAsync(message); }
public void Test_Substitute() { var tag = "{this}"; var replacements = new List<string>() { "that", "that other", "and one other" }; var mail = BasicMailBuilder .Substitute(tag, replacements) .Build(); var message = new SendGridMessage(); message.AddSubstitution(tag, replacements); Assert.IsFalse(string.IsNullOrEmpty(message.Header.JsonString())); Assert.AreEqual(message.Header.JsonString(), mail.Header.JsonString()); }
public MailBuilder Substitute(string replacementTag, IEnumerable <string> substitutionValues) { sendgrid.AddSubstitution(replacementTag, substitutionValues.ToList()); return(this); }
public static void SendIncidentPaymentReceiptEmail(Payment payment, ApiServices Services) { SendGridMessage receiptMessage = new SendGridMessage(); IncidentInfo receiptIncident = new IncidentInfo(payment.IncidentGUID); receiptMessage.From = SendGridHelper.GetAppFrom(); receiptMessage.AddTo(receiptIncident.IncidentUserInfo.Email); receiptMessage.Html = " "; receiptMessage.Text = " "; receiptMessage.Subject = " "; receiptMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_ReceiptTemplateID"]); receiptMessage.AddSubstitution("%invoicestub%", new List<string> { receiptIncident.IncidentGUID.Substring(0, 5).ToUpper() }); receiptMessage.AddSubstitution("%name%", new List<string> { receiptIncident.IncidentUserInfo.Name }); receiptMessage.AddSubstitution("%jobdescription%", new List<string> { receiptIncident.JobCode }); receiptMessage.AddSubstitution("%servicefee%", new List<string> { receiptIncident.ServiceFee.ToString() }); receiptMessage.AddSubstitution("%datesubmitted%", new List<string> { DateTime.Now.ToShortDateString() }); receiptMessage.AddSubstitution("%paymentmethod%", new List<string> { receiptIncident.PaymentMethod }); receiptMessage.AddSubstitution("%paymentamount%", new List<string> { receiptIncident.PaymentAmount.ToString() }); // Create an Web transport for sending email. var transportWeb = new Web(SendGridHelper.GetNetCreds()); // Send the email. try { transportWeb.Deliver(receiptMessage); Services.Log.Info("Payment Receipt Email Sent to [" + receiptIncident.IncidentUserInfo.Email + "]"); } catch (InvalidApiRequestException ex) { for (int i = 0; i < ex.Errors.Length; i++) { Services.Log.Error(ex.Errors[i]); } } }
public static void SendIncidentSubmissionAdminEmail(Incident incident, ApiServices Services) { SendGridMessage submissionMessage = new SendGridMessage(); IncidentInfo submisionIncident = new IncidentInfo(incident); submissionMessage.From = SendGridHelper.GetAppFrom(); submissionMessage.AddTo(WebConfigurationManager.AppSettings["RZ_SysAdminEmail"]); submissionMessage.Html = " "; submissionMessage.Text = " "; submissionMessage.Subject = " [" + WebConfigurationManager.AppSettings["MS_MobileServiceName"] + "]"; submissionMessage.EnableTemplateEngine(WebConfigurationManager.AppSettings["RZ_SubmisionTemplateID"]); submissionMessage.AddSubstitution("%timestamp%", new List<string> { submisionIncident.CreatedAt.ToString() }); submissionMessage.AddSubstitution("%incidentguid%", new List<string> { submisionIncident.IncidentGUID }); submissionMessage.AddSubstitution("%vehicledetails%", new List<string> { submisionIncident.IncidentVehicleInfo.RegistrationNumber }); submissionMessage.AddSubstitution("%name%", new List<string> { submisionIncident.IncidentUserInfo.Name }); submissionMessage.AddSubstitution("%phone%", new List<string> { submisionIncident.IncidentUserInfo.Phone }); submissionMessage.AddSubstitution("%email%", new List<string> { submisionIncident.IncidentUserInfo.Email }); submissionMessage.AddSubstitution("%jobdescription%", new List<string> { submisionIncident.JobCode }); submissionMessage.AddSubstitution("%location%", new List<string> { submisionIncident.LocationObj.RGDisplay }); // Create an Web transport for sending email. var transportWeb = new Web(SendGridHelper.GetNetCreds()); // Send the email. try { transportWeb.Deliver(submissionMessage); Services.Log.Info("New Incident Submission Email Sent to [" + submisionIncident.IncidentUserInfo.Email + "]"); } catch (InvalidApiRequestException ex) { for (int i = 0; i < ex.Errors.Length; i++) { Services.Log.Error(ex.Errors[i]); } } }
//Note that at the moment, we actually are submitting through SendGrid, not Gmail. public async void Send(EnvelopeDO envelope) { if (envelope == null) throw new ArgumentNullException("envelope"); if (!string.Equals(envelope.Handler, EnvelopeDO.SendGridHander, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(@"This envelope should not be handled with Gmail.", "envelope"); if (envelope.Email == null) throw new ArgumentException(@"This envelope has no Email.", "envelope"); if (envelope.Email.Recipients.Count == 0) throw new ArgumentException(@"This envelope has no recipients.", "envelope"); var email = envelope.Email; if (email == null) throw new ArgumentException(@"Envelope email is null", "envelope"); try { var fromName = !String.IsNullOrWhiteSpace(email.FromName) ? email.FromName : email.From.Name; var mailMessage = new SendGridMessage { From = new MailAddress(email.From.Address, fromName) }; if (!String.IsNullOrWhiteSpace(email.ReplyToAddress)) { mailMessage.ReplyTo = new[] { new MailAddress(email.ReplyToAddress, email.ReplyToName) }; } mailMessage.To = email.To.Select(toEmail => new MailAddress(toEmail.Address, toEmail.NameOrAddress())).ToArray(); mailMessage.Bcc = email.BCC.Select(bcc => new MailAddress(bcc.Address, bcc.NameOrAddress())).ToArray(); mailMessage.Cc = email.CC.Select(cc => new MailAddress(cc.Address, cc.NameOrAddress())).ToArray(); mailMessage.Subject = email.Subject; if ((email.PlainText == null || email.HTMLText == null) && string.IsNullOrEmpty(envelope.TemplateName)) { throw new ArgumentException("Trying to send an email that doesn't have both an HTML and plain text body"); } if (email.PlainText == null || email.HTMLText == null) { mailMessage.Html = "<html></html>"; mailMessage.Text = ""; } else { mailMessage.Html = email.HTMLText; mailMessage.Text = email.PlainText; } var headers = new Dictionary<String, String>(); if (!String.IsNullOrEmpty(email.MessageID)) headers.Add("Message-ID", email.MessageID); if (!String.IsNullOrEmpty(email.References)) headers.Add("References", email.References); if (headers.Any()) mailMessage.AddHeaders(headers); foreach (var attachment in email.Attachments) { mailMessage.AddAttachment(attachment.GetData(), attachment.OriginalName); } if (!string.IsNullOrEmpty(envelope.TemplateName)) { mailMessage.EnableTemplateEngine(envelope.TemplateName);//Now TemplateName will be TemplateId on Sendgrid. if (envelope.MergeData != null) { //Now, we need to do some magic. //Basically - we need the length of each substitution to match the length of recipients //In our case, most of the time, all the substitutions are the same, except for token-related fields //To make it easier to use, we attempt to pad out the substition arrays if they lengths don't match //We only do that if we're given a string value. In any other case, we allow sengrid to fail. var subs = new Dictionary<String, List<String>>(); foreach (var pair in envelope.MergeData) { var arrayType = pair.Value as JArray; List<String> listVal; if (arrayType != null) { listVal = arrayType.Select(a => a.ToString()).ToList(); } else { listVal = new List<string>(); for (var i = 0; i < email.Recipients.Count(); i++) //Pad out the substitution listVal.Add(pair.Value == null ? String.Empty : pair.Value.ToString()); } subs.Add(pair.Key, listVal); } foreach(var sub in subs) mailMessage.AddSubstitution(sub.Key, sub.Value); } } try { await _transport.DeliverAsync(mailMessage); OnEmailSent(email.Id); } catch (Exception ex) { OnEmailRejected(ex.Message, email.Id); } } catch (Exception ex) { OnEmailCriticalError(-1, "Unhandled exception.", ex.Message, email.Id); } }
private SendGridMessage CreateDefaultMessage(string templateId) { var message = new SendGridMessage { From = new MailAddress(_globalSettings.Mail.ReplyToEmail, _globalSettings.SiteName), Html = " ", Text = " " }; if(!string.IsNullOrWhiteSpace(templateId)) { message.EnableTemplateEngine(templateId); } message.AddSubstitution("{{siteName}}", new List<string> { _globalSettings.SiteName }); message.AddSubstitution("{{baseVaultUri}}", new List<string> { _globalSettings.BaseVaultUri }); return message; }
public void SimpleEmail(string strTo, string strToEmail, string templateid, Hashtable hstemp, string subject) { try { // From string strFrom = "*****@*****.**"; string strFromName = "Arb bot"; var myMessage = new SendGrid.SendGridMessage(); myMessage.AddTo(strToEmail); myMessage.From = new MailAddress(strFrom, strFromName); myMessage.Subject = subject; myMessage.Text = " "; myMessage.Html = " "; foreach (DictionaryEntry entry in hstemp) { List <string> templist = new List <string>(); templist.Add(entry.Value.ToString()); myMessage.AddSubstitution(entry.Key.ToString(), templist); } //Filters var filters = new Dictionary <string, dynamic>() { { "opentrack", new Dictionary <string, dynamic>() { { "settings", new Dictionary <string, dynamic>() { { "enable", 1 } } } } }, { "templates", new Dictionary <string, dynamic>() { { "settings", new Dictionary <string, dynamic>() { { "enable", 1 }, { "template_id", templateid } } } } } }; foreach (var filter in filters.Keys) { var settings = filters[filter]["settings"]; foreach (var setting in settings.Keys) { myMessage.Header.AddFilterSetting(filter, new List <string> { setting }, Convert.ToString(settings[setting])); } } /* CREDENTIALS * ===================================================*/ string sgUsername = ConfigurationSettings.AppSettings["Sendgrid_username"]; string sgPassword = ConfigurationSettings.AppSettings["Sendgrid_pwd"]; /* SEND THE MESSAGE * ===================================================*/ var credentials2 = new NetworkCredential(sgUsername, sgPassword); // Create a Web transport for sending email. var transportWeb = new Web(credentials2); // Send the email. transportWeb.Deliver(myMessage); } catch (Exception ex) { Console.WriteLine(ex.Message); } }