Django Sending Email : SMTPServerDisconnected: Connection unexpectedly closed - python

hello i want to sending email activation use django registration redux.
this is my setting.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
ACCOUNT_ACTIVATION_DAYS = 3
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'blahblah#gmail.com'
EMAIL_HOST_PASSWORD = 'blahpassword'
EMAIL_PORT = 465
EMAIL_USE_SSL = True
LOGIN_REDIRECT_URL = '/'
when i try with
python manage.py shell
from django.core.mail import send_mail
send_mail('Test', 'This is a test', 'youremail#gmail.com', ['toemail#gmail.com'])
i am getting error like this:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/apsijogja/djangogirls/myvenv/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 62, in send_mail
return mail.send()
File "/home/apsijogja/djangogirls/myvenv/local/lib/python2.7/site-packages/django/core/mail/message.py", line 286, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/apsijogja/djangogirls/myvenv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 92, in send_messages
new_conn_created = self.open()
File "/home/apsijogja/djangogirls/myvenv/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 50, in open
self.connection = connection_class(self.host, self.port, **connection_params)
File "/usr/lib/python2.7/smtplib.py", line 249, in __init__
(code, msg) = self.connect(host, port)
File "/usr/lib/python2.7/smtplib.py", line 310, in connect
(code, msg) = self.getreply()
File "/usr/lib/python2.7/smtplib.py", line 361, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
SMTPServerDisconnected: Connection unexpectedly closed
can you help me solve this problem?

To use port 465, you need to call smtplib.SMTP_SSL().
Currently, it calls smtplib.SMTP() ..
so,change your PORT from 465 into 587 it
if you want use PORT 465,
your EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_PORT=465
and you need to install django_smtp_ssl
otherwise you can keep,
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_PORT=465

For python3.0+
I found a workaround or maybe this is the solution , there is some issue in the django email package.
1)pip install sendgrid-django
2)Add these in the settings.py along with other email configurations
EMAIL_BACKEND = 'sgbackend.SendGridBackend'
SENDGRID_API_KEY = "YOUR SENDGRID API KEY"
EMAIL_PORT = 465
3)Code sample to send mail(yours maybe different):
from django.core.mail import EmailMessage
send_email = EmailMessage(
subject=subject,
body=body,
from_email=from_email,
to=to_email,
reply_to=reply_to,
headers=headers,
)
send_email.send(fail_silently=fail_silently)
You have to certainly make changes to the code as i was just showing a example.
For debugging purpose only-sendgrid mail send using telnet

Please look into this Link: https://code.djangoproject.com/ticket/9575
and try sending via shell, it should work

In my case using smtplib.SMTP_SSL() solve this problem. You can try this.

Like myself, if your deployed django app is on heroku and using https meaning you need port 465, you should not forget to add these same values below here to your heroku Config Vars. It threw 'connection unexpectedly closed' error untill i had to add this.
# settings.py
EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD')
# replace here with the long SendGrid API secret code
# xyxyxyxyzzzyz on heroku's Config Vars
EMAIL_PORT = 465
EMAIL_USE_SSL = True
Without that, debugging on localhost or development sever will work (with port 587 under http) but not at deployment under port 465 with https

I'm using AWS SES and was having the same problem.
Using port 587 worked for me. Settings were pretty much identical to #User0511

In my case the problem was that I used my api for EMAIL_HOST_PASSWORD.
Then I found my SMPT password by going to https://app.mailgun.com/app/sending/domains/
Clicked on my domain name
Then Selected on SMPT

I was developing and testing on localhost with the Gmail SMTP server and ran into this error. I figured out this was because I was using the EMAIL_PORT = 465 on a EMAIL_USE_TLS = True configuration.
EMAIL_PORT = 465 is an SSL port configuration and is supposed to be used alongside the EMAIL_USE_SSL = True configuration and not on a EMAIL_USE_TLS = True configuration.
So anybody that will run into this issue in the future with same mistake as me should change that and everything should work fine. Below is what the full SMTP configuration looked like for me:
# Email server configuration
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'your_gmail_account#gmail.com'
EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxxxx'
EMAIL_PORT = 465
EMAIL_USE_SSL = True
Also note that using TLS with EMAIL_PORT = 587 and EMAIL_USE_TLS = True didn't work for me on Gmail, so I had to switch to using SSL and it worked.

Normally this is raised because wrong SENDGRID credentials
here you have to use
EMAIL_HOST_USER = 'apikey'

Related

Django Password Recovery via Gmail [Errno 110] Connection timed out

I had a password recovery system via email in my web app, which was working perfectly before deployment. However, now that I have succesfully deployed, password recovery is the only feature that is not working, when solicited it stays loading for some time until the error TimeoutError at /password-reset/ [Errno 110] Connection timed out
Here is my settings.py file email configuration:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_USER = config.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = config.get('EMAIL_PASS')
The credentials are tucked away into config file.
What could be causing this issue?
Does sending emails other than the password reset work? If yes, what kind of email?
What platform is the app deployed on?
What service are you using to send emails?
I added the port to my UFW firewall with sudo ufw allow 587. Also since I deployed through Linode (they currently have port 587 blocked for all users to prevent spam) I had to contact Linode Support, who then lifted the ban of port 587 on my Linode.

How to send a mail using gmail in Django 1.10 on windows [duplicate]

I registered a domain and a private email using namecheap.com. I am trying to send an email from this private email. However, I get the error in the title.
In my settings.py, I have these settings:
EMAIL_HOST = 'mail.privateemail.com'
EMAIL_HOST_USER = 'contact#mysite.com'
EMAIL_HOST_PASSWORD = 'my password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
And I am trying to send the email through a view:
send_mail(
'Subject here',
'Here is the message.',
'contact#mysite.com',
['myname#gmail.com'],
fail_silently=False,
)
However, I get this error:
SMTPException at /
STARTTLS extension not supported by server.
Any idea why? Any help is appreciated.
EDIT
After changing the EMAIL_USE_TLS to False, and also removing it to check both separately, I get this error now:
SMTP AUTH extension not supported by server.
Any idea why? Thanks!
your server mail.privateemail.com does not know what is STARTTLS SMTP Commnad is
this may happen in two cases:
your server (mail.privateemail.com) do not support secure communication at all and you need to use plain, non-encrypted communication.
you are trying to connect to the port that is already using SSL as the communication, then STARTTLS to upgrade connection to secure make no sense whatsoever.
your server is configured improperly and ignores STARTTLS on submission port (587).
Judging, that you are connecting to port 587 which should provide plain communication - it's either 1 or 3.
If you want this just work, remove EMAIL_USE_TLS = True or set it to False, otherwise - SMTP server configuration should be fixed.
You may try SSL instead of TLS by making following changes in settings.py
EMAIL_USE_SSL = True
EMAIL_PORT = 465
hope that helps
Either setup TLS on your mail server or use EMAIL_USE_TLS = False.
I am able to resolve the issue with modifying below line of code, by adding port number with server name:
server = smtplib.SMTP('mail.mycompany.com:587')
Not sure if you have solved the problem yet. I also recently try the 2-month free private email package from NameCheap. Here is my code and it works for me as of Jan 2018:
import smtplib
from email.message import EmailMessage
fromaddr = 'account#yourdomain.com'
toaddrs = "recipient#somedomain.com"
SMTPServer = 'mail.privateemail.com'
port = 465 #587
login = "account#yourdomain.com"
password = "password"
msg = EmailMessage()
msgtxt = "http://www.google.com"+"\n\n"+"This is a test."
msg.set_content(msgtxt)
msg['Subject'] = "Test message"
msg['From'] = fromaddr
msg['To'] = toaddrs
server = smtplib.SMTP_SSL(SMTPServer, port) #use smtplib.SMTP() if port is 587
#server.starttls()
server.login(login, password)
server.send_message(msg)
server.quit()
Hope this help!
PS. You can also use port 587, but you have to use smtplib.SMTP() instead of smtplib.SMTP_SSL(), and also have to un-comment the server.starttls() line.

Django: Outlook email smtp timeout in production server

i'm trying to send a SMTP email from Django, using my credentials of Outlook. My code works in localhost, but when I upload my code to production server, it doesn't.
If I use my Gmail credential, it also works in production, but it doesn't with Outlook. So, I think Outlook is configured in a different way, but I dont know.
This is my view code:
def send_my_custom_email():
connection = mail.get_connection(
host = 'smtp-mail.outlook.com',
port = 25,
username = 'myemail#outlook.com',
password = 'mypassword' ,
)
connection.open()
email2send = mail.EmailMessage('hello', 'hello', 'myemail#outlook.com', to=['receiveremail'], connection=connection)
email2send.send()
connection.close()
I know that my configuration setting are right because it can send emails from localhost. These are my settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
I already try to check the Outlook settings, but I couldn't find anything about SMTP use.
My exact questions are:
Outlook need aditional settings in production?
The problem is in my code or in Outlook settings?
Why it works in localhost but it does not in production server?
Outlook.com only allows encrypted SMTP TLS connections on port 587. It does not even listen on port 25, that is why you get a timeout.

Django SMTPServerDisconnected: Connection unexpectedly closed using Postfix on Centos

I have installed Postfix on Centos 7 and have successfully configured it to send mail (tested with command line program MailX).
However, when trying to send mail through Django shell or my Django website I am getting:
File "/usr/lib64/python2.7/smtplib.py", line 367, in getreply
raise SMTPServerDisconnected("Connection unexpectedly closed")
SMTPServerDisconnected: Connection unexpectedly closed
My mail configuration in settings.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
EMAIL_USE_TLS = False
DEFAULT_FROM_EMAIL = 'Admin <admin#mywebsite.com>'
Any ideas?
Maillog highlighted:
fatal: no SASL authentication mechanisms
Resolved with:
yum install cyrus-sasl-plain

Send email via Python/django on 1&1

I am developing a website with django framework. And I recently tried to release it on a 1&1 shared hosting.
I managed to make the project run well, except for one last “detail”: I can't send email from django.
I tried almost everything in settings (different emails, ports, etc.), but each time I got a beautiful '500 Internal Server Error' =/ (whereas it went fine on a free alwaysdata server)
In order to find the origin of this issue, I tried different things:
to test send_mail and EmailMessage via the python interpreter:
>>> send_mail('a subject', 'a test message', 'mymail#gmail.com', ['mymail#gmail.com'])
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: a subject
From: mymail#gmail.com
To: mymail#gmail.com
Date: Tue, 14 Jan 2014 22:12:48 -0000
Message-ID: <20140114221248.6718.86150#infong-fr25.kundenserver.de>
a test message
-------------------------------------------------------------------------------
1
But... I got nothing in my inbox.
My settings being:
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
DEFAULT_FROM_EMAIL = 'mymail#gmail.com'
EMAIL_HOST_USER = 'mymail#gmail.com'
EMAIL_PORT = 587
to connect to an SMTP server via the python interpreter:
./manage.py shell
>>> from smtplib import SMTP
>>> smtp_conn = SMTP()
>>> smtp_conn.connect('smtp.gmail.com', 25)
And nothing happens (I tried it with auth.smtp.1and1.fr, or port 587...); when I interrupt the process, it tells me:
^CTraceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.6/smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/lib/python2.6/smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "/usr/lib/python2.6/socket.py", line 554, in create_connection
sock.connect(sa)
File "<string>", line 1, in connect
KeyboardInterrupt
to test with a php file:
With a basic:
<?php
if (mail("mymail#gmail.com", "a subject", "a test")) {
echo("<p>Email successfully sent!</p>");
}
else {
echo("<p>Email delivery failed…</p>");
}
?>
And the mail was sent! So, it seems that without SMTP connection, it is possible (at least, via php).
Conclusion
So, my questions are: do you think I can manage to correct this bug, and otherwise is it possible to send mail without smtp connection ("like php")?
1and1 does not allow SMTP within 1and1. To send an email when running on 1and1...
#!/usr/bin/python
import os
mail_to = "sam#comcast.net"
mail_from = "steve#example.com"
subject = "test message"
header = """From: {0}
To: {1}
Subject: {2}
""".format(mail_from, mail_to, subject)
msg = header + "a test from me"
sendmail = os.popen("/usr/lib/sendmail -t", "w")
sendmail.write(msg)
sendmail.close()
The blog post linked shows an example that sends mail using SMTP through 1and1 via an external machine. Perhaps you can override Django's send_mail (or maybe this gives you [or someone else] a hint as to why it doesn't work.) This should allow you to send email in the Python interpreter, anyway.
Source: https://flenniken.net/blog/send-email-using-python-and-1and1/

Categories