提问者:小点点

发送文件到电子邮件python


有一个输入形式,我可以从那里得到文件(pdf,txt,png等)在页面上,并发送到电子邮件。 除了一件事,一切都能起作用。 我只能从所有代码所在某个目录中选择文档,如果我从另一个文件夹中选择文档,我会得到错误No such file or directory。 如何从任何文件夹中选择文档?

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>

共1个答案

匿名用户

嗯,至少有几个问题。 就一个。 你正在寻找上传的文件,不管它是不是一个帖子。 另一方面,文件将上传到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>