0

I am sending an email in Python and am trying to pass a variable in the HTML. I see that this can be done with "formatstring".format, but I am unable to do it successfully. Here's a short(er) version of what I have:

email_to = []
email_apiendpoint = []

for data_item in json.loads(email_curl_str, strict=False)['data']:
    email_to.append(data_item['emailAddress'])
    email_apiendpoint.append(data_item['apiEndpoint'])

ddn = random.randint(200, 400)

email_msg = MIMEMultipart('alternative')
email_msg['Subject'] = "Link"
email_msg['From'] = email_from
email_msg['To'] = email_to[0]

email_text = "Plain text here."
email_html = """\
<html>
<head>
</head>
<body>
<p>Compare to: {ddn}</p>
</body>
</html>
""".format(ddn=ddn)

part1 = MIMEText(email_text, 'plain')
part2 = MIMEText(email_html, 'html')

email_user = ''
email_pw = ''

smtpserver = smtplib.SMTP("mauimail.prxy.com")


def send_email():
    email_msg.attach(part1)
    email_msg.attach(part2)

    smtp.server.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(email_user, email_pw)

    smtpserver.sendmail(email_from, email_to[0], email_msg.as_string())
    smtpserver.quit()

This results in:

""".format(ddn=ddn)
KeyError: ' border'

What am I doing wrong?

EricY
  • 376
  • 1
  • 3
  • 19
  • 1
    This error looks like it is produced somewhere else in your code, are you accessing a dictionary before/after? That code alone works fine and produces a string like: ```In [4]: print email_html

    Compare to: 321

    ``` So can you edit in more of the code?
    – Jeff_Hd Aug 20 '15 at 22:47
  • @Jeff_Hd Yes I do actually. I'll include some more code in the original question. – EricY Aug 20 '15 at 22:53
  • 1
    I still can't see the offending line but your problem is somewhere in your code a line something like this is happening `var = dictionary['_border']` (where var is any variable and dictionary is just a dict) which is producing the keyerror as the dictionary doesn't have anything under `_border`. – Jeff_Hd Aug 20 '15 at 23:07
  • @Jeff_Hd Ok thanks for the suggestion, I'll dig deeper. – EricY Aug 20 '15 at 23:12
  • 2
    If you add the *full* traceback (instead of just these 2 lines), it should immediately show where the error comes from. In fact, if you read the traceback, you'll find line numbers and file names directing you to the actual cause of the error. –  Aug 21 '15 at 00:13
  • @Evert This is the full traceback: `File "~/Git/pr0xy/webapps/lib/WEB-INF/tpy/test3.py", line 272, in """.format(ddn=ddn) KeyError: ' border'` Am I missing something here? – EricY Aug 21 '15 at 18:02
  • There's some information missing somewhere, but it's not possible to tell this way. They key `' border'` (with the intruiging space at the start) is nowhere to be found in your example, but it must show somewhere in your original script. If there anything like `{ border}` in the actual `email_html`? –  Aug 22 '15 at 01:32

0 Answers0