【问题标题】:Requests Get and Flask Mail Python请求获取和烧瓶邮件 Python
【发布时间】:2019-08-23 18:58:14
【问题描述】:
msg.html = requests.get("http://2teso.com/cachedigital/themail.html")
mail.send(msg)

我不想使用这样的东西:

msg.html = """
<p>Hey</p>
"""

顺便说一句。

我只想引用一个文件。我该怎么做?

我想我可以使用请求模块。

为了澄清第一个代码块没有将 html 输入到电子邮件中。 如果我直接在 python 应用程序中编写 html 代码,那么它可以工作并发送电子邮件。

我想通过指向文件或 url 来发送 html 电子邮件。

【问题讨论】:

    标签: python-3.x flask flask-mail


    【解决方案1】:

    您可以使用来自requests 包的响应的text 属性获取URL 的响应内容。

    这是一个如何使用requests 包从 URL 获取 HTML 内容的示例。

    code.py:

    import requests
    
    
    r = requests.get('https://example.com/')
    content = r.text
    print(type(content))
    print(content)
    

    输出:

    <class 'str'>
    <!doctype html>
    <html>
    <head>
        <title>Example Domain</title>
    
        <meta charset="utf-8" />
        <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <style type="text/css">
        body {
            background-color: #f0f0f2;
            margin: 0;
            padding: 0;
            font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
    
        }
        div {
            width: 600px;
            margin: 5em auto;
            padding: 50px;
            background-color: #fff;
            border-radius: 1em;
        }
        a:link, a:visited {
            color: #38488f;
            text-decoration: none;
        }
        @media (max-width: 700px) {
            body {
                background-color: #fff;
            }
            div {
                width: auto;
                margin: 0 auto;
                border-radius: 0;
                padding: 1em;
            }
        }
        </style>    
    </head>
    
    <body>
    <div>
        <h1>Example Domain</h1>
        <p>This domain is established to be used for illustrative examples in documents. You may use this
        domain in examples without prior coordination or asking for permission.</p>
        <p><a href="http://www.iana.org/domains/example">More information...</a></p>
    </div>
    </body>
    </html>
    

    此外,您可以通过在r.encoding 中设置编码来更改编码(例如:r.encoding = 'ISO-8859-1')。如果您更改编码,请求将在您调用r.text 时使用新值r.encoding

    使用requests获取所需URL的HTML内容后,将其分配给msg.html以发送电子邮件中的内容。

    代码可以这样更新:

    import requests
    
    
    r = requests.get('https://example.com/')
    content = str(r.text)
    msg.html = content
    mail.send(msg)
    

    参考:

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2018-12-03
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多