[Django]-Django- Try sending email in python shell using send_mail(), but cannot work

2👍

Hy, I’ve tried asking and this can successfully send email without any setting in the settings.py

first, add these two imports

import smtplib
from email.mime.text import MIMEText as text

then the code to send email could be like this

def send_email(sender,receiver,message,subject):
    sender = sender
    receivers = receiver
    m = text(message)
    m['Subject'] = subject
    m['From'] = sender
    m['To'] = receiver

   # message = message

    try:
       smtpObj = smtplib.SMTP('localhost')
       smtpObj.sendmail(sender, receivers, str(m))
       print "Successfully sent email"
    except SMTPException:
       print "Error: unable to send email" 

This works just as expected.

👤Mona

2👍

I’m going to go ahead and say that the mail is probably being sent, but it is hitting your spam filter.

Unless you have something other than django.core.mail.backends.smtp.EmailBackend set as your settings.EMAIL_BACKEND, you will only get a return of True (or 1) if the backend has successfully connected to the server and told the server to send the message. If fail_silently=False, that means that send_mail will either return True or raise an exception. This means that the error either lies in your SMTP or it is being sent directly to “spam”.

But, in the off chance that you have already checked spam, there are ways to make an SMTP server fail silently. Check out this article for Sendmail (one of the most common *nix applications), or this one for Mercury (one of the SMTP servers available for Windows). If you’re using IIS, this site looks like it addresses some potential issues.

Leave a comment