Send_email 使用 django 生成错误 _getfullpathname:

Send_email with django generate error _getfullpathname:

我正在尝试使用 django 发送电子邮件,但即使使用简单的代码我也收到错误

send_mail(
            'Subject here',
            'Here is the message.',
            'from@example.com',
            ['to@example.com'],
            fail_silently=False,
        )

我得到那个输出错误

Traceback (most recent call last):
  File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\VisualStudioWorkspaces\DjangoPlayground\django_tutorial\accounts\views.py", line 93, in register
    send_mail(
  File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\mail\__init__.py", line 52, in send_mail
    connection = connection or get_connection(
  File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\mail\__init__.py", line 35, in get_connection
    return klass(fail_silently=fail_silently, **kwds)
  File "D:\VisualStudioWorkspaces\DjangoPlayground\.venv\lib\site-packages\django\core\mail\backends\filebased.py", line 20, in __init__
    self.file_path = os.path.abspath(self.file_path)
  File "C:\Users\oscur\AppData\Local\Programs\Python\Python39\lib\ntpath.py", line 527, in abspath
    return normpath(_getfullpathname(path))

Exception Type: TypeError at /accounts/registration/
Exception Value: _getfullpathname: path should be string, bytes or os.PathLike, not NoneType

Django 支持不同的电子邮件后端。

  1. SMTP 后端(默认)
  2. 控制台后端
  3. 文件后端
  4. 内存后端

当你使用 send_mail 没有后端参数的函数时 django select backend based on settings.EMAIL_BACKEND.

从异常看来 django using File backend(这意味着 EMAIL_BACKEND 您最有可能使用 'django.core.mail.backends.filebased.EmailBackend'

引用自 django 文档

The file backend writes emails to a file. A new file is created for each new session that is opened on this backend. The directory to which the files are written is either taken from the EMAIL_FILE_PATH setting or from the file_path keyword when creating a connection with get_connection().

所以我的建议是在settings.py中设置EMAIL_FILE_PATH可以解决这个问题。