如何用Mailgun使用python httplib2发送电子邮件附件
问题描述:
我正在使用httplib2和Mailgun API来发送电子邮件附件,这是我使用Google Drive下载的,电子邮件正在发送但没有附件..以下是我的代码..如何用Mailgun使用python httplib2发送电子邮件附件
DRIVE = discovery.build('drive', 'v3', http=http_auth)
request = DRIVE.files().export_media(fileId=file_id, mimeType='application/pdf')
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
logging.info("Download %d%%." % int(status.progress() * 100))
messages = {
"from": sender,
"to": recipient,
"subject": 'Attachment Mail from Mailgun',
"text": 'Testing',
"attachment": fh.getvalue()
}
url = URL
data = {
"from": messages['from'],
"to": messages['to'],
"subject": messages['subject'],
"text": messages['text'],
"attachment": messages['attachment']
}
pl = urllib.urlencode(data)
http = httplib2.Http()
http.add_credentials('api', API)
resp, content = http.request(
url, 'POST', pl,
headers={"Content-Type": "application/x-www-form-urlencoded"})
答
我们使用mailgun
API发送使用Appengine
和cloud storage
阅读电子邮件,同样的原则将适用于google drive
:
我会建议的第一件事就是寻找到StringIO。它允许您以比BytesIO更简单的方式模拟appengine沙箱内的文件,但都产生python称为支持.read()
的file objects
,所以这应该适用于两者。
将文件作为file like object
后,您只需将其正确传递给API即可。以下示例使用requests库,因为它使用文件进行POST很容易,并且与appengine兼容。
请注意,在这种情况下open(FILE_PATH_1, 'rb')
是file like object
,您只需要更换,以你的文件对象:
def send_complex_message():
return requests.post("https://api.mailgun.net/v2/DOMAIN/messages",
auth=("api", "key-SECRET"),
files={
"attachment[0]": ("FileName1.ext", open(FILE_PATH_1, 'rb')),
"attachment[1]": ("FileName2.ext", open(FILE_PATH_2, 'rb'))
},
data={"from": "FROM_EMAIL",
"to": [TO_EMAIL],
"subject": SUBJECT,
"html": HTML_CONTENT
})