如何在 Flask 的电子邮件中附加文件?

How to attach files in email message in Flask?

我正在使用 Flask 处理邮件 api,我是新手。我定义了 post 路由,它可以获取图像和一些 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 库附加图像并将其发送到 post 路由的。

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

我使用了 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)