使用 API 发送电子邮件时将文件附加到电子邮件

问题描述 投票:0回答:1

我正在使用此 API 通过亚马逊 lambda 发送电子邮件。

https://documentation.mailgun.com/en/latest/api-sending.html

这按预期工作,但我无法发送附件。

def handler(event,context):

  import requests, os

  tempurl = event['url']
  myReq = requests.get(tempurl)
  email = event.get('email', '[email protected]')
  title = event.get('title', 'emailThis')
  params = {"from": "Excited User <[email protected]>", "to": email, "subject": title, "html": myReq.text}

  requests.post(os.environ['myUrl'] + '/messages', auth=("api", os.environ['myAuth'] ), data=params)

如何附加 lambda 本地环境中的文件? 我正在使用此代码创建一个文件...

import tempfile
temp = tempfile.TemporaryFile()
temp.write(b'Hello world!')
temp.close()

上面提到的发布请求中需要附加“临时”文件。

aws-lambda python-requests mailgun
1个回答
0
投票

要在 AWS Lambda 函数中使用 Mailgun Email API 发送带有附件的电子邮件,您需要修改现有代码以将附件包含在 HTTP

POST
请求中。在 Python 中,您可以使用
requests
通过在
files
调用中包含
requests.post
参数来完成此任务。

def handler(event, context):
    import requests, os
    import tempfile

    # Fetch the email template
    tempurl = event['url']
    myReq = requests.get(tempurl)

    # Create a temporary file
    temp = tempfile.NamedTemporaryFile(delete=False)
    temp.write(b'Hello world!')
    temp.seek(0)

    # Email configuration
    email = event.get('email', '[email protected]')
    title = event.get('title', 'emailThat')
    params = {"from": "Excited User <[email protected]>", "to": email, "subject": title, "html": myReq.text}

    # Attach the temporary file
    with open(temp.name, 'rb') as attachment:
        files = {'attachment': ('tempfile.txt', attachment)}
        requests.post(
            os.environ['myUrl'] + '/messages',
            auth=("api", os.environ['myAuth']),
            data=params,
            files=files
        )

    # Close and remove the temporary file
    temp.close()
    os.unlink(temp.name)

临时文件是使用

tempfile.NamedTemporaryFile(delete=False)
创建的,以便我们稍后可以使用它的名称。
files
字典指定附件名称 (
'tempfile.txt'
),因为它将出现在电子邮件和文件对象本身 (
attachment
) 中。

POST
请求之后,临时文件将被关闭并从 Lambda 环境中删除,以防止任何资源泄漏。

requests.post(
    os.environ['myUrl'] + '/messages',
    auth=("api", os.environ['myAuth']),
    data=params,
    files=files
)

用于发送消息的特定 API 端点通常是

/messages
,这就是
requests.post
URL 中
os.environ['myUrl'] + '/messages'
调用的目标。 auth 参数用于使用 Mailgun 电子邮件 API 密钥进行身份验证,该密钥存储在环境变量
os.environ['myAuth']
中。

data=params
包括基本的电子邮件详细信息,例如发件人、收件人、主题和 HTML 内容。最后,
files=files
参数是将附件添加到电子邮件的位置。

© www.soinside.com 2019 - 2024. All rights reserved.