簡體   English   中英

如何使用Python通過Gmail發送電子郵件

[英]How to Send Emails with Gmail using Python

如何使用Python發送電子郵件嘗試了兩種方法沒有用戶名,密碼和其他用戶名和密碼的方法但谷歌攔截器

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

您可能已將Gmail帳戶保留為不安全的應用程序。 這意味着Gmail會拒絕任何不太安全的程序發送的電子郵件,並阻止您的電子郵件。 我強烈推薦本教程該教程將介紹為該程序設置Gmail帳戶的所有內容。

嘗試下面的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"
}

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工具來實現這一點,這里是文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM