我如何通过电子邮件向Flask发送错误日志?

时间:2015-12-14 19:22:37

标签: python flask

如果应用程序中出现404或500错误,我如何让Flask向我发送电子邮件?我在config.py from app import app ADMINS = ['myemail@domain.com'] if not app.debug: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler('smtpout.secureserver.net', 'info@mydomain.com', ADMINS, 'YourApplication Failed', credentials=('info@mydomain.com','***'), port=25) mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler) 中插入了以下内容here,但我没有收到任何电子邮件。我是Flask的新手,请原谅任何错误。

public class PlaceAPI{

    private static final String TAG = PlaceAPI.class.getSimpleName();

    private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";

    private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
    private static final String OUT_JSON = "/json";

    private static final String API_KEY = "key here";

    public ArrayList<String> autocomplete (String input) {
        ArrayList<String> resultList = null;
        ArrayList<String> resultListid = null;

        HttpURLConnection conn = null;
        StringBuilder jsonResults = new StringBuilder();

        try {
            StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
            sb.append("?key=" + API_KEY.trim());
            sb.append("&input=" + URLEncoder.encode(input, "utf8"));

            URL url = new URL(sb.toString());
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Load the results into a StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                jsonResults.append(buff, 0, read);
            }
        } catch (MalformedURLException e) {
            Log.e(TAG, "Error processing Places API URL", e);
            return resultList;
        } catch (IOException e) {
            Log.e(TAG, "Error connecting to Places API", e);
            return resultList;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        try {
            // Log.d(TAG, jsonResults.toString());

            // Create a JSON object hierarchy from the results
            JSONObject jsonObj = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");//result

            // Extract the Place descriptions from the results
            resultList = new ArrayList<String>(predsJsonArray.length());
            for (int i = 0; i < predsJsonArray.length(); i++) {
                resultList.add(predsJsonArray.getJSONObject(i).getString("description"));//geometry
            }
        } catch (JSONException e) {
            Log.e(TAG, "Cannot process JSON results", e);
        }

        //GET PLACEID
        try {

            // Create a JSON object hierarchy from the results
            JSONObject jsonObjid = new JSONObject(jsonResults.toString());
            JSONArray predsJsonArrayid = jsonObjid.getJSONArray("predictions");

            // Extract the Place descriptions from the results
            resultListid = new ArrayList<String>(predsJsonArrayid.length());
            for (int i = 0; i < predsJsonArrayid.length(); i++) {
                resultListid.add(predsJsonArrayid.getJSONObject(i).getString("id"));
            }
        } catch (JSONException e) {
            Log.e(TAG, "Cannot process JSON results", e);
        }

        return resultList;
    }
}

我对文档中的这一行感到有些困惑:

  

如果您的邮件服务器需要凭据,也可以提供这些凭据。

我的服务器不是“邮件服务器”。我应该提供什么证书?我的电子邮件是在GoDaddy托管的。

2 个答案:

答案 0 :(得分:6)

您需要添加电子邮件的凭据(用户名和密码),如下所示:

mail_handler = SMTPHandler(mailhost=('smtpout.secureserver.net',25),
                           fromaddr='info@mydomain.com',
                           toaddrs=ADMINS, subject='YourApplication Failed',
                           credentials=('mail_username','mail_password'))

从本质上讲,您需要登录您的邮件帐户(来自godaddy)才能发送电子邮件。所使用的IP需要是godaddy为STMP服务提供的IP(我相信它是smtpout.secureserver.net),没有SSL的端口是25,80,3535之一,如果你使用SSL端口是465。 / p>

希望它有所帮助!

编辑: 因为它在我应该添加一个完整的最小源代码来测试它时仍然不起作用,这是快速启动最小的hello word示例,修改为在发生错误时发送电子邮件并始终失败(它将每次发送一封电子邮件)你访问该页面的时间),在godaddy(我们)上进行了全面测试:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    raise Exception
    #return 'Hello World!'

if __name__ == '__main__':
    ADMINS = ['admin@mydomain.com']
    if not app.debug:
        import logging
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler(mailhost=('smtpout.secureserver.net',25),
                           fromaddr='admin@mydomain.com',
                           toaddrs=ADMINS, subject='YourApplication Failed',
                           credentials=('admin@mydomain.com','mypassword'))
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
    app.run()

重要的是你需要检查你需要使用的实际smtp服务器。当您登录godaddy时,单击电子邮件管理员按钮(电子邮件工作区上的按钮),转到顶部菜单工具 - &gt;服务器功能。在那之后选择你的域并在最后一行(SMTP)中你应该看到一个类似我为smtp传出访问提供的域,在我的情况下我对不同的域有不同的域:

smtpout.asia.secureserver.net
smtpout.secureserver.net

找到您需要使用的代码并修改我的示例代码,您应该立即通过godaddy电子邮件的网络界面收到电子邮件。

拥有合适的服务器并使用您的凭据后,您应该在运行该应用时收到类似这样的电子邮件:

Exception on / [GET]
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "hello.py", line 6, in hello_world
raise Exception
Exception

答案 1 :(得分:0)

您应该考虑使用Flask-Mail(https://pythonhosted.org/flask-mail/#configuring-flask-mail)。它有助于组织电子邮件过程。阅读本文:(http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xi-email-support

假设您的域名没有smtp服务:

重新。证书。在您的域名注册商处设置电子邮件转发。然后设置一个Gmail帐户或其他服务来发送电子邮件。 (https://webapps.stackexchange.com/questions/66228/add-new-alias-to-gmail-without-smtp-forwarding-only-address)。 (见@John的回答)

然后custom@yoursite.com被发送到u@gmail.com。然后,您可以通过您的Gmail或其他服务(例如mailgun)从custom@yoursite.com发送邮件。

相关问题