使用Python请求库在HTML中发送Mailgun内联图像

2024-04-25 22:49:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难弄清楚如何使用Mailgun api从使用请求库的Python应用程序发送多条内联消息。目前我有(使用jinja2作为模板,使用flask作为webframework,托管在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(当然是简化的!)(二)

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

很明显我做错了,但是我试着用requests.files对象附加这些文件,它甚至没有发送电子邮件,也没有给出错误,所以我认为这根本不是正确的方法。

遗憾的是,关于这方面的文献相当稀少。

最好让HTML直接指向服务器端的图像吗?但是,这并不理想,因为服务器端映像通常不会是静态的(有些会,有些不会)。


Tags: topathnamefromapiosaddressdef