Search code examples
pythonpython-2.7sendgridemail

schedule email with sendgrid python


I am using python module of sendgrid (https://github.com/sendgrid/sendgrid-python) to send transactional emails. I need help with the syntax to send the email at a scheduled time. The general sendgrid documentation asks to modify json as "{ “send_at”: 1409348513 }". I believe this json is not directly accessible in sendgrid-python. I need syntax for doing equivalent thing with the python library.

My current code is equivalent to the one copied below. It would be great if some one can suggest how to modify this code to schedule it at a particular time e.g. datetime.dateime.now() + datetime.timedelta(days=1)

import sendgrid    
from sendgrid.helpers.mail import Email, Content, Substitution, Mail
import urllib2 as urllib

def send_email_custom():    
    sg = sendgrid.SendGridAPIClient(apikey=myApiKey)        
    from_email = Email(sendEmail)
    to_email = Email(custEmail)
    reply_to_email = Email(receiveEmail)
    content = Content("text/html", "Introduction")
    mail = Mail(from_email, subject="Hi!", to_email=to_email, content=content)
    mail.personalizations[0].add_substitution(Substitution("_firstName_", firstName))
    mail.set_template_id(templateId)
    try:
        response = sg.client.mail.send.post(request_body=mail.get())
    except urllib.HTTPError as e:
        print(e.read())
        return False
    if response.status_code >=200 and response.status_code < 300:
        return True
    else:
        return False

Solution

  • send_at is a component of the personalizations Object, so you can define it at that level, allowing you to set distinct sending times for each recipient/personalization set.

    If you don't need that, you can also set it at the top mail level.