FileNotFoundError: [Errno 2] No such file or directory in Django

FileNotFoundError: [Errno 2] No such file or directory in Django

我正在开发一个 Django 项目,我需要通过我的系统通过电子邮件将文件发送给客户端。但是,当我将文件名放在 attach_file() 字段中时,出现找不到文件的错误。 这是我的代码:

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()

这是我的例外:

FileNotFoundError: [Errno 2] No such file or directory: 'file.file'
[08/Dec/2021 11:52:52] "GET /email/send/ HTTP/1.1" 500 83111

这是我的 setting.py:

...
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
...

这是我的项目结构:

src
   \_emailsender
               \_ urls.py
               \_ views.py
               \_ setting.py
   \_ static
            \_ file.file

attach_file 方法没有搜索功能,如果使用相对路径,您需要注意 Django 进程的 CWD,它可能不是静态目录。您可以尝试 static/file.file,但我建议使用绝对路径。

from emailsender.settings import BASE_DIR
...
msg.attach_file(os.path.join(BASE_DIR, 'static', 'file.file'))
msg.send()