FileNotFoundError: [Errno 2] No such file or directory in Django
I'm working on a Django project where I need to send a file to the client via my system by email. But when I put the file name in the attach_file() field, I get the error of not finding the file. This is my code:
def email_sender(request):
if request.method == "GET":
subject = 'welcome to GFG world'
email_from = settings.EMAIL_HOST_USER
recipient_list = ["example@gmail.com", ]
to = 'example@gmail.com'
text_content = 'This is an important message.'
msg = EmailMultiAlternatives(subject, text_content, email_from, [to])
msg.attach_file('file.file')
msg.send()
And this is my exception:
FileNotFoundError: [Errno 2] No such file or directory: 'file.file'
[08/Dec/2021 11:52:52] "GET /email/send/ HTTP/1.1" 500 83111
This is my setting.py:
...
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
...
This is my project structure:
src
\_emailsender
\_ urls.py
\_ views.py
\_ setting.py
\_ static
\_ file.file
Thanks for your help.
The attach_file
method does not have search functionality, if using a relative path you need to be aware of the CWD of the the Django process which is probably not the static dir. You could try static/file.file
but I suggest going with an absolute path.
from emailsender.settings import BASE_DIR
...
msg.attach_file(os.path.join(BASE_DIR, 'static', 'file.file'))
msg.send()