Is this code correct to send email (django)?

Viewed 88

Test.py

email = EmailMessage()
email['from'] = 'Your Name'
email['to'] = 'name@gmail.com'
email['subject'] = 'Welcome to 
Ourr Website!'

email.set_content("Hope You are 
doingg great.")

with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.login('example@gmail.com', 'password: ********') 
    smtp.send_message(email)
    print("Done")

When I execute I'm getting timeout error(10060). Can any one help?

1 Answers

For emails, you will need to specify:

EMAIL_HOST 
EMAIL_USE_TLS
EMAIL_PORT
EMAIL_HOST_USER
EMAIL_HOST_PASSWORD

(If you're using Gmail for sending Django emails, you will need to allow less secure access. More info on my answer here)

I'm going to paste a block of code that I reuse in all my projects. Feel free to customize it to your benefit.

from django.core.mail import send_mail, EmailMultiAlternatives
from django.template.loader import get_template

def send_email(email, subject, msg, username):
    message = EmailMultiAlternatives(subject=subject, body=msg, from_email='email@gmail.com', to=[email])
    html_templ = get_template("app/email.html").render({'email':email,'username': username})
    message.attach_alternative(html_templ, "text/html")
    message.send()
    print("email sent")
Related