How to add replyto with sendgrid in C# - c#

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;

Related

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.

Send a sendgrid legacy template

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.

SendGrid V3 api with C#. email not sending

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

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);

Confirmation Url comes up as a string in Hotmail

I have this in my Account Controller Register:
var token = WebSecurity.CreateUserAndAccount(
model.UserName,
model.Password,
new
{
model.Email
},
true);
var confirmationUrl = System.Web.HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
"/Account/ConfirmAccount/" + token;
dynamic email = new Email("RegisterConfirmation");
email.To = model.Email;
email.UserName = model.UserName;
email.ConfirmationUrl = confirmationUrl;
email.Send();
Usually i expect that to send out a link to emails and its doing so when sent to a GMail and Yahoo account, but when sent to aHotmail account the link is sent as a plain string which would require copy and past to navigate there.
Any ideas on what's causing this?
I would expect its something to do with hotmail.
If you want, you can instead flag the email as html (email.IsHtml= true I believe) and write it in html, which should work with everything.

Categories