6

I could send mail using the following code

E:\Python\django-test\LYYDownloaderServer>python manage.py shell

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.core.mail import send_mail
>>>
>>> send_mail(
...     'Subject here',
...     'Here is the message.',
...     'redstone-cold@163.com',
...     ['2281570025@qq.com'],
...     fail_silently=False,
... )
1
>>> 

According to the doc:

When DEBUG is False, Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (HTTP status code 500). This gives the administrators immediate notification of any errors. The ADMINS will get a description of the error, a complete Python traceback, and details about the HTTP request that caused the error.

but in my case, Django doesn't email reporting an internal server error (HTTP status code 500) enter image description here

what's the problem? please help fix the problem

settings.py

"""
Django settings for LYYDownloaderServer project.

Generated by 'django-admin startproject' using Django 1.9.1.

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

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

import os
ADMINS = [('Philip', 'r234327894@163.com'), ('Philip2', '768799875@qq.com')]
EMAIL_HOST = 'smtp.163.com'  # 'localhost'#'smtp.139.com'
# EMAIL_PORT = 25
# EMAIL_USE_TLS = True

EMAIL_HOST_USER = 'r234327894@163.com'  # '13529123633@139.com'
EMAIL_HOST_PASSWORD = '******'
# DEFAULT_FROM_EMAIL = 'r234327894@163.com'
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 's4(z8qzt$=x(2t(ok5bb58_!u==+x97t0vpa=*8bb_68baekkh'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['127.0.0.1']#, '.0letter.com'


# Application definition

INSTALLED_APPS = [
    'VideoParser.apps.VideoparserConfig',
    'FileHost.apps.FilehostConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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

ROOT_URLCONF = 'LYYDownloaderServer.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'LYYDownloaderServer.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

STATIC_URL = '/static/'

the start of views.py

from django.http import JsonResponse, HttpResponse
import logging
import m3u8
import os
from VideoParser.parsers.CommonParsers import *
import urllib.parse
import hashlib
from datetime import datetime, timedelta, date
from django.views.decorators.csrf import csrf_exempt
from django.db import IntegrityError
from VideoParser.models import *
from importlib import import_module
# print('-------------views --------')
FILES_DIR = 'files'

# specialHostName2module = {'56': 'v56'}
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d %I:%M:%S %p', level=logging.ERROR, handlers=[logging.handlers.RotatingFileHandler(filename=os.path.join(FILES_DIR, 'LYYDownloaderServer.log'), maxBytes=1024 * 1024, backupCount=1)])
...
iMath
  • 2,326
  • 2
  • 43
  • 75

3 Answers3

2

First, it doesn't matter if you were able to send the mail using the console, but if you received the mail. I assume you did.

Second, it's best to try with exactly the same email address in the console as the one set in the ADMINS, just to be sure.

Finally, the sender address might also matter. The default is "root@localhost", and while "root" is OK, "localhost" is not, and some mail servers may refuse the email. Specify another sender email address by setting the SERVER_EMAIL Django setting.

Antonis Christofides
  • 6,990
  • 2
  • 39
  • 57
  • Thanks, SERVER_EMAIL is essential to this problem , I've written a article about the problem, learn more here http://redstoneleo.blogspot.com/2016/12/email-reporting-exceptions-and-errors_30.html – iMath Dec 30 '16 at 11:22
0

Djano sends admin emails on error using logging system.

As I can see from your views.py you are changing logging settings. This can be the cause of the problem as you cleared that django admin handler mail_admins.

For more information check django documentation

kostak
  • 36
  • 4
0

The Django doc says: In order to send email, EMAIL_HOST, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are at the very least needed, but as I tested, we should also specify SERVER_EMAIL, and only when SERVER_EMAIL is equal to EMAIL_HOST_USER so can send the email, e.g.

EMAIL_HOST = 'smtp.163.com'  
SERVER_EMAIL = '234327894-cold@163.com'  # 
EMAIL_HOST_USER = '234327894-cold@163.com'  # 
EMAIL_HOST_PASSWORD = '234327894123'  #

Django uses AdminEmailHandler to send an email to the site admins for each log message it receives. Besides Django, we could also use Python's logging.handlers.SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0) to do the same. For example, put the following code in views.py(do change to your account), it will email reporting unhandled exceptions and results in an internal server error (HTTP status code 500).

import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d %I:%M:%S %p', handlers=[logging.handlers.SMTPHandler('smtp.163.com', '234327894-cold@163.com', ['234327894-cold@163.com'], 'LYYDownloader Server Exception', credentials=('234327894-cold@163.com', '234327894123'))])

Comparing AdminEmailHandler and SMTPHandler, I advocate to use SMTPHandler whenever possible. First, AdminEmailHandler is Django specific, while you can use SMTPHandler in any Python program, one thing you should care is when using SMTPHandler in client side software, some anti-virus software may treat the software as spyware, so you should inform users when your software is about to send email. Second, I found email sending by AdminEmailHandler has a bunch of Information while SMTPHandler just send the Python exception Information which makes debugging a bit clear!

Third , If you configure your email within settings.py in Django , there is no exception throw out even If you have made something wrong with the email confirmation , while SMTPHandler always throw out exception on what's wrong in using .

cite from http://redstoneleo.blogspot.com/2016/12/email-reporting-exceptions-and-errors_30.html

iMath
  • 2,326
  • 2
  • 43
  • 75