我无法弄清楚如何使用请求库从 Python 应用程序使用 Mailgun api 发送多条内联消息。目前我有(使用 jinja2 作为模板和 flask 作为网络框架,托管在 Heroku 上):
def EmailFunction(UserEmail):
Sender = 'testing@test.co.uk'
Subject = 'Hello World'
Text = ''
name = re.sub('@.*','',UserEmail)
html = render_template('GenericEmail.html', name=name)
images = []
imageloc = os.path.join(dirname, 'static')
images.append(open(os.path.join(imageloc,'img1.jpg')))
images.append(open(os.path.join(imageloc,'img2.jpg')))
send_mail(UserEmail,Sender,Subject,Text,html,images)
return html
def send_mail(to_address, from_address, subject, plaintext, html, images):
r = requests.\
post("https://api.mailgun.net/v2/%s/messages" % app.config['MAILGUN_DOMAIN'],
auth=("api", app.config['MAILGUN_KEY']),
data={
"from": from_address,
"to": to_address,
"subject": subject,
"text": plaintext,
"html": html,
"inline": images
}
)
return r
因此电子邮件发送正常,但电子邮件末尾没有图像。当我点击下载它们时,它们不显示。根据 mailgun api 在 HTML 中引用图像(当然已简化!);
<img src="cid:img1.jpg"/>
<img src="cid:img2.jpg"/>
etc ...
显然我做错了什么,但是我尝试使用 requests.files 对象附加这些,它甚至没有发送电子邮件并且没有给出任何错误,所以我认为这根本不是正确的方法。
遗憾的是,这方面的文档相当稀少。
让 HTML 直接指向服务器端图像会更好吗?然而,这并不理想,因为服务器端图像通常不会是静态的(有些会,有些不会)。
最佳答案
发送内联图像已记录 here .
在 HTML 中,您将像这样引用图像:
<html>Inline image here: <img src="cid:test.jpg"></html>
然后,定义一个 Multidict,将文件发布到 API:
files=MultiDict([("inline", open("files/test.jpg"))])
披露,我为 Mailgun 工作。 :)
关于python - 使用 Python 请求库以 HTML 格式发送 Mailgun 内联图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15299693/