1
msg.html = requests.get("http://2teso.com/cachedigital/themail.html")
mail.send(msg)

I don't want to use something like this:

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

Which works by the way.

I would just like to ref a file. How can I do this?

I thought I could use the request module.

To clarify the first code block does not input the html into the email. If I write html code directly in the python app, then it works and the email send.

I want to send an html email by pointing to a file or url.

1 Answers1

0

You can get the response content of an URL using text attribute of response from requests package.

Here is an example of how to get HTML contents from an URL using requests package.

code.py:

import requests


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

Output:

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

Additionally you can change the encoding by setting encoding in r.encoding (e.g.: r.encoding = 'ISO-8859-1'). If you change the encoding, Requests will use the new value of r.encoding whenever you call r.text.

After getting the HTML contents of the desired URL using requests, assign it to msg.html to send the content in the email.

Code can be updated like this:

import requests


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

Reference:

arshovon
  • 13,270
  • 9
  • 51
  • 69