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.
Related
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.
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.
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";
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.";
I've just created a sendgrid account. Then I went to settings=>API Keys
and clicked on "Create API Key" and gave any possible permission.
Then I've created a c# project, added nuget packages and put my write the hello world code from here
public async Task HelloEmail()
{
dynamic sg = new SendGrid.SendGridAPIClient("XXX-XXXXXXXXXXXXXXXXXX", "https://api.sendgrid.com");
Email from = new Email("MY#Email.com");
String subject = "Hello World from the SendGrid CSharp Library";
Email to = new Email("test#example.com");
Content content = new Content("text/plain", "Textual content");
Mail mail = new Mail(from, subject, to, content);
Email email = new Email("test2#example.com");
mail.Personalization[0].AddTo(email);
dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
var x=response.StatusCode;
var y = response.Body.ReadAsStringAsync().Result;
var z = response.Headers.ToString();
}
But I get
Unauthorized =>
"{\"errors\":[{\"message\":\"The provided authorization grant is invalid, expired, or revoked\",\"field\":null,\"help\":null}]}"
In the example, they got the API key from the EnvironmentVariableTarget.User is it related to that?
string apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY", EnvironmentVariableTarget.User);
dynamic sg = new SendGridAPIClient(apiKey);
*The problem is that no one reads messages when creating a key, also Microsoft chooses to show us "API Key ID" which is worst name ever
It is not a duplicate because although the reason was the same, no one would guess it since in c# we use a nuget library, not the api.
Something is wrong with your API key. Check this answer, generate a new key, and double check your permissions.
You also don't need to specify the URL in your SendGrid.SendGridAPIClient. I'd remove that line to reduce hardcoded values.
Put key directly , do not use System.getenv(KEY)
String key = "YOUR KEY";
SendGrid sg = new SendGrid(key);