2016-09-19 15 views
0

私は実行時に電子メールを送信するSendGridのpythonスクリプトの作成に取り組んでいます。私はサンプルスクリプトhereに従っていますが、これは私のカスタムSMTP APIヘッダーを生成するものです。実際にメールを送信するにはどうすればいいですか?ありがとう!SMTPヘッダーを使用してSendGrid電子メールを送信する方法?

マイコード:

#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 

答えて

0

ライブラリは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("[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) 

しかし、それは私が簡単に、必要に応じてプロバイダを切り替えることが許さので、個人的に、私はいつもSMTPを優先しています。

+0

こんにちは@masnun、私は公式のPythonライブラリを使用してみましたが、私は私のトランザクションテンプレートで動作する代替タグを取得する問題がありました。私のテンプレートでは、 ":name"というテキストがあり、jsonで代替タグを使用しようとしましたが、問題がありました。私のコードはここにあります:[リンク](http://pastebin.com/wF0UVHqK) –

関連する問題