プログラムを実行した様子
$ ./test_mail.py
*** 開始 ***
<Response [202]>
*** 終了 ***
test_mail.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
# test_mail.py
#
# --------------------------------------------------------------------
import sys
from sendgrid_v3 import sendgrid_v3_proc
# --------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
content='ハロー ワールド\n'
content += 'テスト\n'
content += '本日は晴天なり。\n'
content += '今日は暑い。\n'
content += "Hello World\n"
content += "Good Afternoon\n"
content += "以上。\n"
mail_from = 'test_aa@example.com'
mail_to = 'test_bb@gmail.com'
subject = 'From SendGrid Aug/24/2017 PM 16:56'
#
sendgrid_v3_proc(mail_from,mail_to,subject,content)
#
sys.stderr.write("*** 終了 ***\n")
# --------------------------------------------------------------------
次のプログラムの api_key は変更して下さい。
sendgrid_v3.py
# -*- coding: utf-8 -*-
#
# sendgrid.py
#
# --------------------------------------------------------------------
import requests
import sys
import json
# --------------------------------------------------------------------
def sendgrid_v3_proc(mail_from,mail_to,subject,content):
#
args = {
"personalizations": [{"to": [{"email": mail_to}]}],
"from": {"email": mail_from},
"subject": subject,
"content": [{"type": "text/plain", "value": content}]
}
json_str = json.dumps(args)
api_key = 'SG.2ZQgUBNcQeiBbLspta6sQw.-UebHZZApnZNesJfzAMf1F9F8WjUESpB1rzBp-FFCN-Y'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + api_key
}
url='https://api.sendgrid.com/v3/mail/send'
try:
rr = requests.post(url,json_str,headers=headers)
print(rr)
except Exception as ee:
sys.stderr.write('*** error *** requests.post ***\n')
sys.stderr.write(str(ee) + '\n')
#
# --------------------------------------------------------------------