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}
CodePudding user response:
In order to solve the problem, I just had to add
msg.attachments
CodePudding user response:
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}