0

I am currently attempting to attach a csv to an email but I keep getting errors, the code I have at the moment is this:

error_list=[{'error_1': 0, 'error_2':1}, {'error_1': 2, 'error_2': 1}]
with open('errors.csv', "w") as infile:
    writer = csv.DictWriter(infile, fieldnames=error_list[0].keys())
    writer.writeheader()
    for data in error_list:
        writer.writerow(data)
mail = EmailMessage(subject='Test', from_email=EMAIL_HOST_USER, to=['example@example.com',])
mail.attach('errors.csv', infile, 'text/csv')
mail.send()

I am not quite sure where I am going wrong - at the moment I am getting the error: 'Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed by the remote host'

1 Answers1

0

The second argument to EmailMessage.attach() is supposed to be the file's content as a bytestring (str in python2, byte in python3), not a file object (and specially not one opened in write mode).

Actually, writing to file here is not only useless and inefficient but also begging for concurrency issues, specially when you use the same filename for everyone (remember that a wsgi app is typically served using multiple process to handle concurrent requests). Creating the file in the current working directory is another bad idea FWIW, you want to setup a specific directory in a known place (and outside your code base) for those kind of things - but anyway: you don't need a file here (unless your json is huge, which is rarely the case), you can use an in-memory file-like object like a StringIO instead.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118