Just started working on email sending implementation using SendGridApiClient. Have this line that sends an email
dynamic response = await _sendGrid.client.mail.send.post(requestBody: mail.Get());
Response can provide StatusCode Accepted and nothing more. Was wondering how can I check was email delivered or stuck ?
The SendGrid API is asynchronous because the length of time it takes to process delivery of the email is non-trivial and dependent on factors like the receiving server.
The best way to keep an eye on events like delivered, bounced, etc in real-time is to implement the Event Webhook.
Take a look at this answer: Can my ASP.Net Code get confirmation from sendgrid that an email has been sent?
Related
The following Twilio code doesn't work. This is my webhook handler in an ASP.NET (Core) 6.0 app.
[AllowAnonymous]
[HttpPost]
[Route("webhook-url")]
public IActionResult PostTwilioMessageReceived([FromForm] TwilioMessageReceivedFormModel formModel)
{
// logging code etc.
var response = new Twilio.TwiML.MessagingResponse();
response.AddText($"You sent '{formModel.Body}' but our systems are dumb and can't process this yet.");
return new TwiMLResult(response);
}
There are no errors. I don't receive the message, and my delivery status webhook doesn't appear to be called.
The method above is called as I see it in my logs.
Note - There is no "to" address. I have adapted sample code from Twilio's documentation which also does nothing to either read the sender address or configure the response with a recipient or other correlation ID.
https://www.twilio.com/docs/whatsapp/tutorial/send-and-receive-media-messages-whatsapp-csharp-aspnet#generate-twiml-in-your-application
I've modified my logging to make doubly sure my webhook is being called. It is. And in Twilio's log there's no acknowledgement of the reply my webhook attempts to produce.
To be clear, the code above is using Twilio's libraries.
The TwiML output of your application would be:
<Response>You sent '...' but our systems are dumb and can't process this yet.</Response>
Unfortunately, that isn't valid TwiML, instead it should look like this:
<Response>
<Message>You sent '...' but our systems are dumb and can't process this yet.</Message>
</Response>
This will respond with a message to the sender. To do this, use the .Message method instead of .AddText:
response.Message($"You sent '{formModel.Body}' but our systems are dumb and can't process this yet.");
Everything else looks fine in your code AFAIK.
Aside: If all you need to do is to respond to the current sender with a single message, you can also respond with plain text and the text/plain content type.
Edit by OP
I also changed the return line to:
return this.TwiML(response);
Which was the advice of Twilio support. I didn't try it my original way, but assumed that if there was some kind of magic that's pre-addressing the response, or correlating it in some way, then it might be in using the helper function on the base controller. Thanks.
It's hard to say what caused this without seeing an error or message log. You should be able to see something in the "Monitor" in the console (more details here).
I've had similar issues in the past with Node.js and the problem was there that I forgot to set the content-type of the response to text/xml. But I'm not sure if this is required in your C# code.
I am working on an appointment confirmation system where I need to bind the SMS response 'Y' or 'N' to some meta data and send that meta data to my API via the Twilio webhook.
I am using.NET SDK from Twilio and trying to add attributes to the SMS message (MessageResource) which their documentation states:
Attributes:
STRING PII MTL: 30 DAYS
"The JSON string that stores application-specific data. If attributes have not been set, {} is returned."
link to docs: https://www.twilio.com/docs/chat/rest/message-resource#message-properties
which is more like metadata which is what I need but when I try finding any 'attributes' property in my C# code with their SDK I can't find it.
Here's my code:
var twilioMessage = MessageResource.Create(
body: msg,
from: _configuration["Twilio:FromPhoneNo"],
to: new PhoneNumber(phoneNumber),
attempt:1,
attributes: "{"id":"test"}" //this property doesn't work
);
var attributes = twilioMessage.attributes; //this doesn't work either
Any help will be highly appreciated.
Twilio developer evangelist here.
I'm afraid you are looking at the wrong documentation for sending SMS messages there. This documentation is for sending a chat (app to app) message. The documentation for sending an SMS is here.
Sadly, SMS messages do not have the ability to bind custom attributes to them. It is simply something that doesn't exist in the protocol.
You are sending an appointment confirmation and expecting a "Y" or "N" response. I am guessing you are trying to add the ID of the appointment in the case that you send confirmations for more than one appointment to the same phone number and you need to work out which appointment the response is about. There's a further issue here in that, as an end user, you cannot reply to a specific SMS messages. SMS is purely chronological.
There are 3 ways I can think of to work around this:
Only send one confirmation at a time. If you are still waiting for a response to a confirmation, don't send another one until you get that response. This might not work if users don't respond to confirmations.
Have the user include the ID of the appointment in the response. This is flaky because it relies on the users getting things right and you want to make things as simple as you can for them
When you need to send more than one confirmation at a time, use different Twilio numbers to send the confirmations. Then you can tie the confirmation response to the appointment by inspecting the Twilio number that the user sent the message to.
Number 3 is the most sound way of doing this. It shouldn't require you to have too many extra numbers, just as many as you might have concurrent appointment confirmations.
Let me know if this helps at all.
When i send a text to a customer using a messaging service id. The from number is null in the returned MessageResource. Code below.
Is the only way to determine the From by making an additional call out using the message sid? I need the from used for analytics and so I can use the same number to contact an account in case the customer uses multiple contact numbers.
return await MessageResource.CreateAsync
(
to: new PhoneNumber(toNumber),
messagingServiceSid: messengerSid,
body: message
);
Twilio developer evangelist here.
When you use a messaging service to send messages from various numbers then you cannot know at the time of message creation what the number used will be. When you make the request to send the message, Twilio queues that message up to be delivered by the messaging service. If you inspect the status of the message object you receive from the API call you show in your question you will see it is "accepted". At this point the messaging service won't have decided which number to use.
So, you can either make a second request to the API using the message SID that is returned to find out the From number. Or, you could set a StatusCallback URL which would receive a request once the message was sent, including the From number.
Let me know if that helps at all.
I am new to using Sendgrid emails using c# .Net library. Our requirements wants us to track the status of the email like Delivered/Went to Spam/Client opened/reported as spam etc., By looking at the documentations and answers from other users to my previous questions its my understanding that there is no direct way to track the status of the email (like result object).
It would be really helpful if someone can point me to some example/sample codes or documentation/implementation in C# for the following
1) Adding unique parameters while sending the email using send grid API. Can I use a Guid string as my argument
I am assuming what I am doing below is correct.
var myMessage = new SendGridMessage();
var identifiers = new Dictionary<String, String>();
identifiers["Email_ID"] = "Email_ID";
identifiers["Email_Key"] = "9ebccd0d-67c0-4c28-bbf3-83d5bb69f098";
myMessage.AddUniqueArgs(identifiers);
2) How to use event webhooks to get the status with the unique argument that I used above from the http_post so that I can associate an email to the status. Any sample code , documentation in c# or an overall idea of how this works will get me started on this.
Appreciate your time and answers.
Sending emails via SendGrid is easier from C# using the official library that SendGrid provides. From your code example, it looks like you may already be using this - good job.
The unique argument should work as long as its been stringified, and you're not trying to pass an object to myMessage.AddUniqueArgs.
The Event Webhook will send a JSON packet to any URL that you specify. If you have included unique arguments in an email that you send out via SendGrid then these are automatically added to each event response you get back from the webhook - you don't need to turn anything else on to get the arguments as well.
There is an example of this call and the resulting response in the SendGrid Documentation.
SendGrid has an Event Webhook which posts events related to your email
activity to a URL of your choice. This is an easily deployable
solution that allows for customers to easiy get up and running
processing (parse and save) their event webhooks.
This is docker-based solution which can be deployed on cloud services
like Heroku out of the box.
https://github.com/sendgrid/sendgrid-csharp/tree/main/examples/eventwebhook/consumer
This question relates to Twilio and the API for it (C#).
I do not have a website nor a web application, just a need to send SMS notifications to my own private mobile when something happens on a server (NOT a webserver). I have already, successfully, sent SMS to my mobile from a C# dll. I want to check the status of the message. All the references imply website/web application use cases, and getting the status using a URL.
How do I do this in C#? Is there an example of the suggestion made here? No PHP or other web servery technology.
The solution I found, was ridiculously simple. The suggestion (made here) was to hang on to the message id. I discovered the GetSMSMessage method on TwilioRestClient. So querying message status some time after sending will give you the updated status.
By the way, the one thing you'll want to watch out for is that if you query the API too soon, you might get a status of "queued" or "sending" rather than "sent" or "failed", so be sure that your logic is set up to handle these other possible responses.
Also good to keep in mind that if you try to send more than 1 message per-second via a Twilio phone number, Twilio will queue the excess messages and release them at a rate of 1 message per-second per-number. This comes into play because if you have a burst where you send 10 messages in 1 second, but then you go to retrieve the status of the messages after 5 seconds half of the messages will be "sent" and half will be "queued".
If you dont have a callback url. Just call the method
TwilioClient.Init(accountSid, authToken);
var message = MessageResource.Create(
body: "Join Earth's mightiest heroes. Like Kevin Bacon.",
from: new Twilio.Types.PhoneNumber(fromNumber),
to: new Twilio.Types.PhoneNumber(toNumber)
);
Console.WriteLine(message.Sid);
//Get the status from twilio
TwilioClient.Init(accountSid, authToken);
var verificationCheck = MessageResource.Fetch(message.Sid);
Console.WriteLine(verificationCheck.Status);
where Sid is the id you get back from Twilio.