1

I'm trying to create a function that e-mails an HTML File with CSS and everything. I'm trying to figure out how to pass variables into my HTML. The HTML code is in a separate file called index.html

FILE 1 app.py

def mailer2(addr_from,addr_to, title, password):

# Define SMTP email server details
smtp_server = 'smtp.gmail.com'
smtp_user   = addr_from
smtp_pass   = password

# Construct email
msg = MIMEMultipart('alternative')
msg['To'] = addr_to
msg['From'] = addr_from
msg['Subject'] = 'Test Email From Me'

html = urllib.urlopen('index.html').read().format(first_header = 'hi')

part2 = MIMEText(html, 'html')

msg.attach(part2)

s = smtplib.SMTP(smtp_server,587)
s.starttls()
s.login(smtp_user,smtp_pass)
s.sendmail(addr_from, addr_to, msg.as_string())
s.quit()

In my HTML code,

  <div class="contentEditable" >
  <h2>{first_header}</h2>

I expect hi to fill in the spot of first_header, but instead I get:

html = urllib.urlopen('index.html').read().format(first_header='goodbye') KeyError: 'padding'

Not sure what the issue is here. Could someone please help me out?

Pax Vobiscum
  • 2,551
  • 2
  • 21
  • 32
user3558939
  • 155
  • 1
  • 7

2 Answers2

0

try this way:

html = urllib.urlopen('index.html').read().format('hi')
<div class="contentEditable" >
<h2>{}</h2>
0

This does not use urllib, but will solve the problem you are looking for.

# Documentation of Jinja http://jinja.pocoo.org/docs/2.10/api/#high-level-api
from jinja2 import Environment, FileSystemLoader
import os
env = Environment(loader=FileSystemLoader(os.getcwd()))
template = env.get_template('index.html')
message = 'hi'
html = template.render(first_header=message)

Your index html file should have:

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, shrink-to-fit=no, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
</head>

<body>
<div class="contentEditable" >
  <h2>{{first_header}}</h2>
</body>
</html>
jujuBee
  • 494
  • 5
  • 13
  • Hi, when I implement this, I get a new error: UnicodeEncodeError: 'ascii' codec can't encode character u'\u201d' in position 6719: ordinal not in range(128) I've tried all the solutions in here, but none seem to work. https://stackoverflow.com/questions/9942594/unicodeencodeerror-ascii-codec-cant-encode-character-u-xa0-in-position-20 – user3558939 Mar 07 '18 at 18:58
  • It's hard for me to say, unless I see _index.html_ file. I have edited by response with the contents of the index file that I have used. Perhaps that could help. – jujuBee Mar 07 '18 at 19:25
  • Got it! Thank you! – user3558939 Mar 07 '18 at 20:07