How to use SMTP header and send SendGrid email?
<p>I'm working on creating a SendGrid python script that sends emails when executed. I followed the example script <a href="https://github.com/sendgrid/smtpapi-python/blob/master/examples/example.py" rel="nofollow">here</a>, but all this does is generate my custom SMTP API Header. How do I actually send the email? Thanks!</p>

<p>My code:</p>

<pre><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('test@email.com')

# 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
</code></pre>

<p>That library seems to be for generating SMTP API headers. You would want to use this library for sending emails - <a href="https://github.com/sendgrid/sendgrid-python" rel="nofollow">https://github.com/sendgrid/sendgrid-python</a></p>

<pre><code>import sendgrid
import os
from sendgrid.helpers.mail import *

sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
from_email = Email("test@example.com")
subject = "Hello World from the SendGrid Python Library!"
to_email = Email("test@example.com")
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)
</code></pre>

<p>But personally, I have always preferred SMTP since it allowed me to easily switch providers as necessary.</p>

python email smtp sendgrid