Search code examples
pythondjangosocketspythonanywhere

IMAP4 not working on python anywhere server but same code works on localhost


I want to user to login in my django web app using our institute mail server. But this code allow to login using institute mail on localhost but not on server.

I tried on pythonanywhere django provided shell:

from imaplib import IMAP4
c = IMAP4('newmailhost.cc.iitk.ac.in')

error comes in web server but not in local host shell..

socket.gaierror: [Errno -2] Name or service not known

In mylib/backend.py

from django.contrib.auth.models import User
from imaplib import IMAP4

class MyCustomBackend:

# Create an authentication method
# This is called by the standard Django login procedure
    def authenticate(self, username=None, password=None):
        try:
        # Check if this user is valid on the mail server
            c = IMAP4('newmailhost.cc.iitk.ac.in')
            c.login(username, password)
        except:
            return None

        user, created = User.objects.get_or_create(username=username)

        return user

# Required for your backend to work properly - unchanged in most scenarios
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

in setting.py

AUTHENTICATION_BACKENDS = (
    'mylib.backend.MyCustomBackend',
    'django.contrib.auth.backends.ModelBackend',

)

Solution

  • That DNS name doesn't resolve to an address from what I can see. So my guess is that it's a private server that doesn't exist outside of your network.