Flask-Mail 如何将多个文件添加到邮件中?
Flask-Mail how to add multiple files to message?
我想添加几个附件之类的文件,但是我看不懂怎么办。
我的代码现在看起来像。
@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}
为了解决问题,我只需要添加
msg.attachments
您可以将 Attachment
个实例的列表提交给您的 Message
对象以执行此操作。请参阅下面的示例
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}
我想添加几个附件之类的文件,但是我看不懂怎么办。
我的代码现在看起来像。
@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}
为了解决问题,我只需要添加
msg.attachments
您可以将 Attachment
个实例的列表提交给您的 Message
对象以执行此操作。请参阅下面的示例
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}