I want to send email in Django application using Outlook's SMTP server. The problem is, I get SSL wrong version number error every time I'm trying to send a message.
Error traceback:
Traceback (most recent call last):
File "F:\Development\Python\lib\smtplib.py", line 366, in getreply
line = self.file.readline()
File "F:\Development\Python\lib\socket.py", line 297, in readinto
return self._sock.recv_into(b)
File "F:\Development\Python\lib\ssl.py", line 453, in recv_into
return self.read(nbytes, buffer)
File "F:\Development\Python\lib\ssl.py", line 327, in read
v = self._sslobj.read(len, buffer)
ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1450)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "F:\Development\Python\lib\site-packages\django\core\handlers\base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "E:\SkyDrive\Repositories\web\skyproject\views.py", line 13, in index
email.send()
File "F:\Development\Python\lib\site-packages\django\core\mail\message.py", line 255, in send
return self.get_connection(fail_silently).send_messages([self])
File "F:\Development\Python\lib\site-packages\django\core\mail\backends\smtp.py", line 88, in send_messages
new_conn_created = self.open()
File "F:\Development\Python\lib\site-packages\django\core\mail\backends\smtp.py", line 55, in open
self.connection.login(self.username, self.password)
File "F:\Development\Python\lib\smtplib.py", line 621, in login
AUTH_PLAIN + " " + encode_plain(user, password))
File "F:\Development\Python\lib\smtplib.py", line 398, in docmd
return self.getreply()
File "F:\Development\Python\lib\smtplib.py", line 370, in getreply
+ str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1450)
This is my SMTP configuration in 'settings.py':
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.live.com'
EMAIL_HOST_USER = 'my_email#outlook.com'
EMAIL_HOST_PASSWORD = 'my_password'
EMAIL_PORT = 587
And this is how messages being sent:
from django.core.mail import EmailMessage
email = EmailMessage('Test', 'Test', to=['email_address#example.com'])
email.send()
I have no idea why I get this error. As far as I know, there are no SSL_VERSION parameter in Django settings.
If it is important, my interpreter's version is 3.3.2, and Django's version is 1.5.2.
Try these settings for OutLook:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_HOST_USER = "youremail#outlook.com"
EMAIL_HOST_PASSWORD = "yourpassword"
I got it working with the following settings:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_HOST_USER = 'myemail#outlook.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 25
I had a very similar issue. I was getting following error message:
SMTPServerDisconnected: Connection unexpectedly closed
The solution was to:
Login to the e-mail address via web interface available at www.outlook.com
Verify my account by providing MS with my phone number and typing back the received SMS.
After this I can nicely send e-mails from Django.
I am getting an error while sending a Django email using outlook, did you send it successfully recently?
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_PORT = 995
EMAIL_USE_TLS = True
EMAIL_HOST = 'outlook.office365.com'
EMAIL_HOST_USER = '********#*******'
EMAIL_HOST_PASSWORD = '************'
EMAIL_FROM_ADDRESS='*****#******'
EMAIL_ENCRYPTION='STARTTLS'
DEFAULT_FROM_EMAIL ='*****#********'
Due to the cancellation of Gmail's less secure apps, I tried outlook. Here is the code:
# setting.py
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_HOST_USER = "your_account#outlook.com"
EMAIL_HOST_PASSWORD = "password"
You could test it in shell:
python manage.py shell
>>> from django.core.mail import send_mail
>>> send_mail("TEST","THis is a test","your_account#outlook.com",["another_account#gmail.com"],fail_silently=False)
Related
I have a problem when sending an email using Django as the email I'm trying to send from is hosted on domain.com, I've tried to send from Gmail and it worked fine but when I use the configuration of domain.com it gives me this error: smtplib.SMTPHeloError: (501, b'Syntactically invalid HELO argument(s)')
what I understand is that it is related to the host name, but I don't know what to do to fix that error and can I use a different hostname for domain.com that works. below is the configuration in setting.py and send_mail function:
setting.py:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.domain.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'Name#emailFrom.com'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False
EMAIL_HOST_PASSWORD = "********"
send_mail function:
send_mail(
'HR Request',
'your request is being processed',
'Name#emailFrom.com',
['Name#emailTo.com'],
fail_silently=False,
)
return HttpResponse('Mail sent')
Previously, I was using SendGrid to serve emails using Django's SMTP backend, which worked perfectly fine. However, now I would like my project to use Microsoft Exchange. When I updated my SMTP configuration in settings.py, upon the submission of some form to be emailed, the page timesout when trying to reach the server: TimeoutError: [Errno 60] Operation timed out.
settings.py
# E-Mail
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.microsoft365.com'
EMAIL_HOST_USER = 'username#domain.com'
EMAIL_HOST_PASSWORD = 'password'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
views.py
# Send email
send_mail('!!New Mail!! ', content, 'noreply#domain.com', ['username#domain.com'], fail_silently=False)
I solved my problem when I used the correct SMTP port (25, 465, 587) for my particular mail server.
settings.py
EMAIL_PORT = 25
I am getting the below error while trying to use Django sendmail using Outlook SMTP
SMTPDataError at /distribute/
(554, '5.2.0 STOREDRV.Submission.Exception:SendAsDeniedException.MapiExceptionSendAsDenied;
Failed to process message due to a permanent exception with message
Cannot submit message. 16.55847:0C0F0000,
17.43559:0000000094000000000000000000000000000000, 20.52176:140F0E852800101064010000, 20.50032:140F0E858817101069010000, 0.35180:0A00E781, 255.23226:6E010000, 255.27962:0A000000, 255.27962:0E000000, 255.31418:0A000000, 16.55847:86000000, 17.43559:0000000068010000000000000000000000000000, 20.52176:140F0E85280010100A00F736, 20.50032:140F0E85881710100A00F836, 0.35180:8C010000, 255.23226:40000730, 255.27962:0A000000, 255.27962:32000000, 255.17082:DC040000, 0.27745:0A001780, 4.21921:DC040000, 255.27962:FA000000, 255.1494:A4010000, 0.37692:05000780, 0.37948:00000000, 5.33852:00000000534D545000000780, 4.56248:DC040000, 7.40748:010000000000010B05000780, 7.57132:000000000000000005000780, 1.63016:32000000, 4.39640:DC040000, 8.45434:824D851FB0676A47B811311E3F17990F00000000, 5.10786:0000000031352E32302E313239342E3032343A5455345052383430314D42303436323A34333038323065332D393530612D346435362D383863332D3037363837616130336664330005000780,
255.1750:0A008984, 255.31418:41010000, 0.22753:0A001986, 255.21817:DC040000, 4.60547:DC040000, 0.21966:4B010000, 4.30158:DC040000 [Hostname=TU4PR8401MB0462.NAMPRD84.PROD.OUTLOOK.COM]')
My settings are as below:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp-mail.outlook.com'
EMAIL_HOST_USER = '********'
EMAIL_HOST_PASSWORD = '********'
EMAIL_PORT = 587
Please help
I had an error similar to yours, and I resolved it as follows, two points that I think you have to pay attention to are:
EMAIL_HOST normally email hosts have this format ** smtp.nameserver.com **, example:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.outlook.com'
EMAIL_HOST_USER = '********'
EMAIL_HOST_PASSWORD = '********'
EMAIL_PORT = 587
When sending the email, the send_mail method has to send the email from an address in your domain, example:
from django.core.mail import send_mail
send_mail(
'Subject here',
'Here is the message.',
'from#outlook.com', # pay attention here I had a problem because of that
['to#example.com'],
fail_silently=False,
)
Settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER = 'no_reply#domain.com'
SERVER_EMAIL = 'no_reply#domain.com'
DEFAULT_DO_NOT_REPLY = 'User <no_reply#domain.com>'
EMAIL_HOST_PASSWORD = 'xxxxxxxxx'
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
Class
class EmailThread(threading.Thread):
def __init__(self, subject, context, recipient, template):
self.subject = subject
self.recipient = recipient
self.message = get_template(template).render(context)
threading.Thread.__init__(self)
def run(self):
msg = EmailMessage(
subject=self.subject,
from_email=settings.DEFAULT_DO_NOT_REPLY,
to=self.recipient,
body=self.message
)
msg.content_subtype = "html"
try:
msg.send(fail_silently=False)
log.info("E-mail triggered. Subject: '%s', to: %s" % (self.subject, self.recipient))
except Exception as e:
log.exception(e)
Usage
def notify_admin_blocked_account(user):
"""
Sends sends an email when the account is blocked
:return:
"""
email = EmailThread(
subject='{}, your account has been blocked'.format(user),
context={
'user': user,
'login_attempts': settings.MAX_STAFF_PWD_ATTEMPTS,
},
recipient=[user.email,],
template='mail/notify_admin_blocked_account.html'
)
email.start()
Error
[ERROR][2017-08-01 10:40:26,835][mail] EOF occurred in violation of protocol (_ssl.c:645)
Traceback (most recent call last):
File "./bin/mail.py", line 27, in run
msg.send(fail_silently=False)
File "/home/web/sites/envs/project/lib/python3.5/site-packages/django/core/mail/message.py", line 348, in send
return self.get_connection(fail_silently).send_messages([self])
File "/home/web/sites/envs/project/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 104, in send_messages
new_conn_created = self.open()
File "/home/web/sites/envs/project/lib/python3.5/site-packages/django/core/mail/backends/smtp.py", line 69, in open
self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile)
File "/usr/lib/python3.5/smtplib.py", line 766, in starttls
server_hostname=self._host)
File "/usr/lib/python3.5/ssl.py", line 377, in wrap_socket
_context=self)
File "/usr/lib/python3.5/ssl.py", line 752, in __init__
self.do_handshake()
File "/usr/lib/python3.5/ssl.py", line 988, in do_handshake
self._sslobj.do_handshake()
File "/usr/lib/python3.5/ssl.py", line 633, in do_handshake
self._sslobj.do_handshake()
ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:645)
I have some weird behavior when I try to send an e-mail (async) with Django. I really wanted to avoid third-party apps being installed to reduce code fragmentation - specially with some of them that seem to use crontab.
It is worth noticing that the error doesn't happen all the time. However, even though it doesn't happen, sometimes e-mails are not sent either. Only some of them manage to go through.
On my development environment it runs fine, and I can send the e-mails. However, on my production environment (EC2 instance) it simply doesn't work.
If I trigger an e-mail through the normal process, it is not sent. If I login to the server, open the manage.py shell, import a project and call the function that sends e-mail, sometimes I receive both triggered and manually-triggered e-mails or get an error (the one bellow).
My solution was to use Django-Mailer. It fragments the project, something I wanted to avoid, but its usage is pretty minimalist.
I use django-registration for my project to manage user registration, login, etc. But When I sign up for an account I came across this problem:
SMTPServerDisconnected
For the record, I did configure email related settings in my settings.py:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 465
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
Also I have all the templates needed and accessible. So this problem doesn't have anything to do with that.
More Error description:
After I click on the send activation email, it takes a long time before it finally give that error.
Here is the traceback (not complete):
SMTPServerDisconnected at /accounts/register/
Connection unexpectedly closed
last trace back:
/usr/lib/python2.7/smtplib.py in getreply
line = self.file.readline()
except socket.error as e:
self.close()
raise SMTPServerDisconnected("Connection unexpectedly closed: "
+ str(e))
if line == '':
self.close()
raise SMTPServerDisconnected("Connection unexpectedly closed")
...
if self.debuglevel > 0:
print>>stderr, 'reply:', repr(line)
resp.append(line[4:].strip())
code = line[:3]
# Check that the error code is syntactically correct.
# Don't attempt to read a continuation line if it is broken.
Thanks for any suggestion.
I think at least one setting is incorrect. Port 587 is required for TLS [1]
EMAIL_PORT = 587
[1] http://support.google.com/mail/bin/answer.py?hl=en&answer=13287
Finally I figured this out. I post my solution here in case someone else get stuck here. The problem is the Gmail port. Use 587 and it worked.
I saw it here: https://code.djangoproject.com/ticket/9575
I wonder why some people can use 465 and some can't. It cost me a few hours to find out. Hope your guys won't!
EDIT: See here for more dicussion about use of port.
To use port 465, you need to call smtplib.SMTP_SSL(). Currently, it looks like Django only uses smtplib.SMTP().
Seems 587 is the right choice.
Meanwhile, you might want to check https://github.com/bancek/django-smtp-ssl
Django Gmail Confi # settings.py
EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_SSL = True # use port 465
EMAIL_USE_TLS = False # use port 587
EMAIL_PORT = 465 # OR 587
EMAIL_HOST_USER = os.environ.get('USER_EMAIL')
EMAIL_HOST_PASSWORD =os.environ.get('USER_EMAIL_PASS')
helper.py (function)
from django.core.mail import send_mail
def send(sub=None,message=None,recipient=[]):
# def send_mail(
# subject,
# message,
# from_email,
# recipient_list,
# fail_silently=False,
# auth_user=None,
# auth_password=None,
# connection=None,
# html_message=None):
send_mail(subject='contact mail'
,message='Test Mail'
,from_email=EMAIL_HOST_USER
,recipient_list=['mail_list']
,fail_silently=False)
return True
If you are not having any luck with the above answers, you may want to check to see if you have set your DEFAULT_FROM_EMAIL in the settings.py
# project/settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 465
EMAIL_USE_TLS = True
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'
DEFAULT_FROM_EMAIL = 'myemail#gmail.com'