使用 Pyramid 通过电子邮件发送从 POST 请求上传的文件

Emailing files uploaded from POST request using Pyramid

我有一个 Angular 应用程序,它通过 POST 将文件上传到由 Pyramid/Python 处理的端点:

@Component({
   selector: 'app-application',
   templateUrl: 'app.application.html'
   })
export class ApplicationComponent {
   public uploader: FileUploader = new FileUploader({
   url: MyEndPoint
   });

还有我的金字塔服务器:

@application.post()
def job_application(request):

    request.response.headerlist.extend(
        (
            ('Access-Control-Allow-Origin', AngularClient),
            ('Content-Type', 'application/json'),
            ('Access-Control-Allow-Credentials', 'true'),
            ('Allow', 'GET, POST')
        )
    )


    mailer = Mailer(host="smtp.gmail.com",
        port="465", username="makeemup@gmail.com", password="password", ssl=True)
message = Message(subject="It works!",
                  sender="makeemup@gmail.com",
                  recipients=["makeemup@gmail.com"],
                  body="hello"
                  )

if request.POST:

    attachment = Attachment("photo.doc", "doc/docx", str(request.body))
    message.attach(attachment)

    mailer.send_immediately(message, fail_silently=True)

return request.response

当我尝试将上传的文件附加到电子邮件时,WebKitFormBoundary 标记附加到文件的页眉和页脚,内容以字节码返回。如何通过金字塔服务器将实际上传的文件附加到电子邮件地址?

It sounds like what is happening is that you are appending the actual body of your POST request to the file itself, thus why the WebKitFormBoundary tag is present in your file.

So firstly you need to access the particular content you want, which is stored in a MultiDict object and is accessible like a normal dictionary.

I'd then write this content somewhere, lets say your /tmp/ directory, especially if your a UNIX user. Then from this file path, attach the email to Pyramids mailer.

if request.POST:

    new_file = request.POST['uploadFile'].filename
    input_file = request.POST['uploadFile'].file
    file_path = os.path.join('/tmp', '%s.doc' % uuid.uuid4())
    temp_file_path = file_path + '~'


    input_file.seek(0)
    with open(temp_file_path, 'wb') as output_file:
        shutil.copyfileobj(input_file, output_file)

    os.rename(temp_file_path, file_path)
    data = open(file_path, 'rb').read()
    mr_mime = mimetypes.guess_type(file_path)[0]

    attachment = Attachment(new_file, mr_mime, data)
    message.attach(attachment)
    mailer.send_immediately(message, fail_silently=True)

希望对您有所帮助!