Email problem

I want to send an email using a Django app, but the email isn’t being sent. I’ve tried Mailtrap, SendGrid, Mailgun, and Google Gmail. Everything seems to be configured correctly in the settings.py file, but the email still isn’t being sent. The console shows that the email was sent, but in reality, no email is being received. Can anyone help me figure out what’s wrong?

Welcome @Hizar62 !

We’re going to need more details here to try and help you.

Have you tried using the sendtestemail command to try sending an email from the command line? (If you haven’t, you should.)

We may also need to see all your email settings (except for your email password) and the view that is supposed to send the emails.

What exactly are you seeing on the console that is making you think that the email was sent? (Please copy/paste your console output here, between lines of three backtick - ` characters. Do not post an image here of your console output.)

1 Like

EMAIL_BACKEND = ‘django.core.mail.backends.smtp.EmailBackend’

EMAIL_HOST = ‘live.smtp.mailtrap’

EMAIL_HOST_USER = ‘kjnfjkn’

EMAIL_HOST_PASSWORD = ‘jdfjkdnfndkf’

EMAIL_PORT = 587

EMAIL_USE_TLS = True

this is the setting.py code where i configure the smtp.

this is the console output
[25/Aug/2024 21:41:50] “GET /simple_mail HTTP/1.1” 301 0
Content-Type: text/plain; charset=“utf-8”
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Thats your subject
From: django@mailtrap.club
To: recipientmail@gmail.com
Date: Sun, 25 Aug 2024 16:41:50 -0000
Message-ID: 172460411088.jdnfkfndjknkjf15@DESKTOP-njfdnsfjdf

Thats your message body

[25/Aug/2024 21:41:51] “GET /simple_mail/ HTTP/1.1” 200 13

basically i write simple function to send email

What you’ve shown here isn’t the view to send the email, nor does it provide any evidence that an email was sent.

You also haven’t shown an attempt to use the sendtestemail to demonstrate that your configuration is correct.

can you give me the simple code for sendtestemail im new in django

It’s a manage.py command. You run it from the command line. See the docs for it referenced above.

so i do sendtestmail this is what i got

(env) D:\SideProjects\danube>python manage.py sendtestemail boy552@gmail.com
Content-Type: text/plain; charset=“utf-8”
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: Test email from DESKTOP-XXXXXX on 2024-08-29 18:21:23.695804+00:00
From: webmaster@localhost
To: boy552@gmail.com
Date: Thu, 29 Aug 2024 18:21:23 -0000

If you’re reading this, it was successful.

And did “boy552@gmail.com” receive the email?

no, not even in the spam folder

You should not see the email on the console when you use the sendtestemail command.

You’ve got something wrong with your configuration. Do you possibly have duplicate entries in your settings.py file for these EMAIL settings? Are you sure you’re using the right settings.py file?

That’s the right contents of the email, but it’s directing the email to the console and not the mail server.

i think i follow the offical documentation for the email configuration in settings.py
and there is no duplication entries i dont know why it is showing on console. and what do you mean by mail server?

The only way we can help verify that is if you were to:

  • post the complete contents of your settings.pty,
  • post the contents of the manage.py command you are using,
  • and verifying that you do not have the DJANGO_SETTINGS_MODULE set as an environment variable.

settings.py

"""
Django settings for danube project.

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

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

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

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-jdnfkjasnknsfjknsfjkgnfjgnas

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




EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'live.smtp.mailtrap.io'
EMAIL_HOST_USER = 'api'
EMAIL_HOST_PASSWORD = 'nskjnjnsfkjvnjfvknfvnkfnvjnfkvnfjkvnkjf'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = 'webmaster@localhost' 


import logging
logging.basicConfig(level=logging.DEBUG)



ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.humanize',
    'widget_tweaks',
    'account',
    'home',
    'anymail'
]

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

ROOT_URLCONF = 'danube.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',
                'account.context_processors.user_profile'
            ],
        },
    },
]

WSGI_APPLICATION = 'danube.wsgi.application'






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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}




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',
    },
]

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'


MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

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

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


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

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'danube/static'),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

manage.py

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'danube.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

i think yes i didnt set DJANGO_SETTINGS_MODULE as an env varaible

Yes there are. Examine your settings file more carefully.

can you help me? to understand where i make a mistake

You have the same email-related setting in two different places in your settings.py file. You need to find the duplicate and remove it.

thank you, it is working now!!!