Forums

Django email feature is not working in production, but worked in development

I want to send an email to my users who added a hotel or booked a hotel on mysite. It successfully worked in development , but not working in production, i don't know what is the reason, It was not throwing any error at all, Please help me on this issue.Here is my settings code

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_PORT = 587

EMAIL_HOST_USER = 'mygmail@gmail.com'

EMAIL_HOST_PASSWORD = 'my_account_password'

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

Did you checkout our help pages on using smtp with free accounts?

yeah, but didn't find any clues, please help me regarding this issue

Check out the section on app-specific passwords at the end of the help page. Google have stricter security rules for access from cloud service providers than they do for computers accessing the Internet via normal ISPs. If you use an app-specific password (which is a different password to the one you normally use to access your Gmail account) then things normally work better.

I already done that but still no progress

Wait- I just noticed that you said that your code is not throwing any errors. What is the endpoint you hit to send an email, and or have you tried sending out an email from the console? (eg: from a manage.py shell)

I didn't understand your point, In the error log and server log , i didn't see any errors regarding email.Sending out an email from console ? The email will be sent when the particular view is called. I didn't understand your point, what can i say is that email feature works perfectly on local host

The communication gap is so long between us , in which you can't understand my problem

Django has the ability for you to run your code from inside a console, using python manage.py shell -- this will load your Django code up, and allow you to run code interactively. So if you do that from a bash console, you can try sending email from there, for example:

from django.core.mail import send_mail

send_mail(
    'Subject here',
    'Here is the message.',
    'from@example.com',
    ['to@example.com'],
    fail_silently=False,
)

...changing the from@example.com and to@example.com to addresses you own, of course.

That will hopefully print out more information than would normally be written to the error or server log, which might help debug the issue.

Traceback (most recent call last): File "<stdin>", line 6, in <module>

File "/usr/local/lib/python2.7/dist-packages/django/core/mail/init.py", line 56, in send_mail fail_silently=fail_silently,

File "/usr/local/lib/python2.7/dist-packages/django/core/mail/init.py", line 36, in get_connection klass = import_string(backend or settings.EMAIL_BACKEND)

File "/usr/local/lib/python2.7/dist-packages/django/conf/init.py", line 53, in getattr self._setup(name)

File "/usr/local/lib/python2.7/dist-packages/django/conf/init.py", line 39, in _setup % (desc, ENVIRONMENT_VARIABLE))

django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environmen

t variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

This is the error i got in console when i tried above code

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_PORT = 587

EMAIL_HOST_USER = 'euphoriareservation@gmail.com'

EMAIL_HOST_PASSWORD = 'My_password'

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

This is my settings file, I configured well, i don't know where is the problem

How did you start your console? Did you use python manage.py shell?

I was unable to start the shell , I am getting some syntax errors

What version of python are you expecting your code to run with? And if they are your syntax errors, then you should fix them?

I am running python 3.6 , and i am getting error like this

python manage.py shell File "manage.py", line 14
) from exc
^
SyntaxError: invalid syntax

ok- so did you look into why there is a syntax error there?

How could i figure it out?

Well a good step would be taking a look at the file, and seeing if there is an obvious syntax error.

It is a configuration file which was ]generated by the system, how can i Change that file , If i change it will lead to unexpected errors, which downs my site .

 #!/usr/bin/env python

  2 import os

  3 import sys
  4 
  5 if __name__ == "__main__":

  6     os.environ.setdefault("DJANGO_SETTINGS_MODULE", "euphoria.settings")

  7     try:

  8         from django.core.management import execute_from_command_line

  9     except ImportError as exc:

 10         raise ImportError(

 11             "Couldn't import Django. Are you sure it's installed and "

 12             "available on your PYTHONPATH environment variable? Did you "

 13             "forget to activate a virtual environment?"

 14         ) from exc

 15     execute_from_command_line(sys.argv)

It was the configuration file , i am getting error there in line 14 ,when i tries to start the shell don't know why?

[edit by admin: formatting]

it certainly seems like you had added the "from exc" words into the document and saved it.

No, I didn't added anything , since it is system generated file , I didn't touched it

Well you should probably take out "from exc"

Is it safe ? since it is system generated file

I think Conrad was incorrect with his suggestion above. What you need to do is run manage.py with the version of Python that you generated it for. Because you're using a virtualenv, the easiest way to do that is to click on the "Start a console in this virtualenv" link on the "Web" page, then to run python manage.py shell there.

I have the exact same problem and from above I can't understand what to do. Please Help.
My problem is - When I write
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587...
these lines in the settings.py file , it gives me Syntax error and on bash also it gives errors.
And without these, anything I write in the views or any file , nothing would work.
Thanks in advance

is that ... in there?

No .. But I guess it's a free account so it is not allowing This SMTP email service. Is it ???

Yes. Free accounts can only use gmail to send SMTP emails: https://help.pythonanywhere.com/pages/SMTPForFreeUsers/

hello i fave error "No module named 'django.core.mail.backend' " please help me

You're probably trying to run code for one version of Django with a different version of Django. Make sure that you are using the version of Django that your code was written for.

const sendToServer = (url, formData) => { const data = Object.fromEntries(formData.entries()); let options = { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }; return new Promise((resolve, reject) => { fetch(url, options) .then((resp) => resp.json()) .then((res) => resolve(res)) .catch((err) => reject(err)); }); };

const handleFormSubmit = (e) => { e.preventDefault(); console.log("form submitted");

const form = e.currentTarget;
const url = "http://127.0.0.1:8000/api/mail/save_user/";  //getting error in this part what should i change

There is nothing listening on 127.0.0.1:8000. You will need to find the address of the service that you're actually trying to connect to.

email not getting please solve it

settings.py

EMAIL_HOST='smtp.office365.com'
EMAIL_HOST_USER='xxxxxxxxx'
EMAIL_HOST_PASSWORD='xxxxxxxx'
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend'

views.py:

class EmailThread(threading.Thread):
    def __init__(self,email_message):
        self.email_message=email_message
        threading.Thread.__init__(self)
    def run(self):
        self.email_message.send()
def signup(request):
     if request.method == 'POST':
        first_name=request.POST['fname']
        last_name=request.POST['lname']
        email=request.POST.get('email')
        password1=request.POST.get('password1')
        password2=request.POST.get('password2')
        if password1 != password2:
            messages.error(request,"Password do not Match,Please Try Again!")
            return redirect('/foodauth/signup')
        try:
            if User.objects.get(username=email):
                messages.warning(request,"Email Already Exists")
                return redirect('/foodauth/signup')
        except Exception as identifier:
            pass
        try:
            if User.objects.get(mobile_number=mobile_number):
                messages.warning(request,"Mobile number is Already Exists")
                return redirect('/foodauth/signup')
        except Exception as identifier:
            pass
        try:
            if User.objects.get(email=email):
                messages.warning(request,"Email Already Exists")
                return redirect('/foodauth/signup')
        except Exception as identifier:
            pass
        # checks for error inputs
        user = User.objects.create_user(email,email,password1)
        user.first_name = first_name
        user.last_name = last_name
        user.is_active=True
        user.save()
        cuurrent_site=get_current_site(request)
        email_subject="Activate your account"
        message=render_to_string('auth/activate.html',{
            'user':user,
            'domain':'2100031674cse.pythonanywhere',
            'uid':urlsafe_base64_encode(force_bytes(user.pk)),
            'token':generate_token.make_token(user)
        })
        email_message=EmailMessage(email_subject,message,settings.EMAIL_HOST_USER,[email],)
        EmailThread(email_message).start()
        messages.info(request," Activate your account in mail bor(check spam)")
        return redirect('/foodauth/login')
     return render(request,'auth/register.html')

If you want to use email on a free account, have a look at this help page.