本文整理汇总了C#中SendGrid.SendGridMessage.AddSubstitution方法的典型用法代码示例。如果您正苦于以下问题:C# SendGridMessage.AddSubstitution方法的具体用法?C# SendGridMessage.AddSubstitution怎么用?C# SendGridMessage.AddSubstitution使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SendGrid.SendGridMessage
的用法示例。
在下文中一共展示了SendGridMessage.AddSubstitution方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SendCurrentIncidentInvoiceEmail
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;
}
}
示例2: BuildEmail
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("[email protected]", "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;
}
示例3: Main
// 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("[email protected]");
myMessage.From = new MailAddress("[email protected]", "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();
}
示例4: SendMailBatch
/// <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;
}
示例5: SendEmailMessageAsync
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);
}
示例6: AddSubstitutionValues
/// <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);
}
示例7: Test_Substitute
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());
}
示例8: SendIncidentPaymentReceiptEmail
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]);
}
}
}
示例9: SendIncidentSubmissionAdminEmail
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]);
}
}
}
示例10: Send
//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);
//.........这里部分代码省略.........
示例11: CreateDefaultMessage
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;
}