How can edit body message email template by Plugin - c#

How can I edit an E-mail template Body by plugin in CRM 2016?
The Template already exist, I retrieve the Template ID by code plugin, and I want edit the message body by plugin.
To retrieve the message body email template I use the 'description' attribute.
and if I want to update the body email template with this attribute, with 'description', this updated the description box not the body message.
The following code describes receiving an e-mail template, how can update the message body by this Template?
private Entity GetTemplateByName(IOrganizationService client, string templateName)
{
var query = new QueryExpression();
query.EntityName ="template";
var filter = new FilterExpression();
var condition1 = new ConditionExpression("title", ConditionOperator.Equal, new object[] { templateName });
filter.AddCondition(condition1);
query.Criteria = filter;
EntityCollection allTemplates = client.RetrieveMultiple(query);
Entity emailTemplate = null;
if (allTemplates.Entities.Count > 0)
{
emailTemplate = allTemplates.Entities[0];
}
return emailTemplate;
}

From the SDK, the Template entity has an attribute called body which is described as:
Body text of the email template
body has an AttributeTypeCode of AttributeType.Memo, which is a string.
You should be able to simply use:
emailTemplate["body"] = "Some new email template body.";

Related

Interpolate model values into dynamic template using SendGridMessage

I'm building my email for sending with the SendGrid library's SendGridMessage object.
I'm defining my values as an anonymous type which I'm injecting with the SendGridMessage's SetTemplateData() method:
var mail = new SendGridMessage
{
Attachments = new List<Attachment>(),
From = new EmailAddress()
{
Email = emailConfig.FromAddress,
Name = $"Redacted on behalf of {booking.Member.Client.Name}"
},
TemplateId = EmailConstants.ConfirmationEmailTemplateId,
Subject = "Redacted"
};
mail.Personalizations = new List<Personalization>() {
new Personalization() {
Tos = new List<EmailAddress>() {
new EmailAddress() {
Email = memberEmail,
Name = memberName
},
}
}
};
var data = new
{
memberName = memberName,
dateOfAppointment = booking.Date.ToString("dd MMM yy"),
timeOfAppointment = booking.Date.ToString("HH:mm"),
questionnaireLink = questionnaireLink
};
mail.SetTemplateData(data);
The email gets sent out perfectly fine, but in the email template, my tags {memberName}, {dateofAppointment}, etc. are not being replaced by the values indicated here.
I've found handlebars but no C# guide to use them; I'd assume the data I'm submitting above would work so long as I get the tags right in the template... Am I right?
How do I replace the indicated tags ({memberName}, {dateofAppointment}, etc.) in my dynamic template with my data values?
Make sure your template contains tags using double-brace syntax, like {{memberName}}. {memberName} (single braces) won't work.
From the SendGrid docs on Handlebars syntax,
<!-- Template -->
<p>Hello {{ firstName }}</p>
// Test data
{ "firstName": "Ben" }
<!-- Resulting HTML -->
<p>Hello Ben</p>
If this syntax is used properly in the template, the code in your question will work just fine.

How do I send a Sendgrid email using a template and add custom data for the template?

I can send a simple email, I can also send emails using a specific template w/ the TemplateId like the example below, but
QUESTION - How do I send this template below and add or include handlebar data (ex. {"name":"Mike", "url":"some_url", "date":"04/18/2022})?
FYI - I can't find any doc that shows any C# examples. I did find this link to create a transactional template but it doesn't send the email. So not sure here if this is what I'm looking for...
var client = new SendGridClient(Options.SendGridKey);
var msg = new SendGridMessage() {
From = new EmailAddress(fromEmailAddress, fromEmailName),
Subject = subject,
PlainTextContent = message,
HtmlContent = message,
TemplateId = "d-30710e173a174ab58cc641nek3c980d4c"
};
var response = await client.SendEmailAsync(msg);
The solution is that you need to remove the PlainTextContent and HtmlContent properties to make use of the template. Also, you need to provide a dynamicTemplateData object that contains your placeholders.
Here are two code examples that send dynamic template emails with and without the helper class (search for dynamic_template_data and dynamicTemplateData). So the full snippet with the mail helper class would be:
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage();
msg.SetFrom(new EmailAddress("test#example.com", "Example User"));
msg.AddTo(new EmailAddress("test#example.com", "Example User"));
msg.SetTemplateId("d-d42b0eea09964d1ab957c18986c01828");
var dynamicTemplateData = new ExampleTemplateData
{
Subject = "Hi!",
Name = "Example User",
Location = new Location
{
City = "Birmingham",
Country = "United Kingdom"
}
};
msg.SetTemplateData(dynamicTemplateData);
var response = await client.SendEmailAsync(msg);
PS: Here is the general API documentation that explains the available properties.

Apply Template using .NET SDK

I'm trying to apply a template (not use a template) using the .NET SDK and I can't seem to get it. I have seen one or two other articles on here but neither is using the SDK. Can anyone help me solve this using the SDK?
My situation is this: I have a template defined that contains all of my anchor tags with placement info. When I apply the template via the UI, it works fine and the tags get placed appropriately. When I upload the same document via the API, the tags are not applied.
I have tried to replicate what is shown in these articles using Composite Templates with no success:
How do I apply a server template to envelope document in DocuSign API?
Docusign API - Create envelope, apply template, prefill values
In one of the articles, the OP said the envelope needed to be a Draft. I tried that, but then I haven't been able to change it to "sent" after that.
Here's some of the relevant code from my ASP.NET Web Forms test project. In this project, I'm using a asp:FileUpload control to grab the file contents and then I call the SendFileToDocusign() method:
private void SendFileToDocusign(byte[] fileData, string accessToken)
{
//Create a signer recipient to sign the document, identified by name and email
//We set the clientUserId to enable embedded signing for the recipient
Signer tmpSigner1 = new Signer {
Email = "me#me.com", Name = "Test Tester",
ClientUserId = "1000", RecipientId = "1", RoleName = "Signer1", CustomFields = new List<string> { "Buyer1" }
};
//Step 1. Create the envelope definition
EnvelopeDefinition tmpEnvDef = MakeEnvelopeAndApplyTemplate(fileData, new List<Signer> { tmpSigner1 });
//Step 2. Call DocuSign to create the envelope
ApiClient tmpClient = new ApiClient(DOCUSIGN_API_BASEPATH);
tmpClient.Configuration.AddDefaultHeader("Authorization", "Bearer " + accessToken);
EnvelopesApi tmpEnvelopesApi = new EnvelopesApi(tmpClient);
EnvelopeSummary tmpResults = tmpEnvelopesApi.CreateEnvelope(DOCUSIGN_ACCOUNTID, tmpEnvDef);
string tmpEnvelopeID = tmpResults.EnvelopeId;
//Step 3. create the recipient view, the Signing Ceremony
RecipientViewRequest tmpViewRequest = MakeRecipientViewRequest(tmpSigner1);
//call the CreateRecipientView API
ViewUrl tmpRecipView = tmpEnvelopesApi.CreateRecipientView(DOCUSIGN_ACCOUNTID, tmpEnvelopeID, tmpViewRequest);
Response.Redirect(tmpRecipView.Url);
}
private EnvelopeDefinition MakeEnvelopeAndApplyTemplate(byte[] fileData, List<Signer> signers)
{
EnvelopeDefinition tmpEnv = new EnvelopeDefinition(EmailSubject:"We don't really use the Subject Line here");
Document tmpDoc = new Document();
Recipients tmpRecipients = new Recipients(Signers:signers);
CompositeTemplate tmpCompTemplate = new CompositeTemplate("1");
string tmpfileDataB64 = Convert.ToBase64String(fileData);
tmpDoc.DocumentBase64 = tmpfileDataB64;
tmpDoc.Name = "Test file";//can be different from actual file name
tmpDoc.FileExtension = "pdf";
tmpDoc.DocumentId = "1";
InlineTemplate tmpInlineTemplate = new InlineTemplate();
tmpInlineTemplate.Sequence = "1";
tmpInlineTemplate.Recipients = tmpRecipients;
ServerTemplate tmpServerTemplate = new ServerTemplate("2", DOCUSIGN_TEMPLATE_ID);
tmpCompTemplate.ServerTemplates = new List<ServerTemplate>() { tmpServerTemplate };
tmpCompTemplate.InlineTemplates = new List<InlineTemplate>() { tmpInlineTemplate };
tmpCompTemplate.Document = tmpDoc;
tmpEnv.CompositeTemplates = new List<CompositeTemplate>() { tmpCompTemplate };
//Request that the envelope be sent by setting |status| to "sent".
//To request that the envelope be created as a draft, set to "created"
tmpEnv.Status = "sent";
return tmpEnv;
}
Thanks for any help you can offer.
Your code has to handle the recipients correctly.
The roleName must match between recipients pre-defined in the template and the ones you add in your code.
I don't see in your code that part.
The example you use is for composite template. The relevant code for this is in a regular template example but it's the same.
https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/eSignature/Controllers/Eg009UseTemplateController.cs
TemplateRole signer1 = new TemplateRole();
signer1.Email = signerEmail;
signer1.Name = signerName;
signer1.RoleName = "signer";
TemplateRole cc1 = new TemplateRole();
cc1.Email = ccEmail;
cc1.Name = ccName;
cc1.RoleName = "cc";

Sendgrid C# bulk email X-SMTPAPI header not working

I am trying to send email with SendGrid to multiple recipients in an ASP.Net C# web application
According to the SendGrid documentation I need to add X-SMTPAPI header to my message in JSON formatted string. I do so, for first check I just added a hand-typed string before building my json email list progamatically here is my code:
string header = "{\"to\": [\"emailaddress2\",\"emailaddress3\"], \"sub\": { \"%name%\": [\"Ben\",\"Joe\"]},\"filters\": { \"footer\": { \"settings\": { \"enable\": 1,\"text/plain\": \"Thank you for your business\"}}}}";
string header2 = Regex.Replace(header, "(.{72})", "$1" + Environment.NewLine);
var myMessage3 = new SendGridMessage();
myMessage3.From = new MailAddress("emailaddress1", "FromName");
myMessage3.Headers.Add("X-SMTPAPI", header2);
myMessage3.AddTo("emailaddress4");
myMessage3.Subject = "Test subject";
myMessage3.Html = "Test message";
myMessage3.EnableClickTracking(true);
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential(ConfigurationManager.AppSettings["xxxxx"], ConfigurationManager.AppSettings["xxxxx"]);
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email, which returns an awaitable task.
transportWeb.DeliverAsync(myMessage3);
But it just seems to ignore my header, and sends the email to the one email "emailaddress4" used in "addto".
According the documentation if the header JSON is parsed wrongly, then SendGrid sends an email about the error to the email address set in "FROM" field, but I get no email about any error.
Anyone got any idea?
For me using the latest 9.x c# library the only way I could solve this was by using the MailHelper static functions like this:
var client = new SendGridClient(HttpClient, new SendGridClientOptions { ApiKey = _sendGridApiKey, HttpErrorAsException = true });
SendGridMessage mailMsg;
var recipients = to.Split(',').Select((email) => new EmailAddress(email)).ToList();
if (recipients.Count() > 1)
{
mailMsg = MailHelper.CreateSingleEmailToMultipleRecipients(
new EmailAddress(from),
recipients,
subject,
"",
body);
}
else
{
mailMsg = MailHelper.CreateSingleEmail(
new EmailAddress(from),
recipients.First(),
subject,
"",
body);
}
if (attachment != null)
{
mailMsg.AddAttachment(attachment.Name,
attachment.ContentStream.ToBase64(),
attachment.ContentType.MediaType);
}
var response = await client.SendEmailAsync(mailMsg).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
_log.Trace($"'{subject}' email to '{to}' queued");
return true;
}
else {
throw new HttpRequestException($"'{subject}' email to '{to}' not queued");
}
I'm not sure why you wouldn't recieve any errors at your FROM address, but your JSON contains the following flaws:
, near the end makes the string invalid json
spaces around the first % in %name%, that might make sendgrid think it's an invalid substitution tag
if you use the X-SMTPAPI header to specify multiple recipients, you are not supposed to add a standard SMTP TO using AddTo().
Besides that, you didn't wrap the header at 72 characters (see the example in the documentation).
I figured that however the X-SMTPAPI documentation talks about passing the header as JSON, the API itself expects it as a parameter, containing Ienumerable string. So the working code is:
var myMessage3 = new SendGridMessage();
myMessage3.From = new MailAddress("email4#email.com", "Test Sender");
myMessage3.AddTo("email2#email.com");
myMessage3.Subject = "Új klubkártya regisztrálva";
myMessage3.Html = "Teszt üzenet";
myMessage3.EnableClickTracking(true);
/* SMTP API
* ===================================================*/
// Recipients
var addresses = new[]{
"email2#email.com", "email3#email.com"
};
//string check = string.Join(",", addresses);
myMessage3.Header.SetTo(addresses);
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential(ConfigurationManager.AppSettings["xxxxxxx"], ConfigurationManager.AppSettings["xxxxxxxxx"]);
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email, which returns an awaitable task.
transportWeb.DeliverAsync(myMessage3);

Sending Mandrill Email from C#

I have a Mandrill email template defined which I would like to send. Before sending I would like to replace certain parameters defined in the template.
For example, one of the emails is for Forgot Password and I would like to replace the new password in the template for parameter |NEW_PASSWORD|
My template was created in MailChimp and imported into Mandrill and I am using the following .Net Library:
Here is the code I have so far
var api = new MandrillApi(api_key);
var recipients = new List<Mandrill.Messages.Recipient>();
recipients.Add(new Mandrill.Messages.Recipient(user_email, user_name));
Mandrill.NameContentList<string> content = new Mandrill.NameContentList<string>();
MVList<Mandrill.Messages.SendResult> result = api.SendTemplate(template, content, message);
Any help is appreciated.
Thanks
Rohit
1)install nuget package from
https://github.com/shawnmclean/Mandrill-dotnet
2)in you template add placeholder like.
{{vendor_name}}
3)replace placeholder using global_merge_vars in api.
they provided
AddGlobalVariable method with placeholder name and value which you want to replace.
Mandrill.Models.EmailMessage email = new Mandrill.Models.EmailMessage();
email.FromEmail = "teste#xxx.com";
email.Subject = "Mandrill API Template Replace";
email.RawMessage = "Hello Pradip Patel";
email.MergeLanguage = "handlebars";
email.AddGlobalVariable("vendor_name", "FI Test");
//your template name
string TemplateName = "Your Template Name.";
email.To = new List<Mandrill.Models.EmailAddress>()
{
new Mandrill.Models.EmailAddress("pradippatel1411#gmail.com")
};
Mandrill.Requests.Messages.SendMessageTemplateRequest objTemp =
new Mandrill.Requests.Messages.SendMessageTemplateRequest(email, TemplateName);
var results = await api.SendMessageTemplate(objTemp);
I use handlebars as Merge Language on mandrill http://blog.mandrill.com/handlebars-for-templates-and-dynamic-content.html
Then I send variables which hold the same names as in the template, or even full objects which hold same members name to match what variables in the templates and then Handlebar and Mandrill handle mapping these to the template.

Categories