Search code examples
pythonflaskpython-requestsmultipartform-datasmtplib

How to attach files in email message in Flask?


I am working on a mailing api in Flask and am a newbie. I have post route defined which can get images and some formData and using it I send email using smtplib. I am having a problem in adding attachments in my message. Can anybody guide me how to add images in attachments in this message?

Printing out print(request.files.getlist('images')) shows me [<FileStorage: 'IMG-20200509-WA0001.jpg' ('application/octet-stream')>] in the terminal meaning it's receiving image.

Here is my code:

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)

If it's any help here is how I'm attaching images and sending it to post route using dio library in my Flutter mobile application.

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

Solution

  • I used flask_mail library and achieved it. Firstly I saved images then attached them to my mail and lastly removed them from my directory.

     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)