如何使用pythonhttplib2和Mailgun发送电子邮件附件

2024-05-29 10:50:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用httplib2和Mailgun API来发送电子邮件附件,我使用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"})

Tags: totextfromapihttp附件attachment电子邮件
3条回答

def send_mailgun(收件人、主题、html、文件、文件名、抄送、密件抄送):

MAILGUN_URL='https://api.mailgun.net/v3/DOMAIN/messages'MAILGUN\ukey='KEY-secret'

data={“subject”:主题,“from”:“from_EMAIL”,“to”:to,“html”:html}

如果抄送!=“”:数据[“cc”]=cc

如果密件抄送!=“”:数据[“密件抄送”]=密件抄送

如果文件名和文件名!比例=“”请求.post(MAILGUN_URL,auth=(“api”,MAILGUN_KEY),files=[(“attachment”,(file_name,file))],data=data)其他:resp=请求.post(MAILGUN_URL,auth=(“api”,MAILGUN_密钥),data=data)

我们使用mailgunAPI发送电子邮件,使用Appengine并从cloud storage读取,相同的原则将适用于google drive

我建议的第一件事是研究StringIO。它允许您以比BytesIO更简单的方式模拟在appengine沙盒中处理文件,但是两者都产生python所称的支持.read()file objects,因此这两种方法都可以使用。在

一旦您将文件作为file like object,您只需要将其正确地传递给API。下面的例子使用了requests库,因为它使发布文件变得非常容易,并且与appengine兼容。在

请注意,在本例中,open(FILE_PATH_1, 'rb')file like object,您只需将其替换为file对象:

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
          })

不过现在已经晚了。。。我早就解决了。。以下是我所做的:

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

相关问题 更多 >

    热门问题