1

I want to add several files like attachment, but I can not understand how.

My code now looking like.

@form.post('/')
def get_data_from_form():
    message = request.form['message']
    grecaptcha = request.form['g-recaptcha-response']
    remote_ip = request.remote_addr
    files = request.files.getlist('file')
    msg = Message('EMAIL FROM FORM', recipients=['admin@****'])
    if check_recaptcha(grecaptcha, remote_ip):
        for file in files:
            mimetype = file.content_type
            filename = secure_filename(file.filename)
            msg.attachments = file
            msg.attach(filename, mimetype)
        msg.body = message
        try:
            mail.send(msg)
            return {'msg': 'The message has sent'}
        except Exception as err:
            logger.debug(err)
            return {'msg': False}

  • Does this answer your question? [Flask WTF to flask-mail attachment?](https://stackoverflow.com/questions/40316387/flask-wtf-to-flask-mail-attachment) – Kris Dec 30 '21 at 13:16
  • No, I know how attachment one file, I need to add several files – user9682431 Dec 30 '21 at 13:20

2 Answers2

0

In order to solve the problem, I just had to add msg.attachments

0

You can submit a list of Attachment instances to your Message object for doing this. See an example below

from flask_mail import Message, Attachment
from werkzeug.utils import secure_filename
@form.post('/')
def get_data_from_form():
    message = request.form['message']
    remote_ip = request.remote_addr
    if check_recaptcha(grecaptcha, remote_ip):
        files = request.files.getlist('file')
        attachments = [
            Attachment(filename=secure_filename(file.filename), content_type=file.content_type, data=file.read())
            for file in files]
        msg = Message(subject='EMAIL FROM FORM', recipients=['admin@****'], body=message,
                      attachments=attachments)
        try:
            mail.send(msg)
            return {'msg': 'The message has sent'}
        except Exception as err:
            logger.debug(err)
            return {'msg': False}
Kris
  • 8,680
  • 4
  • 39
  • 67