Reputation: 13
I want to send an email at a specified time in Sendgrid. according to this document.and this question,I created a sample console application in VS2022 with c#
There is no problem sending Email. However, Email is still delivered to target even after canceling
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SendGrid;
using SendGrid.Helpers.Mail;
namespace sendmailtest
{
internal class Program
{
private static string batchId = "";
private static string apikey = "my sendgrid apikey";
static void Main(string[] args)
{
SendEmail().Wait();
Console.WriteLine("Cancel scheduled emails. yes or not?");
var result = Console.ReadLine();
if (result == "yes")
{ //Cancel scheduled sends while inputting "yes" in console
NotSendEmail().Wait();
}
}
static async Task SendEmail()
{
var client = new SendGridClient(apikey);
var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "mail/batch");
if (response.StatusCode == HttpStatusCode.Created)
{ // get batchID
JObject joResponse = JObject.Parse(response.Body.ReadAsStringAsync().Result);
batchId = (((Newtonsoft.Json.Linq.JValue)joResponse["batch_id"]).Value).ToString();
}
var dtNow = DateTime.Now;
//Automatically send emails 30 seconds after execution starts
var dtSend = dtNow.AddSeconds(30);
long sendAtUnixTime = new DateTimeOffset(dtSend).ToUnixTimeSeconds();
var msg = new SendGridMessage()
{
From = new EmailAddress("[email protected]", "sample"),
Subject = "scheduling sending mail test",
PlainTextContent = "and easy to do anywhere, even with C#",
HtmlContent = "<strong>and easy to do anywhere, even with C#</strong>",
BatchId = batchId,
SendAt = sendAtUnixTime
};
msg.AddTo(new EmailAddress("targetEmailAddress", "targetName"));
await client.SendEmailAsync(msg);
//Email sent successfully
}
static async Task NotSendEmail()
{
var client = new SendGridClient(apikey);
string data = "{\"batch_id\":\"" + batchId + "\",\"status\": \"cancel\"}";
await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "user/scheduled_sends", requestBody: data);
}
}
}
How can achieve this problem. Please provide the solutions for it. Thanks in advance.
Upvotes: 1
Views: 215
Reputation: 788
ToUnixTimeSeconds
is based on UTC. Your dtNow
is in local time. If you set it with DateTime.UtcNow
you've probably fixed the issue, assuming you're living in a country with a negative timezone (as such it's probably sending the email as soon as you create the call since the scheduled date is surpassed).
https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimeseconds?view=net-7.0
Going by the example of https://docs.sendgrid.com/for-developers/sending-email/stopping-a-scheduled-send your code seems fine otherwise.
Upvotes: 1