I have an Angular app which uploads files via POST to an endpoint which is handled by Pyramid/Python:
@Component({
selector: 'app-application',
templateUrl: 'app.application.html'
})
export class ApplicationComponent {
public uploader: FileUploader = new FileUploader({
url: MyEndPoint
});
And my Pyramid server:
@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="[email protected]", password="password", ssl=True)
message = Message(subject="It works!",
sender="[email protected]",
recipients=["[email protected]"],
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
When I try to attach the uploaded file to the e-mail, the WebKitFormBoundary tag is appended to the header and footer of the file, and the content is returned in Byte code. How do I attach the actual uploaded file to an e-mail address via Pyramid server?
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)
Hope this helps!