Home > Blockchain >  Django email backed error brings socket error on smtp but send to console successful
Django email backed error brings socket error on smtp but send to console successful

Time:06-13

I tried to send email via django Email message for account mail verification. When I send email via to console it send the activation link successfully but when it comes to sending via smtp I get TypeError: getaddrinfo() argument 1 must be string or none

Token generator

from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six
class TokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return (
six.text_type(user.pk) six.text_type(timestamp)
six.text_type(user.is_active)
)
account_activation_token = TokenGenerator()

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class SignupForm(UserCreationForm):
email = forms.EmailField(max_length=200, help_text='Required')
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password

"""

Django settings for project.


   import os
    from pathlib import Path
    
    from django.contrib.messages import constants as messages
    
    
    MESSAGE_TAGS = {
            messages.DEBUG: 'alert-secondary',
            messages.INFO: 'alert-info',
            messages.SUCCESS: 'alert-success',
            messages.WARNING: 'alert-warning',
            messages.ERROR: 'alert-danger',
     }
    
    # 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/3.1/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = ''
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'dashboard.apps.DashboardConfig',
        'user.apps.UserConfig',
        'crispy_forms',
    ]
    
    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 = 'inventoryproject.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [BASE_DIR / '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',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'inventoryproject.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/3.1/ref/settings/#databases
    
    # DATABASES = {
    #     'default': {
    #         'ENGINE': 'django.db.backends.mysql',
    #         'NAME': 'inventory',
    #         'USERNAME': 'root',
    #         'HOST': 'localhost',
    #         'PORT': 3306,
    #         'PASSWORD': '',  # Your Password
    #     }
    # }
    #
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/3.1/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/3.1/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    CRISPY_TEMPLATE_PACK = 'bootstrap4'
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/3.1/howto/static-files/
    
    STATIC_URL = '/static/'
    
    MEDIA_ROOT = (BASE_DIR/"media/")
    
    MEDIA_URL = '/media/'
    
    STATICFILES_DIRS = [
        BASE_DIR / "static",
    ]
    
    STATIC_ROOT = (BASE_DIR/"asert/")
    
    LOGIN_REDIRECT_URL = 'dashboard-index'
    
    LOGIN_URL = 'user-login'
    
    # if DEBUG:
    #     EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
    #
    # else:
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_USE_TLS = True
    EMAIL_HOST = 'smtp.gmail.com',
    EMAIL_HOST_USER = '[email protected]',
    EMAIL_HOST_PASSWORD = 'password1',
    EMAIL_PORT = 587









def register(request):
    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user = form.save()
            group = Group.objects.get(name='Customers')
            user.groups.add(group)
            current_site = get_current_site(request)
            mail_subject = "Activate your account."
            message = {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': account_activation_token.make_token(user),
            }
            message = get_template('acc_active_email.html').render(message)
            to_email = form.cleaned_data.get('email')
            print(to_email)
            email = EmailMessage(mail_subject, message, to=[to_email])
            email.content_subtype = "html"
            import socket
            socket.getaddrinfo('localhost', 25)
            email.send()

error

TypeError at /register/
getaddrinfo() argument 1 must be string or None
Request Method: POST
Request URL:    http://127.0.0.1:8000/register/
Django Version: 3.2
Exception Type: TypeError
Exception Value:    
getaddrinfo() argument 1 must be string or None
Exception Location: C:\Users\ACME\AppData\Local\Programs\Python\Python39\lib\socket.py, line 954, in getaddrinfo
Python Executable:  C:\Users\ACME\Desktop\inventory\inventory\real\Scripts\python.exe
Python Version: 3.9.10
Python Path:    
['C:\\Users\\ACME\\Desktop\\inventory\\inventory',
 'C:\\Users\\ACME\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
 'C:\\Users\\ACME\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
 'C:\\Users\\ACME\\AppData\\Local\\Programs\\Python\\Python39\\lib',
 'C:\\Users\\ACME\\AppData\\Local\\Programs\\Python\\Python39',
 'C:\\Users\\ACME\\Desktop\\inventory\\inventory\\real',
 'C:\\Users\\ACME\\Desktop\\inventory\\inventory\\real\\lib\\site-packages']
Server time:    Sat, 11 Jun 2022 18:13:49  0000

CodePudding user response:

Well, you know that , changes string to tuple? Just delete it :)

EMAIL_HOST = 'smtp.gmail.com',
EMAIL_HOST_USER = '[email protected]',
EMAIL_HOST_PASSWORD = 'password1',

# should look like this:

EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password1'

And I think you will be good to go (I assume that you created app_password in Google account as changes came since 01.06 this year and it's not account passowrd)

  • Related