How to schedule an email using twilio sendgrid in django?

I'm currently building an app which contains email sending to multiple users which i'm able to do but i want to add a functionality which schedule's an email, for instance I'm using sent_at method as you can see below:-

extra_headers = {'X-SMTPAPI': json.dumps({'send_at': FinalScheduleTime})}

I've also tried SendAt but it's not working either.

This is an official blog by Twilio on Using Twilio SendGrid To Send Emails from Python Django Applications - https://www.twilio.com/blog/scheduled-emails-python-flask-twilio-sendgrid

Also here are, official docs

Here the FinalScheduleTime is of the datetime object. The sendgrip api accepts the UNIX timestamp according to the documentation. You can check it here

Hence to convert your datetime object into unix time stamp, you can use the time module of python.

scheduleTime = int(time.mktime(FinalScheduleTime.timetuple()))

Also, replace the message.extra_headers with message.send_at.

Hence, your final code will look like:

import json
import time
from sendgrid import SendGridAPIClient
from django.conf import settings

message = Mail(from_email=settings.EMAIL_FROM,
               to_emails=selectedphone,
               subject=subject,
               html_content=editor)


scheduleTime = int(time.mktime(FinalScheduleTime.timetuple()))
message.send_at = scheduleTime

sg = SendGridAPIClient(settings.EMAIL_API_CLIENT)
response = sg.send(message)
if response.status_code == 202:
     emailstatus = "Accepted"
elif .....
else.....
Back to Top