Reputation: 1
I'm working on creating a SendGrid python script that sends emails when executed. I followed the example script here, but all this does is generate my custom SMTP API Header. How do I actually send the email? Thanks!
My code:
#sudo pip install smtpapi
import time, json
if __name__ == '__main__' and __package__ is None:
from os import sys, path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from smtpapi import SMTPAPIHeader
from smtpapi import SMTPAPIHeader
header = SMTPAPIHeader()
header.add_to('[email protected]')
# Substitutions
header.set_substitutions({'key': ['value1', 'value2']})
# Sections
header.set_sections({':name':'Michael', 'key2':'section2'})
# Filters
header.add_filter('templates', 'enable', 1)
header.add_filter('templates', 'template_id', 'a713d6a4-5c3e-4d4c-837f-ffe51b2a3cd2')
# Scheduling Parameters
header.set_send_at(int(time.time())) # must be a unix timestamp
parsed = json.loads(header.json_string())
print json.dumps(parsed, indent=4, sort_keys=True) #display the SMTP API header json
Upvotes: 0
Views: 1151
Reputation: 11916
That library seems to be for generating SMTP API headers. You would want to use this library for sending emails - https://github.com/sendgrid/sendgrid-python
import sendgrid
import os
from sendgrid.helpers.mail import *
sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("[email protected]")
subject = "Hello World from the SendGrid Python Library!"
to_email = Email("[email protected]")
content = Content("text/plain", "Hello, Email!")
mail = Mail(from_email, subject, to_email, content)
response = sg.client.mail.send.post(request_body=mail.get())
print(response.status_code)
print(response.body)
print(response.headers)
But personally, I have always preferred SMTP since it allowed me to easily switch providers as necessary.
Upvotes: 1