【问题标题】:How exactly configure Django to send emails with bug reports?如何准确配置 Django 以发送带有错误报告的电子邮件?
【发布时间】:2018-08-02 22:29:28
【问题描述】:

我真的是 Django 新手,在配置我的应用程序以向我发送包含错误报告的电子邮件时遇到了麻烦。

我已经在设置文件中设置了我在 Django 文档中看到的所需变量,如下所示:

DEBUG = False
...
ADMINS = [('myname', 'myemail@server')]   # For server errors
MANAGERS = [('myname', 'myemail@server')] # For missing pages errors

我引发了测试错误,但什么也没发生,没有电子邮件。我该怎么办?

这是设置文件的代码(当然没有敏感数据):

"""
Django settings for genform project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

SECRET_KEY = '****************************************'

DEBUG = False

ALLOWED_HOSTS = []

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'widget_tweaks',
    'generador',
    'menu',
    'parametros_transformados',
    'seguridad',
    'tablas_de_no_parametros',
    'reportes',
    'logger',
    'parametros',
    'django_openid_auth'
     )

SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',

)

AUTHENTICATION_BACKENDS = (
    'django_openid_auth.auth.OpenIDBackend',
    'django.contrib.auth.backends.ModelBackend',
)

TEMPLATES = [
    {
        'BACKEND':'django.template.backends.django.DjangoTemplates',
        'DIRS':[os.path.join(os.path.dirname(__file__), '../templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

OPENID_UPDATE_DETAILS_FROM_SREG = True

ROOT_URLCONF = 'genform.urls'

WSGI_APPLICATION = 'genform.wsgi.application'

DATABASES = {
'default': {
     'ENGINE': 'django.db.backends.postgresql_psycopg2',
     'NAME': '*****',
     'USER': '******',
     'PASSWORD': '******',
     'HOST': '***********',
     'PORT': '***',
     }
}

STATICFILES_DIRS = (
    #os.path.dirname(__file__)+"static",
    # Put strings here, like "/home/html/site_media" or "C:/www/django/site_media".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(os.path.dirname(__file__), '../static'),
)

AUTH_PROFILE_MODULE = 'seguridad.c_perfil_usuario'

LOGIN_REDIRECT_URL = '/index'

OPENID_SSO_SERVER_URL = '***********'

OPENID_CREATE_USERS = True

LANGUAGE_CODE = 'es-es'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

STATIC_URL = '/static/'

ADMINS = [('MyName', 'myemail@server')]

MANAGERS = [('MyName', 'myemail@server')]

【问题讨论】:

  • 把settings.py的代码粘贴到这里。
  • 太长了,怎么粘贴?
  • 好的,我添加了settings.py文件的代码
  • 您缺少有效的电子邮件后端,并且您没有配置日志记录。看看我下面的答案。
  • 如果这解决了您的问题,请考虑对答案进行投票、接受或评论。这是在 SO 的其他人投入一些时间发布之后向他们表示感谢的最佳方式。谢谢!

标签: django configuration


【解决方案1】:

你的LOGGING configuration 是什么? 我在生产环境中使用以下内容:

ADMINS = [
    ('Admin1', 'admin1@mail.com'),
    ('Admin2', 'admin2@mail.com')
]

MANAGERS = ADMINS

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'  # for testing
EMAIL_HOST = 'relay.server.com'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s '
                      '%(process)d %(thread)d %(message)s'
        },
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false', ],
            'class': 'django.utils.log.AdminEmailHandler'
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins', ],
            'level': 'ERROR',
            'propagate': True
        },
        'django.security.DisallowedHost': {
            'level': 'ERROR',
            'handlers': ['console', 'mail_admins', ],
            'propagate': True
        }
    }
}

确保您有一个有效的EMAIL_BACKEND defined。如果您没有自己的 SMTP 服务器 (EMAIL_HOST),您可以使用 mailgun 甚至 gmail 之类的服务。

【讨论】:

    【解决方案2】:

    这些设置看起来是正确的,但还有其他事情可能会阻碍您。

    1. settings.py 中的电子邮件信息可能未配置

    2. 您已覆盖settings.py 中的默认日志设置,并且没有将错误写入电子邮件日志。

    如果其中一项或两项设置不正确,那么您将不会收到电子邮件。

    要修复 1,您可以查看以下答案:https://stackoverflow.com/a/4642194/4788717

    要修复 2,您可以查看文档:https://docs.djangoproject.com/en/dev/topics/logging/ 并确保您拥有默认或邮件管理员案例:

    LOGGING = {
    ...
    'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'filters': ['special']
    ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      • 2013-05-05
      • 2017-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 1970-01-01
      相关资源
      最近更新 更多