首页 > 解决方案 > Send_email 与 django 生成错误 _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

标签: pythondjangoemail

解决方案


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

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

当您使用send_mail没有后端参数的函数时,django 选择基于settings.EMAIL_BACKEND.

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

引用 django 文档

文件后端将电子邮件写入文件。为在此后端打开的每个新会话创建一个新文件。 当使用 get_connection() 创建连接时,写入文件的目录取自 EMAIL_FILE_PATH设置或 file_path 关键字。

所以我的建议是EMAIL_FILE_PATHsettings.py 中的设置将解决这个问题。


推荐阅读