Django使用Gmail报告错误

时间:2017-02-09 10:14:47

标签: django email smtp gmail error-reporting

我正在尝试设置我的Django帐户以接收错误报告(docs here)。

我已将ADMINS添加到settings.py。然后,根据文档:

  

为了发送电子邮件,Django需要一些设置告诉它如何   连接到您的邮件服务器。至少,你需要   指定EMAIL_HOST并可能指定EMAIL_HOST_USER和   EMAIL_HOST_PASSWORD,但也可能需要其他设置   取决于您的邮件服务器的配置。咨询Django   有关电子邮件相关设置的完整列表的设置文档。

但这是我迷路的时候。 我有一个商家Gmail帐户,我想在此处链接。 This post奇妙地解释了它,

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'myemail@mydomain.com'
EMAIL_HOST_PASSWORD = 'mypassword'

但它说:

  

2016年,Gmail不再允许这样做了。

显然,问题出在EMAIL_HOST_PASSWORD设置中,必须是特定密码,如this other post中所述。

但是,很难相信Gmail不会以任何方式允许这种情况,特别是在您为该服务付费的商家帐户中。

不幸的是,我发现的所有相关信息都比2016年早,因此不再有用。

有没有办法将Django应用程序与Gmail连接?

2 个答案:

答案 0 :(得分:0)

最终为我工作的解决方法是为此目的创建一个新的Gmail帐户。这暂时有效,尽管我在其他地方读到了一些相反的评论。

请注意,这个新帐户将没有两步验证,但安全性并不是一个大问题,因为该帐户将“仅”处理Django电子邮件。

答案 1 :(得分:0)

您可以使用Gmail API通过Gmail电子邮件地址发送授权电子邮件。文档是一个不错的起点:https://developers.google.com/gmail/api/quickstart/python

我一直遇到这个问题,因此我在博客文章https://www.willcarh.art/blog/Automating-Emails-in-Python/

中记录了如何使用API

这让我很痛苦,最终我建立了自己的Python实用程序,用于通过Gmail API发送电子邮件。这是我最初的原型:

import os
import sys
import pickle
import base64
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText

def get_gmail_api_instance():
    """
    Setup Gmail API instance
    """
    if not os.path.exists('token.pickle'):
        return None
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
    service = build('gmail', 'v1', credentials=creds)
    return service

def create_message(sender, to, subject, message_text):
    """
    Create a message for an email
        :sender: (str) the email address of the sender
        :to: (str) the email address of the receiver
        :subject: (str) the subject of the email
        :message_text: (str) the content of the email
    """
    message = MIMEText(message_text)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    body = {'raw': raw}
    return body

def send_email(service, user_id, message):
    """
    Send an email via Gmail API
        :service: (googleapiclient.discovery.Resource) authorized Gmail API service instance
        :user_id: (str) sender's email address, used for special "me" value (authenticated Gmail account)
        :message: (base64) message to be sent
    """
    try:
        message = (service.users().messages().send(userId=user_id, body=message).execute())
        return message
    except Exception as e:
        print("err: problem sending email")
        print(e)

def main():
    """
    Set up Gmail API instance, use it to send an email
      'sender' is the Gmail address that is authenticated by the Gmail API
      'receiver' is the receiver's email address
      'subject' is the subject of our email
      'message_text' is the content of the email
    """
    # draft our message
    sender = 'pythonista@gmail.com'
    receiver = 'receiver@gmail.com'
    subject = 'Just checking in!'
    message_text = "Hi! How's it going?"

    # authenticate with Gmail API
    service = get_gmail_api_instance()
    if service == None:
        print("err: no credentials .pickle file found")
        sys.exit(1)

    # create message structure
    message = create_message(sender, receiver, subject, message_text)

    # send email
    result = send_email(service, sender, message)
    if not result == None:
        print(f"Message sent successfully! Message id: {result['id']}")

if __name__ == '__main__':
    main()

然后,要使Django发送有关404、500等错误的电子邮件,请添加到相关的urls.py

from django.conf.urls import handler404, handler500
handler404 = projectname_views.error_404
handler500 = projectname_views.error_500

在相关的views.py中,添加:

import send_gmail
from django.shortcuts import render

def error_500(request):
    # call email function
    send_gmail.main()
    response = render(request, '500_errror_template.html')
    response.status_code = 500
    return response

具有以上代码的GitHub要点:https://gist.github.com/wcarhart/b4f509c46ad1515a9954d356aaf10df1