使用Python通过Mailgun发送附带文件的邮件
使用Python通过Mailgun发送附带文件的邮件
我想使用requests.post和Mailgun API发送带有附件的电子邮件。
在他们的文档中,他们提醒说在发送附件时必须使用 multipart/form-data编码,我正在尝试这样做:
import requests MAILGUN_URL = 'https://api.mailgun.net/v3/sandbox4f...' MAILGUN_KEY = 'key-f16f497...' def mailgun(file_url): """使用MailGun发送电子邮件""" f = open(file_url, 'rb') r = requests.post( MAILGUN_URL, auth=("api", MAILGUN_KEY), data={ "subject": "我的主题", "from": "my_email@gmail.com", "to": "to_you@gmail.com", "text": "文本", "html": "HTML", "attachment": f }, headers={'Content-type': 'multipart/form-data;'}, ) f.close() return r mailgun("/tmp/my-file.xlsx")
我已经定义了标题,以确保内容类型为multipart/form-data,但当我运行代码时,我得到一个400状态,原因是错误的请求。
问题出在哪里?我需要确保我使用的是multipart/form-data,并且我是否正确地使用了attachment参数。
问题的原因是没有正确使用Mailgun的Python库来发送带有附件的邮件。解决方法是使用关键字参数files
来指定附件,并在POST请求中添加正确的数据。
下面是一个使用Mailgun文档中提供的示例代码的例子:
def send_complex_message(): return requests.post( "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages", auth=("api", "YOUR_API_KEY"), files=[("attachment", open("files/test.jpg")), ("attachment", open("files/test.txt"))], data={"from": "Excited User <YOU_DOMAIN_NAME>", "to": "foo.com", "cc": "baz.com", "bcc": "bar.com", "subject": "Hello", "text": "Testing some Mailgun awesomness!", "html": "<html>HTML version of the body</html>"})
所以需要修改POST请求为:
r = requests.post( MAILGUN_URL, auth=("api", MAILGUN_KEY), files = [("attachment", f)], data={ "subject": "My subject", "from": "my_email.com", "to": "to_you.com", "text": "The text", "html": "The<br>html" }, )
这样就可以成功发送带有附件的邮件了。
注意,这个方法只有在不指定headers
参数时才有效。似乎这个参数会自动处理。