python - 使用 Python 请求库以 HTML 格式发送 Mailgun 内联图像

标签 python html email python-requests mailgun

我无法弄清楚如何使用请求库从 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/

相关文章:

python - 如何查看 django 模板列表中是否存在某个值。尝试使用 IN 运算符但不起作用

python - 这是 Python 中的鸭子类型(duck typing)吗?

html - 样式 3 输入彼此下方

html - 如何将div放在body之外?

javascript - HTML 页面左侧和右侧的文本

html - 电子邮件签名在回复时搞砸了

email - 如何仅为 Outlook 2013 将动画图像插入电子邮件正文?

python - 使用 itertools、melt 和 groupby 正确地使用 Pandas 计算每个属性值的事件对

python - 使用 strptime 的日期格式不正确

node.js - nodemailer Node 电子邮件模板,没有此类文件或目录错误