简体   繁体   English

如何在Mailgun中使用python httplib2发送电子邮件附件

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

I am using httplib2 with the Mailgun API to send an email attachment which I downloaded using the Google Drive, the email is sending but without attachments.. below is my code.. 我正在使用带有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"})

We use the mailgun API to send emails using Appengine and reading from cloud storage , the same principles will apply to google drive : 我们使用mailgun API发送邮件使用Appengine和读取cloud storage ,同样的原则将适用于google drive

The first thing I would suggest is looking into StringIO . 我建议的第一件事是调查StringIO It allows you to simulate working with files inside the appengine sandbox in an easier way than BytesIO, but both produce what python calls file objects that support .read() so this should work with both. 与BytesIO相比,它可以让您以更简单的方式模拟在appengine沙箱中使用文件的方式,但是两者都会产生python调用支持.read() file objects ,因此这两种方式都应适用。

Once you have your file as a file like object , you just need to pass it correctly to the API. 将文件作为file like objectfile like object ,只需将其正确传递给API。 The following example uses the requests library as it makes it really easy to POST with files and is compatible with appengine. 以下示例使用了请求库,因为它使发布文件变得非常容易并且与appengine兼容。

Notice that in this case open(FILE_PATH_1, 'rb') is a file like object , you just need to replace that with your file object: 请注意,在这种情况下, 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(to,subject,html,file,file_name,cc,bcc ): def send_mailgun(收件人,主题,html,文件,文件名,cc,密件抄送):

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

data = { "subject": subject, "from": "FROM_EMAIL", "to": to, "html": html } 数据= {“主题”:主题,“来自”:“ FROM_EMAIL”,“至”:至,“ html”:html}

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

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

if file_name and file_name!="": resp = requests.post( MAILGUN_URL, auth=("api", MAILGUN_KEY), files=[("attachment", (file_name,file))], data=data) else: resp = requests.post( MAILGUN_URL, auth=("api", MAILGUN_KEY), data=data) 如果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)

This is late though... I solved this long time ago.. below was what I did: 不过,这已经很晚了……我很久以前解决了这个问题。

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