Search code examples
pythonhtml-emailpython-3.6smtplib

Is there a way to fix Python strings embedded in html email body from returning "none"?


Python strings embedded or inserted in html email bodies return 'none' in the body of the sent email.

I imported a .py file named Bscrape.py as a module and called it's function. This worked, but when i try to print the string as print(k), i get a 'TypeError: must be str, not NoneType'. Using the string 'k' alone removes the error but sends the email with the string appearing as "none".

import smtplib
import email
import sys, csv
from email.mime.multipart import MIMEMultipart
from email.headerregistry import Address
from email.message import EmailMessage
import email.encoders
import email.mime.text
import email.mime.base
from email.mime.text import MIMEText
import ast
import re
import os
import subprocess

smtpserver = smtplib.SMTP_SSL('smtp.gmail.com', 465)

me =  'Update <[email protected]>'
you = "[email protected]"



# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Today's Headlines | Freshly Pressed"
msg['From'] = me
msg['To'] = you



#specifiy the module location for import
sys.path.extend(["C:\blinker\Webscrp_send_experiments"])

#import the python script file for usage
from Bscrape import print_BAE
k = str(print_BAE())

# now place this in the html body print_BAE()


#####
text = "Numbers for Monday"
html = """\
<html>
<body>

  <h3>Values remain marginal</h3>
  <p>States on the coast returned these numbers.<br>
  """ + k + """<br>
  The number above is surprising</p>

  <hr>     
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
s.login("[email protected]", "my_password")
s.sendmail(me, you, msg.as_string())
s.quit()

I expect python to print-out the "k" string within the body of the sent email. This is not working. It prints the entire email with the string shown as "none".


Solution

  • Problem: Function in imported readymade beautifulsoup script (Bscrape) from my local drive would not print or display when embedded as a string in email html body.

    Solution was: Paste the beautifulsoup script in the destination script rather than import it. With this, 'None' disappears and all strings worked immediately when embedded as a string in email html body. Email now displays entire text.

    My problem has been solved.