使用Python Requests库通过Mailgun发送HTML内联图片

10 投票
2 回答
9332 浏览
提问于 2025-04-17 18:26

我在用Mailgun的API从一个Python应用程序发送多个内联消息时遇到了问题,使用的是requests库。目前我有以下代码(使用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

邮件发送得很好,但最后邮件里没有图片。当我点击下载时,图片也不显示。这些图片在HTML中是按照Mailgun的API引用的(当然是简化过的!);

<img src="cid:img1.jpg"/>
<img src="cid:img2.jpg"/>
etc ...

显然我做错了什么,不过我尝试用requests.files对象来附加这些图片,但这样不仅没有发送邮件,还没有任何错误提示,所以我猜这根本不是正确的方法。

可惜的是,关于这个的文档信息非常少。

直接让HTML指向服务器上的图片会不会更好呢?不过这样并不理想,因为服务器上的图片一般不会是静态的(有些是,有些不是)。

2 个回答

10

截至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
)
20

发送内嵌图片的相关信息可以在这里找到。

在HTML代码中,你可以这样引用图片:

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

接下来,定义一个多字典(Multidict),用来把文件发送到API:

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

顺便说一下,我在Mailgun工作。:)

撰写回答