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

时间:2013-03-08 17:18:48

标签: python html email python-requests mailgun

我无法使用请求库从Python应用程序中使用Mailgun api发送多个内联消息。目前我有(使用jinja2作为模板和烧瓶作为web框架,托管在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直接指向服务器端图像会更好吗?然而,这并不理想,因为服务器端图像通常不会是静态的(有些会,有些则不会)。

2 个答案:

答案 0 :(得分:16)

发送内联图片已记录here

在HTML中,您将像这样引用图像:

<html>Inline image here: <img src="cid:test.jpg"></html>

然后,定义一个Multidict,将文件发布到API:

files=MultiDict([("inline", open("files/test.jpg"))])

披露,我为Mailgun工作。 :)

答案 1 :(得分:2)

截至2020年,此处的实际文档为:https://documentation.mailgun.com/en/latest/api-sending.html#examples

我的例子:

response = requests.post(
    'https://api.mailgun.net/v3/' + YOUR_MAILGUN_DOMAIN_NAME + '/messages',
    auth=('api', YOUR_MAILGUN_API_KEY),
    files=[
        ('inline[0]', ('test1.png', open('path/filename1.png', mode='rb').read())),
        ('inline[1]', ('test2.png', open('path/filename2.png', mode='rb').read()))
    ],
    data={
        'from': 'YOUR_NAME <' + 'mailgun@' + YOUR_MAILGUN_DOMAIN_NAME + '>',
        'to': [adresat],
        'bcc': [bcc_adresat],
        'subject': 'email subject',
        'text': 'email simple text',
        'html': '''<html><body>
            <img src="cid:test1.png">
            <img src="cid:test2.png">
            </body></html>'''
    },
    timeout=5  # sec
)