0

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

4

5 に答える 5

2

通常、aganders3が提案するように、私は以下を使用します。

mail.attach_file(myfile.path) as well

ただし、スペースを含む添付ファイルでは失敗することに注意しました。

于 2012-10-13T23:06:11.513 に答える
2
mail = EmailMessage(subject, message, 'from@from,com', ['to@to.com'])
mail.attach('arbitrary_filename', myfile.read(), 'application/pdf')
mail.send()

EmailMessage を使用しているので、添付ファイルの kwarg も渡すことができます。

email = EmailMessage(subject, message, 'from@from,com', ['to@to.com'], 
    attachments=(('foo.pdf', myfile.read(), 'application/pdf'),))
于 2012-01-25T19:21:09.887 に答える
0

他の提案は機能するはずですが、次のこともできます。

mail.attach_file(myfile.path)

必要に応じて、MIME タイプを 2 番目の引数として渡すことができますが、指定しない場合はファイル名から判断しようとします。

于 2012-01-25T19:26:27.227 に答える
0

試す:

myfile = mymodel.somefilefield

mail = EmailMessage(subject, message, 'from@from,com', ['to@to.com'])
mail.attach('File Name', myfile.path, 'application/pdf')
mail.send()
于 2012-01-25T19:23:27.010 に答える
0

これでうまくいくと思います:

mail.attach(os.path.basename(myfile.name), myfile.read(), 'application/pdf')

MIME エンコーディングのステップを見落としているかもしれませんが、IIRC の mail.attach がそれを行います。

于 2012-01-25T19:21:31.223 に答える