'Graph API to know when email is sent
I am currently sending emails via Graph API using the following code:
var graphClient = GetAuthenticatedGraphClient();
var metadata = JsonSerializer.Deserialize<MyMetadata>(queueItem);
if (metadata is null) throw new InvalidOperationException("Could not convert metadata");
await graphClient.Users[metadata.MailboxUsername].Messages[metadata.OutlookPlugInIdentityGUID].Send().Request().PostAsync();
Whilst this works, I have no way of knowing when the email has actually sent. The code that I have considered to check is a while loop like this:
while (isSent == false)
{
var checkMessage = await graphClient.Users[metadata.MailboxUsername].Messages[metadata.OutlookPlugInIdentityGUID].Request().GetAsync();
if (checkMessage.IsDraft == false)
{
isSent = true;
}
else if (noOfAttempts > 50) { throw new Exception("some error message"); }
noOfAttempts += 1;
await Task.Delay(5000);
}
This is obviously very inefficient and runs the risk of causing Graph to throttle API calls which would potentially cause a performance bottleneck. Is there a cleaner and more efficient way of determining when an email has been successfully sent?
I need to know when the email has been sent so that I can trigger a separate process in sequence.
Thanks in advance!
Solution 1:[1]
You can send HTTP request and check the status code of the response.
Example:
var graphClient = GetAuthenticatedGraphClient();
var metadata = JsonSerializer.Deserialize<MyMetadata>(queueItem);
if (metadata is null) throw new InvalidOperationException("Could not convert metadata");
var requestUrl = graphClient.Users[metadata.MailboxUsername].Messages[metadata.OutlookPlugInIdentityGUID].Send().Request().RequestUrl;
// Create the request message and add the content.
var hrm = new HttpRequestMessage(HttpMethod.Post, requestUrl);
// Authenticate (add access token) our HttpRequestMessage
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);
// Send the request and get the response.
var response = await graphClient.HttpProvider.SendAsync(hrm);
if (response.IsSuccessStatusCode)
{
...
}
else
throw new ServiceException(
new Error
{
Code = response.StatusCode.ToString(),
Message = await response.Content.ReadAsStringAsync()
});
Resources:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | user2250152 |