【问题标题】:send file to email python将文件发送到电子邮件 python
【发布时间】:2020-06-30 13:44:37
【问题描述】:

有一个输入表单,我可以从中获取页面上的文档(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>

【问题讨论】:

  • 你能发布你看到的实际追溯吗?
  • @KenKinder,当然。请再次检查。当我从另一个文件夹中选择其他文档的图像时,就会发生这种情况

标签: python html python-3.x flask


【解决方案1】:

嗯,至少有几个问题。一个。您正在寻找上传的文件,无论它是否是 POST。另一方面,文件将上传到request.files,而不是request.form

您可以查看uploading files 上的 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2020-10-10
    相关资源
    最近更新 更多