Flask-Mail 如何将多个文件添加到邮件中?
Posted
技术标签:
【中文标题】Flask-Mail 如何将多个文件添加到邮件中?【英文标题】:Flask-Mail how to add multiple files to message? 【发布时间】:2021-12-30 12:55:12 【问题描述】:我想添加几个文件,比如附件,但我不明白怎么做。
我的代码现在看起来像。
@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
【问题讨论】:
这能回答你的问题吗? Flask WTF to flask-mail attachment? 不行,我知道怎么附件一个文件,我需要添加几个文件 【参考方案1】:为了解决问题,我只需要添加
msg.attachments
【讨论】:
【参考方案2】:您可以将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
【讨论】:
以上是关于Flask-Mail 如何将多个文件添加到邮件中?的主要内容,如果未能解决你的问题,请参考以下文章