Iron Man
Iron Man

Reputation: 145

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:-

settings.py

EMAIL_FROM = 'EMAIL'
EMAIL_API_CLIENT ='XXXXXXXX'

views.py

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

message = Mail(from_email=settings.EMAIL_FROM,
               to_emails=selectedphone,
               subject=subject,
               html_content=editor)
message.extra_headers = {'X-SMTPAPI': json.dumps({'send_at': 
                         FinalScheduleTime})}
sg = SendGridAPIClient(settings.EMAIL_API_CLIENT)
response = sg.send(message)
if response.status_code == 202:
     emailstatus = "Accepted"
elif .....
else.....

I've also tried message.extra_headers = {'SendAt':FinalScheduleTime} but it's not working either.

Upvotes: 0

Views: 352

Answers (2)

Jarvis
Jarvis

Reputation: 68

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.....

Upvotes: 1

Pradumnasaraf
Pradumnasaraf

Reputation: 7

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

Upvotes: 0

Related Questions