I am using C#, 4.7.1 FW, and the SendGrid nuget.
I have been in contact with SG support and so far have not yet been directed to or figured out how to send a template. I have tried to use the native MailMessage, and also the SendGridMessage.
I have my template id specified and I keep running into problems where the email fails and I am told "Substitutions may not be used with dynamic templating"
Here is the latest snippet I am bashing my head against a brick wall over:
var apiKey = "snip";
var client = new SendGridClient(apiKey);
var from = new EmailAddress("from#domain.com", "display name");
var subject = "Sending an email template";
var to = new EmailAddress("me#domain.com", "To Name");
var plainTextContent = "";
var htmlContent = ""; // I read htmlContent needs to be blank?
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
Personalization p = new Personalization
{
Substitutions = new Dictionary<string, string>()
};
p.Substitutions.Add("[eventname]", "test event"); // my template has 3 subs, this is one of them
p.Tos = new List<EmailAddress>();
p.Tos.Add(to);
msg.Personalizations.Add(p);
msg.SetTemplateId("snip");
var response = await client.SendEmailAsync(msg);
var stringResponse = response.Body.ReadAsStringAsync();
Response:
{"errors":[{"message":"Substitutions may not be used with dynamic templating","field":"personalizations.1.substitutions","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.substitutions"}]}
I am this close to just reverting all of this to building my own HTML template and storing that in a database, pulling it and replacing the placeholders like [eventname] with values. This shouldn't be this hard.
Related
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 am using sendgrid with a .NET Core site I built. It has a contact form on it so a client can fill out the form and it is sent to my email address. I am using the Sendgrid nuget package to generate and send the email. The issue is that when I get the email I dont want to replyto myself and when I make the replyto equal the email address entered - sendgrid wont send the email because that email isnt entered into the Single Sender Verification. There must be a way to configure things so in my email when I click reply it will go to the person who sent the email. Right?
string key = _iConfig.GetSection("Email").GetSection("SendGridKey").Value;
var client = new SendGridClient(key);
var subject = "Form submission";
var fromemail = _iConfig.GetSection("Email").GetSection("From").Value;
var from = new EmailAddress(fromemail, model.Name);
var toemail = _iConfig.GetSection("Email").GetSection("To").Value;
var to = new EmailAddress(toemail, "Admin");
var htmlContent = "<strong>From: " + model.Name + "<br>Email: " + model.Email + "<br>Message: " + model.Message;
var msg = MailHelper.CreateSingleEmail(from, to, subject, model.Message, htmlContent);
var response = await client.SendEmailAsync(msg);
return response.IsSuccessStatusCode;
Twilio SendGrid developer evangelist here.
To set the reply-to address in C# you need the setReplyTo method, like this:
var msg = MailHelper.CreateSingleEmail(from, to, subject, model.Message, htmlContent);
// Add the reply-to email address here.
var replyTo = new EmailAddress(model.Email, model.Name);
msg.setReplyTo(replyTo);
var response = await client.SendEmailAsync(msg);
return response.IsSuccessStatusCode;
is there something wrong with this code? I already put my email in my code but I don't get any email.
I have a hint that is it not working because I am using API key ID instead of API key because I can't see my API key because of its only show just once. if is that the reason why is this code not working. Is there no way to view your API key again?
public string SendEmailMain()
{
SendEmail().Wait();
}
static async Task SendEmail()
{
common com = new common();
var apiKey = com.sendGridAPI;
var client = new SendGridClient(apiKey);
var from = new EmailAddress("testmail#gmail.com", "test user");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("testemai#gmail.com", "teset user");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
}
the code is working pretty well. The thing is i'm using the API key ID because instead of the API key that generated by sendgrid.
Please refer to this thread for more info
The code I'm using looks just like so many examples
But "Web" is an undefined type.
Even ReSharper can't tell me where to find it.
Do I need another reference with a using or has 'Web' been renamed in v 9.9.0?
var myMessage = new SendGridMessage();
myMessage.AddTo(message.Destination);
myMessage.From = new EmailAddress("somebody#xyz.com", "Fff
Lll");
myMessage.Subject = message.Subject;
myMessage.PlainTextContent = message.Body;
myMessage.HtmlContent = message.Body;
var credentials = new NetworkCredential(
ConfigurationManager.AppSettings["mailAccount"],
ConfigurationManager.AppSettings["mailPassword"]
);
// Create a Web transport for sending email.
var transportWeb = new Web(credentials);
You are following the V2 api documentation which is now obsolete . You can use the V3 api SDK instead . The sample code is like below
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test#example.com", "Example User");
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress("test#example.com", "Example User");
var plainTextContent = "and easy to do anywhere, even with C#";
var htmlContent = "<strong>and easy to do anywhere, even with C#</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
you need to refer the below namespaces
using SendGrid;
using SendGrid.Helpers.Mail;
you can also send the mail without the mail helper class . Follow the below link for more usage and demo
https://github.com/sendgrid/sendgrid-csharp/blob/master/USE_CASES.md
Nuget link :
https://www.nuget.org/packages/Sendgrid/
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);