When sending an email with a csv attachment in python
When I sent it to windows, it became untitled document.txt
and I was addicted to it, so make a note.
from email.mime.text import MIMEText
from django.core.mail import EmailMessage
filename = 'test.csv'
encoding = 'cp932'
contents = create_csv() #Create csv file here
contents = contents.encode(encoding, 'ignore') #Convert from python3 unicode type to str type
csv_file = MIMEText(
contents,
'csv',
encoding,
)
csv_file.set_param('name', filename) #outlook support
csv_file.add_header('Content-Disposition', 'attachment',
filename=('iso2022-jp', '', filename))
email = EmailMessage(
'Email title',
'the content of the email\n',
to=['[email protected]'],
attachments=(csv_file,),
)
email.send()
The attached file part of the email actually sent is as follows.
--===============3879210183231680079==
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Type: text/csv; charset="cp932"; name="test.csv"
Content-Disposition: attachment; filename*=iso2022-jp''test.csv
File contents
--===============3879210183231680079==--
EmailMessage is a sending method provided by django. Add the files you want to attach with attachements.
Since the MIMEType of the attached file is text / csv
, use ʻemail.mine.text.MIMEText. The file name is specified by
Content-Disposition`.
This is fine for mac mail and gmail, but outlook doesn't look at this header.
The name =" test.csv "
at the end of Content-Type
is important, and it seems that outlook displays the file name by looking at this.
In the case of Japanese files, it seems necessary to convert name with base64encode.
Content-Type: application/applefile;
name="=?utf-8?B?5pel5pys6Kqe44Gu44OV44Kh44Kk44OrLmNzdg==?="
Recommended Posts