SendGrid API Substitutions not working in C# - c#

I created a simple email dynamic transactional email template in SendGrid with only tag "First_Name".
When I DO NOT use a substitution everything works fine i.e. I get an email. But when I do use a substitution the email fails. Here is the code that uses substitution.
var client = new SendGridClient(apiKey);
Personalization personalization = new Personalization();
personalization.Substitutions = new Dictionary<string, string>() { {"First_Name","Don" } };
var msgs = new SendGridMessage()
{
TemplateId = "d-123",
From = new EmailAddress("info#domain.us", "Name"),
Subject = "Account is ready",
ReplyTo = new EmailAddress("info#domain.us", "Name"),
Personalizations = new List<Personalization>() { personalization },
};
msgs.AddTo(new EmailAddress("user#email.com"));
msgs.AddBcc(new EmailAddress("admin#domain.us));
msgs.SetClickTracking(true, true);
var responses = await client.SendEmailAsync(msgs);
Any help will be most appreciated.

Related

Can you have a returnUrlRequest for a sender view generated from a bulk send?

I'm trying to create a workflow where a user can do a bulk send through docusign within my application. They would select the clients they want to send forms to for a signature, be presented with a sender view to specify what fields they require, send it off, then have it post back to my application in order to generate emails for embedded signing. However, currently, it doesn't return back to my application after the user has sent off the bulk request despite the return url request being set. Is this currently not possible with a bulk send request?
The following is just some code to generate the sender view url:
// Create envelope definition
var envelopeDefinition = new EnvelopeDefinition
{
EmailSubject = documentDesc,
Documents = new List<Document>(),
Recipients = new Recipients { Signers = new List<Signer> {
new Signer
{
Name = "Multi Bulk Recipient::signer",
Email = "multiBulkRecipients-signer#docusign.com",
RoleName = "signer",
RoutingOrder = "1",
Status = "sent",
DeliveryMethod = "Email",
RecipientId = "1",
RecipientType = "signer"
}
} },
CustomFields = new CustomFields()
{
TextCustomFields = new List<TextCustomField>()
{
new TextCustomField() {Name = "Client", Value = _config.DatabaseName},
new TextCustomField() {Name = "Server", Value = _config.DatabaseServer},
new TextCustomField() {Name = "DocId", Value = documentId.ToString()}
}
},
EnvelopeIdStamping = "true",
};
// Read a file from disk to use as a document.
byte[] fileBytes = File.ReadAllBytes("test.pdf");
// Add a document to the envelope
Document doc = new Document();
doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
doc.Name = "TestFile.pdf";
doc.DocumentId = "1";
envDef.Documents = new List<Document>();
envDef.Documents.Add(doc);
// Add each recipient and add them to the envelope definition
var recipients = new List<BulkSendingCopyRecipient>();
var recipients = new List<BulkSendingCopyRecipient> {
new BulkSendingCopyRecipient
{
Name = "Bob Ross",
Email = "bobross#happymistakes.com",
ClientUserId = "1234",
CustomFields = new List<string>()
{
"A custom field for internal use"
},
RoleName = "signer"
},
new BulkSendingCopyRecipient
{
Name = "Fred Rogers",
Email = "mrrogers#neighborhood.com",
ClientUserId = "5678",
CustomFields = new List<string>()
{
"Another custom field for internal use"
},
RoleName = "signer"
}
};
var bulkSendingCopy = new BulkSendingCopy
{
Recipients = recipients
};
var bulkCopies = new List<BulkSendingCopy>
{
bulkSendingCopy
};
var bulkSendingList = new BulkSendingList
{
BulkCopies = bulkCopies
};
bulkSendingList.Name = "A document name";
envelopeDefinition.Status = "created";
var envelopesApi = new EnvelopesApi(config);
var bulkEnvelopesApi = new BulkEnvelopesApi();
var createBulkListResult = bulkEnvelopesApi.CreateBulkSendList(AccountId, bulkSendingList);
envelopeDefinition.CustomFields.TextCustomFields.Add(
new TextCustomField
{
Name = "mailingListId",
Required = "false",
Show = "false",
Value = createBulkListResult.ListId //Adding the BULK_LIST_ID as an Envelope Custom Field
}
);
var envelopeSummary = envelopesApi.CreateEnvelope(AccountId, envelopeDefinition);
var options = new ReturnUrlRequest
{
ReturnUrl = HttpContext.Current.Request.Url.Scheme + "://" +
HttpContext.Current.Request.Url.Authority +
HttpContext.Current.Request.ApplicationPath +
"/SIP/ConfirmTagSendAndPublish.aspx?idockey=" + documentId
};
var senderView = envelopesApi.CreateSenderView(AccountId, envelopeSummary.EnvelopeId, options);
var senderViewInfo = new string[2];
senderViewInfo[0] = senderView.Url;
senderViewInfo[1] = envelopeSummary.EnvelopeId;
return senderViewInfo;
When the sender view comes up and you hit send it just takes me to the Sent tab in docusign
What I see after send
So in order for you to do the scenario you're asking to do, you will have to take a slightly different approach:
Generate a regular envelope in draft mode with the things you need.
Have user interact with it in embedded sending experience.
Generate a bulk using the CreateBulkList() method based on the envelope from #2 and the users you add like in your code.
(to do #3 you may need to copy custom fields etc. from the initial envelope to the one used for custom fields)

retrieve email from CRM in the activities from account entity

This is my code for sending email.
private void SendEmail(Guid accountToGuid)
{
string name = GetName(service, accountToGuid);
#region Email
Entity fromParty = new Entity("activityparty");
fromParty["partyid"] = new EntityReference("systemuser", ownerId);
Entity toParty = new Entity("activityparty");
toParty["partyid"] = new EntityReference("account", accountToGuid);
Entity Email = new Entity("email");
Email.Attributes["from"] = new Entity[] { fromParty };
Email.Attributes["to"] = new Entity[] { toParty };
Email.Attributes["subject"] = "Hello " + name;
Email.Attributes["description"] = "Your account has been confirmed by Admin";
Email.Attributes["ownerid"] = new EntityReference("systemuser", ownerId);
Guid EmailId = service.Create(Email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = EmailId;
req.IssueSend = true;
req.TrackingToken = "";
SendEmailResponse res = (SendEmailResponse)service.Execute(req);
#endregion
}
Lets say, I already sent an email to account. Email will display in activities section. How to retrieve it from SDK?
You need to perform either:
(Full examples in links)
Retrieve - When you already know the record Id, email Id in your case.
RetrieveMultiple - When you don't know the record Id, but you are going to search based on some other criteria, e.g. emails related to the account Id.

Using X-SMTPAPI in sendgrid not working

Please help! I'm new to SendGrid and I need to send a mass email, so I found this X-SMTPAPI on SendGrid. The problem is that email was only sent to "TO" only. You can give another approach if you like. Here's my code.
Email from = new Email(retsendemail.From);
Email to = new Email(retsendemail.To);
String subject = retsendemail.Subject;
Content content = new Content("text/html", retsendemail.Body);
Mail mail = new Mail(from, subject, to, content);
var header = new Header();
var recipients = new List<String> { "test1#xxx.com", "test2#xxx.com", "test3#xxx.com" };
header.SetTo(recipients);
var subs1 = new List<String> { "t1", "t2", "t3" };
header.AddSubstitution("%name%", subs1);
string jsonvalue = header.JsonString();
Dictionary<String, String> headers = new Dictionary<String, String>();
headers.Clear();
headers.Add("X-SMTPAPI", jsonvalue);
dynamic response = sg.client.mail.send.post(requestBody: mail.Get(), requestHeaders: headers).GetAwaiter().GetResult();
string statusCode = ((object)response.StatusCode).ToString();
string headerString = response.Headers.ToString() as string;
Here's the Jsonvalue:
{
"to": [
"test1#xxx.com",
"test2#xxx.com",
"test3#xxx.com"
],
"sub": {
"%name%": [
"t1",
"t2",
"t3"
]
}
}

How to implement Signer Attachment in Docusign?

The requirement which I have regarding docusign is I need to implement Signer Attachment and that same scenario is mentioned at [https://github.com/docusign/docusign-soap-sdk/wiki/Code-Walkthrough-_-Signer-Attachments]
But I am not sure how do I achieve with code in C#. As not sure how do I attach it to Envelope?
I want to send someone a contract letter to sign and also request them attach few docs and when all of that is completed , those docs should be sent to my email.
Anyone knows if I can achieve it with docusign?
The previous entry is not bad... I got it working eventually. But this code below is solid, in production, and works great! It also uses anchor strings.
EnvelopeDefinition env = new EnvelopeDefinition();
env.EmailSubject = "Please sign this document set";
Document doc4 = new Document
{
DocumentBase64 = doc4PdfBytes,
Name = "Voided Check Attachment", // can be different from actual file name
FileExtension = "pdf",
DocumentId = "4"
};
env.Documents = new List<Document> { doc4 };
SignerAttachment signAttachDoc = new SignerAttachment
{
TabLabel = "Attach your voided check",
DocumentId = "1",
TabId = "1",
PageNumber = "1",
AnchorString = "/at1/",
AnchorUnits = "pixels",
AnchorXOffset = "0",
AnchorYOffset = "0",
AnchorIgnoreIfNotPresent = "false",
};
Tabs signer1Tabs = new Tabs
{
SignerAttachmentTabs = new List<SignerAttachment> { signAttachDoc }
};
signer1.Tabs = signer1Tabs;
Recipients recipients1 = new Recipients
{
Signers = new List<Signer> { signer1 }
};
env.Recipients = recipients1;
Here is how we can do it while using C# SDK
create a signer object
Signer signer = new Signer();
signer.Name = recipientName;
signer.Email = recipientEmail;
signer.RecipientId = "1";
then create attachment tabs
signer.Tabs.SignerAttachmentTabs = new List<SignerAttachment>();
after which we need an attachment to add to it
SignerAttachment signDoc = new SignerAttachment();
signDoc.TabLabel = "Attach your Other Doc";
signDoc.DocumentId = "1";
signDoc.TabId = "1";
signDoc.PageNumber = "1";
And finally we add it to the tabs
signer.Tabs.SignerAttachmentTabs.Add(signDoc);

Adding document to docusign envelope always return false

I'm using the following code to try to add a pdf document to an existing template with multiple documents using the AddDocument function of the c# API but the result is always false. The template is succesfully sent with all the preset documents sent correctly. How do I correctly add the pdf document? I have to add the pdf document using code because this particular document is different every time we send the template. I have tested GetIPS function and it returned the byte[] for the pdf document so I know that's not the issue.
Here are my codes
byte[] ips = GetIPS("");
RestSettings.Instance.DocuSignAddress = "https://demo.docusign.net";
RestSettings.Instance.WebServiceUrl = RestSettings.Instance.DocuSignAddress + "/restapi/v2";
RestSettings.Instance.IntegratorKey = integratorKey;
DocuSign.Integrations.Client.Account account = new DocuSign.Integrations.Client.Account();
account.Email = username;
account.Password = password;
var loginResult = account.Login();
Template template = new Template();
template.TemplateId = templateId;
template.Login = account;
template.EmailSubject = emailSubject;
template.EmailBlurb = emailMessage;
var documents = template.GetDocuments();
TemplateRole tr = new TemplateRole();
var roles = new List<TemplateRole>();
//Handle Primary Client
roles.Add(new TemplateRole
{
roleName = "Primary Client",
name = primaryClientName,
email = primaryClientEmail,
tabs = new RoleTabs
{
textTabs = new RoleTextTab[] {
new RoleTextTab {
tabLabel = "FeeEffectiveDate",
value = effectiveDate
},
new RoleTextTab {
tabLabel = "FeePercentage",
value = fee
}
}
},
});
if (secondaryClientName.Trim().Length != 0)
{
roles.Add(new TemplateRole
{
roleName = "Secondary Client",
name = secondaryClientName,
email = secondaryClientEmail,
});
}
roles.Add(new TemplateRole
{
roleName = "President",
name = presidentName,
email = presidentEmail,
});
roles.Add(new TemplateRole
{
roleName = "Css",
name = cssName,
email = cssEmail,
});
template.TemplateRoles = roles.ToArray<TemplateRole>();
template.Status = "sent";
//The following code always return false
bool status = template.AddDocument(ips, "IPS.pdf", 1);
var result = template.Create();
In order to use the AddDocument function, an envelope must be in draft state (as you can also see in the remarks for this function in the source code). Therefore, in your case, you must first create a draft envelope (by changing the envelope status to "created"), then invoke the AddDocument function, and finally update the envelope status to "sent" to send the envelope.
For example:
.
.
.
template.Status = "created";
var result = template.Create();
bool status = template.AddDocument(ips, "IPS.pdf", 2);
template.Status = "sent";
result = template.UpdateStatus();
Note that the document index is the document ID, and is must be different from the IDs of the existing documents in your template. Otherwise, an existing document that has the same ID number, will be replaced by the new document.

Categories