Skip to content

Fix `ValueError: read of closed file` when attach files in multithreading

Nonchalant requested to merge fix_parallel_email_threads into master

This is a strange issue that occurs when attaching any files to an email when it is done on a separate thread. The error goes away when you do not call the function in a separate thread, but then the task becomes a bottleneck on the main application thread and the client receives a time out error from their request.

The fix involves creating the Attachment objects first before creating a Message instance. This is very strange because instantiating Message does not touch the file request object in any way, so I wouldn't expect it to open (and importantly, CLOSE) the file prematurely and result in this error.

Note that multithreading.Thread has been replaced with ThreadPoolExecutor here so that the total number of threads can be set/limited beforehand.

Merge request reports