这个代码发送电子邮件(django)正确吗



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")

当我执行时,我得到超时错误(10060(。有人能帮忙吗?

对于电子邮件,您需要指定:

EMAIL_HOST 
EMAIL_USE_TLS
EMAIL_PORT
EMAIL_HOST_USER
EMAIL_HOST_PASSWORD

(如果你使用Gmail发送Django电子邮件,你需要允许不太安全的访问。更多信息请点击此处了解我的答案(

我将粘贴一块代码,以便在我的所有项目中重复使用。欢迎根据您的利益进行定制。

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")

最新更新