Send email through Zoho SMTP

Daniel picture Daniel · Aug 20, 2013 · Viewed 13.1k times · Source

I am trying to send email from my django-based website, but I got some problem - SMTPServerDisconnected Connection unexpectedly closed My setting.py:

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.zoho.com'
EMAIL_PORT = 465
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'XXXXXX'

I am using django 1.5.1, python 2.7.3. Anyone can solve this problem?

Thanks for your help

Answer

Brittany picture Brittany · Aug 22, 2013

I'm having the same problem with connection timeouts. It seems to me that there are issues around SSL sockets in the default Django SMTP library. In the development version of Django there is an option to set EMAIL_USE_SSL = True which allows for the use of an implicit TLS connection (as opposed to explicit, which is specified by EMAIL_USE_TLS = True). Generally the former (implicit) uses port 465, while the latter (explicit) uses port 587. See the Django docs -- compare the development version with version 1.5. Note that the option EMAIL_USE_SSL is NOT present in 1.5.

Thus, the problem is that Zoho's default SMTP server uses port 465 and requires SSL, but the EMAIL_USE_TLS option doesn't fulfill this requirement. (Side note: maybe try setting this option to False? I didn't try that.) Anyway, my best guess is that this is a Django-specific issue and may not be solved until 1.7.

As for a solution to your problem: you can definitely access Zoho's SMTP server with Python (2.7.1)'s smtplib (see script below). So, if you want a slightly inelegant fix, you could go that route. I've tested this in Django 1.5.1 and it works like a charm.

Here's the stand-alone Python script (which can be adapted for use in a Django project):

import smtplib
from email.mime.text import MIMEText

# Define to/from
sender = '[email protected]'
recipient = '[email protected]'

# Create message
msg = MIMEText("Message text")
msg['Subject'] = "Sent from python"
msg['From'] = sender
msg['To'] = recipient

# Create server object with SSL option
server = smtplib.SMTP_SSL('smtp.zoho.com', 465)

# Perform operations via server
server.login('[email protected]', 'password')
server.sendmail(sender, [recipient], msg.as_string())
server.quit()

Try checking that the above script runs with your Zoho credentials before plugging it into your web project. Good luck!