JayBTProgramming
JayBTProgramming

Reputation: 25

SMTP disconnected Error occured in Django

So i've been working on a repo of a project for some time now in an effort to learn and get familiar with Django. In the project, once a student register's onto the site, it's supposed to send a confirmation link to the specified email, but when i did, nothing happened and instead i got this traceback:

Traceback (most recent call last):
  File "C:\Users\afric\.pyenv\pyenv-win\versions\3.8.10\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "C:\xampp\htdocs\Online-Examination-System\Exam\student\views.py", line 134, in run
    self.email.send(fail_silently = False)
  File "C:\Users\afric\.virtualenvs\Online-Examination-System-aZtpAN9a\lib\site-packages\django\core\mail\message.py", line 298, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\Users\afric\.virtualenvs\Online-Examination-System-aZtpAN9a\lib\site-packages\django\core\mail\backends\smtp.py", line 127, in send_messages
    new_conn_created = self.open()
  File "C:\Users\afric\.virtualenvs\Online-Examination-System-aZtpAN9a\lib\site-packages\django\core\mail\backends\smtp.py", line 92, in open        
    self.connection.starttls(context=self.ssl_context)
  File "C:\Users\afric\.pyenv\pyenv-win\versions\3.8.10\lib\smtplib.py", line 762, in starttls
    self.ehlo_or_helo_if_needed()
  File "C:\Users\afric\.pyenv\pyenv-win\versions\3.8.10\lib\smtplib.py", line 604, in ehlo_or_helo_if_needed
    if not (200 <= self.ehlo()[0] <= 299):
  File "C:\Users\afric\.pyenv\pyenv-win\versions\3.8.10\lib\smtplib.py", line 444, in ehlo
    self.putcmd(self.ehlo_msg, name or self.local_hostname)
  File "C:\Users\afric\.pyenv\pyenv-win\versions\3.8.10\lib\smtplib.py", line 371, in putcmd
    self.send(str)
  File "C:\Users\afric\.pyenv\pyenv-win\versions\3.8.10\lib\smtplib.py", line 363, in send
    raise SMTPServerDisconnected('please run connect() first')
smtplib.SMTPServerDisconnected: please run connect() first

My settings.py:

from pathlib import Path
import os
from django.contrib import messages
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
MEDIA_DIR = os.path.join(BASE_DIR,'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'd*8x97+1&+ea&x9=*1ay*b6v&lr14u7l*g6*+#b@oummi^&&z^'

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

ALLOWED_HOSTS = []

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'admission',
    'student',
    'course',
    'resultprocessing',
    'studentPreferences',
    'questions',
    'faculty',
    'openpyxl',
    'pandas',
]

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 = 'examProject.urls'

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


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

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


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

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.Argon2PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
]

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


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

LANGUAGE_CODE = 'en-us'

TIME_ZONE =  'Asia/Calcutta'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'examProject/static')
]
STATIC_ROOT = os.path.join(BASE_DIR,'static')

MESSAGE_TAGS = {
    messages.ERROR : 'danger',
}

MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'

EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = os.environ.get('EMAIL_HOST')
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER')
EMAIL_PORT = 587
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')

and my env.bat configuration:

set EMAIL_HOST_PASSWORD=<************>
set EMAIL_HOST_USER=<[email protected]>
set EMAIL_HOST=<smtp-mail.outlook.com>
set DEFAULT_FROM_EMAIL=<[email protected]>

I followed This tutorial for the connections, and this is the Github repo i'm using. Any help and/or suggestions are appreciated!

Edit: Here's the code for actually sending the email incase that would help clarify the problem. I've also changed the email server from Gmail to Outlook since i don't have an administrator account.

 def post(self,request):
        student_form = StudentForm(data=request.POST)
        student_info_form = StudentInfoForm(data=request.POST)
        f_email = request.POST['email'].strip()
        print(f"email: {f_email}")

        if student_form.is_valid() and student_info_form.is_valid():
            student = student_form.save()
            student.set_password(student.password)
            student.is_active = False
            my_group = Group.objects.get_or_create(name='Student')
            my_group[0].user_set.add(student)
            student.save()

            uidb64 = urlsafe_base64_encode(force_bytes(student.pk))
            domain = get_current_site(request).domain
            link = reverse('activate',kwargs={'uidb64':uidb64,'token':account_activation_token.make_token(student)})
            activate_url = 'http://' + domain +link
            email_subject = 'Activate your Exam Portal account'
            email_body = 'Hi.Please use this link to verify your account\n' + activate_url + ".\n\n You are receiving this message because you registered on " + domain +". If you didn't register please contact support team on " + domain 
            fromEmail = '[email protected]'
            email = EmailMessage(
                email_subject,
                email_body,
                fromEmail,
                [f_email],
            )
     
            student_info = student_info_form.save(commit=False)
            student_info.user = student
            if 'picture' in request.FILES:
                student_info.picture = request.FILES['picture']
            student_info.save()
            messages.success(request,"Registered Succesfully. Check Email for confirmation")
            return redirect('login')
        else:
            print(student_form.errors,student_info_form.errors)
            return render(request,'student/register.html',{'student_form':student_form,'student_info_form':student_info_form})

Upvotes: 0

Views: 37

Answers (0)

Related Questions