Problem
I am using zoho's email and would like to send contact form through their smtp server.
But no matter what I tried, it alwasy returns: SMTPServerDisconnected:Connection unexpectedly closed
.
SMTPServerDisconnected
Connection unexpectedly closed
Possible Solutions
I have visited these sites when dealing with this problem:
- Python 2: SMTPServerDisconnected: Connection unexpectedly closed
- Django Sending Email : SMTPServerDisconnected: Connection unexpectedly closed
- "SMTPServerDisconnected: Connection unexpectedly closed" when sending email from Django
- SMTPServerDisconnected: Connection unexpectedly closed
- Send email through Zoho SMTP
- Zoho mail servers reject python smtp module communications
My codes when I have this problem
views.py
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
send_mail(
cd['subject'],
cd['message'],
cd.get('email', '[email protected]'),
['[email protected]'],
)
return HttpResponseRedirect('/contact/thank-you/')
else:
form = ContactForm()
return render(request, 'books/contact_form.html', {'form':form})
settings.py
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.zoho.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = '********'
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
DEFAULT_TO_EMAIL = '[email protected]'
My new codes when problem solved
The only problem is that sender's email in the views.py
is using cd.get('email', '[email protected]')
. When the customer typed his email in the contact form, it will use the customer's email address as the sender's email, thus the connection will be closed. So I have to keep the sender's email consistant to the smtp user account, as shown in the views.py
.
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
# Using send_mail
msg = """
New contact form received!
Path: {}
Name: {}
Suject: {}
Email: {}
Message: {}
""".format(request.path, cd['name'], cd['subject'], cd['email'], cd['message'])
send_mail(
cd['subject'],
msg,
'[email protected]',
['[email protected]',],
)
return HttpResponseRedirect('/contact/thank-you/')
else:
form = ContactForm()
return render(request, 'books/contact_form.html', {'form':form})
No changes in the settings.py
.
Here is what I received after changed the views.py
:
New contact form received!
Path: /contact/
Name: fakename
Suject: this is my subject
Email: [email protected]
Message: Hello, this is the message body.