python - 将文件发送到电子邮件 python
问题描述
有一个输入表单,我可以从中获取页面上的文档(pdf、txt、png 等)并将其发送到电子邮件。除了一件事之外,一切都有效。我只能从所有代码所在的某个目录中选择文档,如果我从另一个文件夹中选择我的文档,我会收到错误消息No such file or directory
。如何从任何文件夹中选择 doc?
python:
@app.route('/', methods=['GET','POST'])
def profile():
file = request.form['file']
password = "mypass"
msg['From'] = "mymail"
msg['To'] = "anothermail"
msg['Subject'] = "Subject"
msg = MIMEMultipart()
file_to_send = MIMEApplication(open(file, 'rb').read())
file_to_send.add_header('Content-Disposition', 'attachment', filename=file)
msg.attach(file_to_send)
server = smtplib.SMTP('smtp.gmail.com: 587')
server.starttls()
server.login(msg['From'], password)
server.sendmail(msg['From'], msg['To'], msg.as_string())
return render_template('profile.html', file=file)
profile.html:
<input type='file' class="form-control" name="file" id="uploadPDF">
<button class="btn btn-primary send">
Send
</button>
解决方案
好吧,至少有几个问题。一个。您正在寻找上传的文件,无论它是否是 POST。另一方面,文件将上传到request.files
,而不是request.form
.
您可以查看有关上传文件的 Flask 文档。我想你想要这样的东西:
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def profile():
if request.method == 'POST':
file = request.files['file']
msg = MIMEMultipart()
msg['From'] = "mymail"
msg['To'] = "anothermail"
msg['Subject'] = "Subject"
file_to_send = MIMEApplication(file.stream.read())
file_to_send.add_header('Content-Disposition', 'attachment', filename=file.filename)
msg.attach(file_to_send)
messagge_content = msg.as_string()
# (Your code that sends an email)
return render_template('profile.html')
另请记住,您的表单需要上传enctype="multipart/form-data"
:
<form method="post" enctype="multipart/form-data">
<input type='file' class="form-control" name="file" id="uploadPDF">
<button class="btn btn-primary send">
Send
</button>
</form>
推荐阅读
- android - Tensorflow Lite GPUdelegate 在最后一层给出“Dimensions are not BHWC”错误。但对我来说,这一层似乎是 BHWC,就像其他所有层一样
- ruby-on-rails - 查询关联数据时急切加载关联
- java - 使用 XSLT 解析 XML 时如何处理多个小数?
- python - 使用 django 电子邮件创建 txt 文件模板
- node.js - 公牛队列包配置混乱
- python - list[:] 的浅拷贝
- java - 在 EJB 中安排类似 Cron 的作业
- python - 无法导入 normalize_corpus python 3
- reactjs - 测试用 recompose 组成的多个 HOC
- php - 如何检测字符串是否包含 PHP 代码?PHP