How do I send as an attachment a file save in a FileField in Django?
-
19-04-2021 - |
質問
how can I send a mail with a file saved in a FileField? I don't know how to access the file in the code below.
mail = EmailMessage(subject, message, 'from@from,com', ['to@to.com'])
mail.attach(?, ?, 'application/pdf')
mail.send()
EDIT
I tried to open the file with
f = list_pca.pdf_file.open(mode='rb')
where list_pca is an instance of
class ListPCA(models.Model):
pdf_file = models.FileField(upload_to=get_file_path_j, null=True, blank=True)
but I get an error "No such file or directory", because the path is wrong.
and
list_pca.pdf_file.path
return the wrong path too. Isn't it supposed to know where is the file thanks to the upload_to
option?
Thanks
Thanks
解決
mail = EmailMessage(subject, message, 'from@from,com', ['to@to.com'])
mail.attach('arbitrary_filename', myfile.read(), 'application/pdf')
mail.send()
Since you're using EmailMessage, you can just pass it the attachments kwarg as well.
email = EmailMessage(subject, message, 'from@from,com', ['to@to.com'],
attachments=(('foo.pdf', myfile.read(), 'application/pdf'),))
他のヒント
Ordinarily, like aganders3 suggested, I would use:
mail.attach_file(myfile.path) as well
But, I noted that it fails for attachments containing spaces.
I think this will do it:
mail.attach(os.path.basename(myfile.name), myfile.read(), 'application/pdf')
I might be overlooking a MIME-encoding step, but IIRC mail.attach will do that.
Try:
myfile = mymodel.somefilefield
mail = EmailMessage(subject, message, 'from@from,com', ['to@to.com'])
mail.attach('File Name', myfile.path, 'application/pdf')
mail.send()
The other suggestions should work, but you can also do:
mail.attach_file(myfile.path)
You can optionally pass the MIME-type as the second argument, but it just tries to figure it out from the file name if you don't provide it.