Home > Blockchain >  How to schedule an email using twilio sendgrid in django?
How to schedule an email using twilio sendgrid in django?

Time:09-13

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related