I am using SendGrid, and I want to add one or more category to the email, but the added category hadn't been sent!
This is the code:
internal class Example
{
private static void Main()
{
Execute().Wait();
}
static async Task Execute()
{
//FYI, the following three variables are not real
var apiKey = "SG.XXX";
var fromEmail = "";
var toEmail = "";
var client = new SendGridClient(apiKey);
var from = new EmailAddress(fromEmail);
var subject = "Sending with SendGrid is Fun";
var to = new EmailAddress(toEmail);
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);
msg.AddHeader("category", "cat1"); //This line does nothing!
var response = await client.SendEmailAsync(msg);
}
}
Thanks Kami, I tried your answer and it worked properly.
I replaced this line msg.AddHeader("category", "cat1"); with msg.AddCategory("cat1");
Related
I am trying to send the same automatic email to multiple email addresses but I can't get it to work.
[HttpGet("largeorderemail")]
public IActionResult LargeOrderEmail()
{
try
{
//var bodyString = $"<h3>{msg}</h3><br/><p> Visit the site <a href='{Startup.appSettings.AllowOrigin}/lidarweb'> LiDAR GIS portal.</a></p>";
var bodyString = $"<h3>email body</h3>" +
<br/>" +
var emailService = new Email { To = "info#tel.net" };
var response = emailService.ExecuteLargeOrder(bodyString);
return Ok();
}
catch (Exception e)
{
Log.Error(e);
return NotFound();
}
}
public async Task<Response> ExecuteLargeOrder(string bodyString)
{
var fromAddr = new EmailAddress(from, "Info");
subject = "large order";
var toAddr = new EmailAddress(to, "User");
plainTextContent = "";
htmlContent = bodyString;
var msg = MailHelper.CreateSingleEmail(fromAddr, toAddr, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
return response;
}
When I send an email to a single address, it works. Like so: var emailService = new Email { To = "info#tel.net" };
but when I try something like this, it doesn't send the email var emailService = new Email { To = "info#tel.net, info#gmail.com" };
I also tried separating the address like so var emailService = new Email { To = "info#tel.net; info#gmail.com" }; but this also doesn't work.
Any suggestions?
Instead of putting Email addresses, try doing this way. Keep all your Email address in Array and try looping through the Array so that you can achieve your goal.
I am having a problem retrieving an HTTP response code from SendGrid, and then updating a label based on that response. Since the SendGrid call uses an async method I am not able to get return a response.statuscode;
this is my code:
protected void BtnSend_Click(object sender, EventArgs e)
{
lblmsg.InnerText = SendMail(txtEmailId.Text.ToString(),
txtMessage.Text.ToString()); //------------
}
private String SendMail(String EmailId, String Message)
{
var status="";
Execute(EmailId, Message).Wait();
return status;
}
async Task Execute(String EmailId, String Message)
{
var apiKey = "abcdefghijklmnopqrstuvwxyz1234567890";
var client = new SendGridClient(apiKey);
var from = new EmailAddress("myemail#gmail.com", "Sender");
var subject = "Testing Email";
var to = new EmailAddress(EmailId, "Reciever");
var plainTextContent = "You have recieved this message from me";
var htmlContent = Message + "<br><i>-Message sent by me</i>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
var status = response.StatusCode;
}
Your method does not allow a return value, since you declared it as async Task. That means it's an async method that returns nothing (it just a returns a Task so the caller knows when it's done, but no actual value).
If you want to return something from an async method, you need to use a Task<T> return type, where T is the type of value you want to return.
So in this case, it should be:
async Task<HttpStatusCode> Execute(String EmailId, String Message)
Then you can return response.StatusCode
Here's some additional reading that might help you understand async code better:
Asynchronous programming
The Task asynchronous programming model in C#
Async in depth
To return a value from an async method it must be awaited. See the example method call below:
private async Task<System.Net.HttpStatusCode> Execute(String EmailId, String Message)
{
var apiKey = "abcdefghijklmnopqrstuvwxyz1234567890";
var client = new SendGridClient(apiKey);
var from = new EmailAddress("myemail#gmail.com", "Sender");
var subject = "Testing Email";
var to = new EmailAddress(EmailId, "Reciever");
var plainTextContent = "You have recieved this message from me";
var htmlContent = Message + "<br><i>-Message sent by me</i>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg).ConfigureAwait(false);
return response.StatusCode;
}
private async Task GetStatusCodeExample(String EmailId, String Message)
{
var statusCode = await Execute(EmailId, Message);
}
EDIT:
update your code to use the following along with the above updated Execute method:
protected void BtnSend_Click(object sender, EventArgs e)
{
lblmsg.InnerText = SendMail(txtEmailId.Text.ToString(),
txtMessage.Text.ToString()); //------------
private String SendMail(String EmailId, String Message)
{
var task = Execute(EmailId, Message);
task.Wait();
return ((int)task.Result).ToString();
}
I want to send text, title of username into an email that I have but how do I add these options so I can call them over to the html file a bit like this here.
MailDefinition oMailDefinition = new MailDefinition();
oMailDefinition.BodyFileName = "~/img/emailskabelon/NewPassword.html";
oMailDefinition.From = Mail;
Dictionary<string, string> oReplacements = new Dictionary<string, string>();
oReplacements.Add("<<name>>", name);
oReplacements.Add("<<password>>", password);
I would therefore like to add some of the values that I would like to have in my html file.
It might be that I should send text, username and other things to the html file and I would like that option.
public async static void Sendmail(string email, string name, string Title, string htmlContent)
{
var api = AzureName;
var client = new SendGridClient(api);
var from = new EmailAddress(Mail, nameFrom);
var to = new EmailAddress(email, name);
var plainTextContent = Regex.Replace(htmlContent, "<[^>]*>", "");
var msg = MailHelper.CreateSingleEmail(from, to, Title, plainTextContent, htmlContent);
var response = client.SendEmailAsync(msg);
await Task.Delay(4255);
}
Situation: When a user registers for a bot (by entering a message to the bot, I store the information of that user in a database:
- UserId
- UserName,
- ServiceURL
At some point in time I want to have my bot broadcast a message to all the users in that table.
foreach (var bUsers in users)
{
MicrosoftAppCredentials.TrustServiceUrl(bUsers.ServiceUrl);
MicrosoftAppCredentials creds = new MicrosoftAppCredentials("<<appid>>", "<<secret>>");
var connector = new ConnectorClient(new Uri(bUsers.ServiceUrl), creds);
var conversationId = await connector.Conversations.CreateDirectConversationAsync(new ChannelAccount(), new ChannelAccount(bUsers.UserId, bUsers.UserName));
message = Activity.CreateMessageActivity();
message.From = botAccount;
message.Recipient = userAccount;
message.Conversation = new ConversationAccount(id: conversationId.Id);
message.Text = "Hello from " + context.Activity.From.Name;
message.Locale = "en-Us";
var reply = await connector.Conversations.SendToConversationAsync((Activity) message);
}
With this code, I get a message saying:
Invalid conversation ID in teamsChannelId
I don't understand this message, and is it even possible to do what I want?
I was doing almost the same thing as you do but it stopped working suddenly. I could see the same error message.
But in my case it was just wrong and maybe it's strange it worked in the first place. Because I used client.UserId which was set to activity.Conversation.Id. If I changed the code to use it as conversationId it works.
Here is my code which is working right now and old pieces are commented out:
public static async Task SendMessageToClient(ServerClient client, string messageText)
{
var connector = new ConnectorClient(new Uri(client.BotServiceUrl), new MicrosoftAppCredentials());
var userAccount = new ChannelAccount(name: client.UserName, id: client.UserId);
var botAccount = new ChannelAccount(name: client.BotName, id: client.BotId);
// this worked before but not anymore
//var conversationId = await connector.Conversations
// .CreateDirectConversationAsync(botAccount, userAccount).Id;
// because client.UserId was set in a MessageController to activity.Conversation.Id we can use this
var conversationId = client.UserId;
var message = Activity.CreateMessageActivity();
message.From = botAccount;
message.Recipient = userAccount;
message.Conversation = new ConversationAccount(false, conversationId);
message.Locale = "en-Us";
if (client.ReplaceFrom != null && client.ReplaceTo != null)
{
messageText = messageText.Replace(client.ReplaceFrom, client.ReplaceTo);
}
message.Text = messageText;
await connector.Conversations.SendToConversationAsync((Activity) message);
}
I am using SendGrid mailhelper (as part of C# SDK) to send email. I need to send to multiple users, and hence I am using Personalization.
I get an error : Bad Request
This is my code:
static async Task Execute(string sub, string body, List<Recipient> recipients)
{
string apiKey = Environment.GetEnvironmentVariable("SendGrid_ApiKey", EnvironmentVariableTarget.User);
dynamic sg = new SendGridAPIClient(apiKey);
SendGrid.Helpers.Mail.Email from = new SendGrid.Helpers.Mail.Email("test1#gmail.com");
string subject = sub;
Personalization personalization = new Personalization();
SendGrid.Helpers.Mail.Email emails = new SendGrid.Helpers.Mail.Email();
var i = 0;
foreach (var recp in recipients)
{
emails.Address = recp.Email;
emails.Name = recp.FirstName + " " + recp.LastName;
personalization.AddTo(emails);
i++;
}
SendGrid.Helpers.Mail.Email to = new SendGrid.Helpers.Mail.Email("test1#gmail.com");
Content content = new Content("text/plain", body);
Mail mail = new Mail(from, subject, to, content);
mail.AddPersonalization(personalization);
dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());
}
I appreciate if someone could advise me what am I doing incorrect.
Sendgrid API responds with bad request when there are more than 1 email address that is the same in the Personalization object. Make sure all the emails are unique