使用Django和Python从gmail发送电子邮件

时间:2016-11-17 17:13:25

标签: python django email smtp gmail

我发现很多关于使用django发送电子邮件的帖子,但我对gmail有一个特定的问题:

error image

这是我的设置:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_USER = "myemail@gmail.com"
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = 'mypassword
EMAIL_PORT = 587
EMAIL_USE_TLS = True

我的观点是:

from django.core.mail import EmailMessage, send_mail

    if request.method == 'POST':
        name = request.POST.get('name','')
        email = request.POST.get('email','')
        subject = request.POST.get('subject','')
        text = request.POST.get('text','')

        message = 'From: ' + email + '\n\n\n' + text

        send_mail(subject, message, 'myemail@gmail.com', ['myemail@gmail.com'], fail_silently=False)

你能告诉我为什么会收到这个错误吗? 我还检查了谷歌设置,如“从不太安全的应用程序访问”和类似的

提前谢谢!!!

修改

我已经允许不太安全的应用并点击解锁验证码

2 个答案:

答案 0 :(得分:0)

你也可以尝试一下。

import smtplib

def send_mail(request):
    try:
        subject = "Email Subject"
        description ="description"

        gmail_user =  "from@gmail.com" # email id from where you want send mail
        gmail_pwd ="password"
        FROM = 'Admin: <from@gmail.com>'
        TO = "to@gmail.com" #email id where you want send mail
        TEXT = description
        SUBJECT = subject
        server = smtplib.SMTP_SSL()
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()

        server.login(gmail_user, gmail_pwd)
        message = """From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
        server.sendmail(FROM, TO, message)
        server.quit()    
    except Exception,e:
        print 'exception',e

答案 1 :(得分:0)

嗨请检查添加电子邮件ID而不使用gmail扩展名

EMAIL_HOST_USER = "myemail"