首页 > 解决方案 > 将文件发送到电子邮件 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>

标签: pythonhtmlpython-3.xflask

解决方案


好吧,至少有几个问题。一个。您正在寻找上传的文件,无论它是否是 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>

推荐阅读