如何使用Python使用Gmail发送电子邮件

时间:2019-05-25 12:46:30

标签: python

如何使用Python发送电子邮件尝试了两种方法,该方法没有用户名,密码以及其他用户名和密码,但有Google阻止程序

import smtplib

content = "anything"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.starttls()
server.login("Your_Username", 'Your_Password')
server.sendmail('Your_Username', "usamnet000@gmail.com", content)
server.close()

3 个答案:

答案 0 :(得分:0)

您可能已经将block less secure apps on.留在了Gmail帐户中,这意味着Gmail将拒绝安全性较低的程序发送的电子邮件,并阻止您的电子邮件。我强烈建议this tutorial,它将为您设置该程序的Gmail帐户所涉及的所有内容。

答案 1 :(得分:0)

请尝试以下send方法:

import smtplib,ssl

def connect(username):
    serverName = username[username.index("@")+1:username.index(".")]
    while True:
        try:
            server = smtplib.SMTP(serverDict[serverName])
        except smtplib.SMTPException as error:
            print(error)
            continue
        try:
            server.ehlo()
            if server.has_extn("starttls"):
                server.starttls()
                server.ehlo()
        except (smtplib.SMTPException,ssl.SSLError) as error:
            print(error)
            disconnect(server)
            continue
        break
    return server

def disconnect(server):
    try:
        server.quit()
    except smtplib.SMTPException as error:
        print(error)

def send(username,password,message):
    server = connect(username)
    try:
        server.login(username,password)
    except smtplib.SMTPException as error:
        print(error)
    else:
        server.sendmail(username,password,message)
    disconnect(server)

serverDict = {
    "gmail"  :"smtp.gmail.com",
    "hotmail":"smtp.live.com",
    "yahoo"  :"smtp.mail.yahoo.com"
}

答案 2 :(得分:0)

settings.py

...
...
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'pruebadjangomail@gmail.com'
EMAIL_HOST_PASSWORD = '********'
EMAIL_PORT = 587

我曾经使用Django信号发送大量电子邮件,例如

signals.py

context = {'event': instance,
           'alarm': instance.alarm,
           'user': user,
           'device': instance.device,
           'var': instance.variables,
           'content_type': instance.content_type.all()}
plain_text = get_template('mail.txt')  # Plain text template
text_content = plain_text.render(context)
subject = 'Event Alert: ' + instance.__str__()
from_email = 'noreply@localhost.com'
to = email
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
try:
   if sub['staff_template'] is not None:
      htmly = get_template(sub['staff_template'])  # Define the HTML template
       html_content = htmly.render(context)  # Rendering the templates with context information
   elif sub['staff_template_text'] != "":
      htmly = Template(sub['staff_template_text'])
      html_content = htmly.render(Context(context))
   elif sub['user_template'] is not None:
      htmly = get_template(sub['user_template'])  # Define the HTML template
      html_content = htmly.render(context)  # Rendering the templates with context information
   elif sub['user_template_text'] != "":
      htmly = Template(sub['user_template_text'])
      html_content = htmly.render(Context(context))
   msg.attach_alternative(html_content, 'text/html')
   msg.send()
except:
   msg.send()
   print('Mail send to %s' % email)

我建议使用Django工具来完成此操作,这里是docs