【问题标题】:How to attach files in email message in Flask?如何在 Flask 的电子邮件中附加文件?
【发布时间】:2020-08-25 05:34:18
【问题描述】:

我正在开发 Flask 中的邮件 API,我是新手。我已经定义了可以获取图像和一些 formData 的发布路线,并使用它我使用 smtplib 发送电子邮件。我在邮件中添加附件时遇到问题。谁能指导我如何在此消息的附件中添加图像?

打印出print(request.files.getlist('images')) 在终端中显示[<FileStorage: 'IMG-20200509-WA0001.jpg' ('application/octet-stream')>],这意味着它正在接收图像。

这是我的代码:

def listMailer(request):

    name = request.form.get('name')
    phone = request.form.get('phone')
    wegmansUsername = request.form.get('wegmans_username')
    wegmansPassword = request.form.get('wegmans_password') 
    description =  request.form.get('description') 


    EMAIL_ADDRESS = xyz
    EMAIL_PASSWORD = xyz
    msg = EmailMessage()
    msg['Subject'] = 'Delivery Schedule'
    msg['From'] = EMAIL_ADDRESS
    msg['To'] = 'xyz@gmail.com'

    print(request.files.getlist('images'))

    msg.set_content('This is a plain text email')

    msg.add_alternative("""\

    <!DOCTYPE html>
    <html>
        <body>
            <p style="">Name: {}</p>
            <p style="">Phone: {}</p>
            <p style="">Wegmans Username: {}</p>
            <p style="">Wegmans Password: {}</p>
            <p style="">Description: {}</p>
        </body>
    </html>
    """.format(name,phone,wegmansUsername,wegmansPassword,description), subtype='html')


    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
        smtp.send_message(msg)

如果这里有任何帮助,那就是我如何在我的 Flutter 移动应用程序中使用 dio 库附加图像并将其发送到发布路线。

        for(var image in _images) {
                      _shoppingForm.files.add(MapEntry(
                          'images',
                          await MultipartFile.fromFile(image, filename: "${image.split("/").last}")
                      ));
                  }

【问题讨论】:

标签: python flask python-requests multipartform-data smtplib


【解决方案1】:

我使用了flask_mail 库并实现了它。首先我保存了图片,然后将它们附加到我的邮件中,最后将它们从我的目录中删除。

 for image in request.files.getlist('images'):
        image.save(image.filename)
        extension = image.filename.split('.')[-1]
        with app.open_resource(image.filename) as fp:
            msg.attach(image.filename,'image/' +extension, fp.read())
        os.remove(image.filename)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    • 2023-03-07
    • 1970-01-01
    • 2021-10-03
    • 2011-08-04
    • 1970-01-01
    • 2019-12-31
    相关资源
    最近更新 更多