gpt4 book ai didi

python - Flask WTF 到 flask-mail 附件?

转载 作者:行者123 更新时间:2023-11-28 22:33:05 26 4
gpt4 key购买 nike

通过flask-wtf上传文件,然后使用flask-mail发送邮件

def careers():
form = CareersForm()

if form.validate_on_submit():
msg = Message('my subject for message', sender = MAIL_USERNAME, recipients = [company_email])
msg.html = "My message"
with app.open_resource(form.resume) as fp:
msg.attach("resume.pdf", "application/pdf", fp.read())
mail.send(msg)

return render_template('default/careers.html',form=form)

我得到的错误是 AttributeError: 'FileField' object has no attribute 'startswith' 理想的结果是附加和发送电子邮件。

最佳答案

此程序将上传文件并将其附加到电子邮件中。电子邮件服务器设置存储在 settings.py 中。

#!/usr/bin/env python

from flask import Flask, render_template_string
from flask_wtf import FlaskForm
from wtforms import StringField, validators
from flask_wtf.file import FileField
from flask_mail import Mail, Message

app = Flask(__name__)
app.config.from_object('settings')
mail = Mail(app)


class FileForm(FlaskForm):
file_ = FileField('Some file')
addr = StringField('Address', [validators.InputRequired()])


@app.route('/', methods=['GET', 'POST'])
def root():
form = FileForm()
if form.validate_on_submit():
msg = Message(
'Sending file',
sender=form.addr.data.strip(),
recipients=[form.addr.data.strip()])
msg.body = 'Sending file %s' % (form.file_.name)
msg.attach(
form.file_.data.filename,
'application/octect-stream',
form.file_.data.read())
mail.send(msg)
return "Sent"

return render_template_string('''
<html><body><form method="post" enctype="multipart/form-data">
{{ form.hidden_tag() }}
{{ form.addr.label }}: {{ form.addr() }}<br/>
{{ form.file_.label }}: {{ form.file_() }}<br/>
<input type="submit" value="Click Me!"/>
</form></body></html>''', form=FileForm())

if __name__ == '__main__':
app.run(debug=True)

关于python - Flask WTF 到 flask-mail 附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40316387/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com