如何使用SMTP标头并发送SendGrid电子邮件?

时间:2016-09-19 00:26:24

标签: python email smtp sendgrid

我正在创建一个SendGrid python脚本,在执行时发送电子邮件。我按照示例脚本here,但所有这一切都生成我的自定义SMTP API标头。我如何实际发送电子邮件?谢谢!

我的代码:

#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

1 个答案:

答案 0 :(得分:1)

该库似乎用于生成SMTP API标头。您可能希望使用此库发送电子邮件 - 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("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)

但就个人而言,我一直更喜欢SMTP,因为它允许我根据需要轻松切换提供商。