簡體   English   中英

如何在Mailgun中使用python httplib2發送電子郵件附件

[英]How to send email attachments using python httplib2 with Mailgun

我正在使用帶有Mailgun API的httplib2發送電子郵件附件,該附件是我使用Google雲端硬盤下載的,正在發送但沒有附件..以下是我的代碼。

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 objectfile like object ,只需將其正確傳遞給API。 以下示例使用了請求庫,因為它使發布文件變得非常容易並且與appengine兼容。

請注意,在這種情況下, open(FILE_PATH_1, 'rb')是一個file like objectfile 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
          })

def send_mailgun(收件人,主題,html,文件,文件名,cc,密件抄送):

MAILGUN_URL =' https ://api.mailgun.net/v3/DOMAIN/messages'MAILGUN_KEY ='key-secret'

數據= {“主題”:主題,“來自”:“ FROM_EMAIL”,“至”:至,“ html”:html}

如果cc!=“”:data [“ cc”] = cc

如果密件抄送!=“”:data [“ bcc”] =密件抄送

如果file_name和file_name!=“”:resp = requests.post(MAILGUN_URL,auth =(“ api”,MAILGUN_KEY),files = [(“ attachment”,(file_name,file))],data = data)否則:resp = requests.post(MAILGUN_URL,auth =(“ api”,MAILGUN_KEY),data = data)

不過,這已經很晚了……我很久以前解決了這個問題。

import io
import base64
from google.appengine.api import urlfetch
from libs.poster.encode import multipart_encode, MultipartParam

from oauth2client.appengine import AppAssertionCredentials
from googleapiclient.http import MediaIoBaseDownload
from apiclient.discovery import build
from httplib2 import Http

request = drive.files().export_media(fileId=spreadsheet_id, mimeType='application/pdf')

        fh = io.BytesIO()
        downloader = MediaIoBaseDownload(fh, request)

        done = False
        while done is False:
            status, done = downloader.next_chunk()

        message = {
            'from': 'noreply',
            'to': 'recipient',
            'subject': mail_subject,
            'text': text,
            'filename': filename,
            'attachment': fh.getvalue()
        }

        # send email using mailgun
        resp = send_attachment_email(message)


# Compose an email with an attachment
def send_attachment_email(messages):

url = 'mailgun_api_url'
api = 'api-key'

load = {
    "from": messages['from'],
    "to": messages['to'],
    "subject": messages['subject'],
    "text": messages['text'],
    "attachment": MultipartParam(
        "attachment",
        filename=messages['filename'],
        filetype='application/pdf',
        value=messages['attachment'])
}

payload, hd = multipart_encode(load)

hd['Authorization'] = 'Basic %s' % (base64.b64encode(api),)

resp = urlfetch.fetch(url=url, payload="".join(payload), method='POST',
                      headers=hd, validate_certificate=True)
logging.info(resp.status_code)
logging.info(resp.content)

return resp.status_code

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM