Talal Kamran Talal Kamran - 2 years ago 67
Python Question

I am trying to send an email using Python, when I pass the last field as variable it does not send anything in the email

# Web scraping

import urllib
import smtplib
from urllib.request import urlopen
from bs4 import BeautifulSoup

def make_soup(url):
thePage= urllib.request.urlopen(url)
soupdata = BeautifulSoup(thePage, "html.parser")

return soupdata

soup = make_soup("http://www.met.gov.kw/?lang=eng")
for record in soup.select('#newForecast'):
information = record.text

content = information[48:440]
msg = content

Here is the part of the code I am having problems with when i transfer the information stored in content to message and then pass it to the sendmail() function where the body message is supposed to go the email shows up as empty
Can you tell me what is going wrong?

server = smtplib.SMTP('smtp.gmail.com', 587)
server.login("yourEmail", "yourPassword")
server.sendmail("placeholder", "placeholder", msg)

Answer Source

Your variable msg is a raw string of content. For content of email you must use the MIME type (Multipurpose Internet Mail Extensions).

In Python you can use the objects MIMEText (for only text) or MIMEMultipart (with attachment). It will convert your content to equivalent MIME format with the function as_string(). Or you can build your own String with the MIME format. ;)

Here is my correction for your code. That should work:

# import the object MIMEText
from email.mime.text import MIMEText
# build a instance of MIMEText from your content string
msg = MIMEText(content)
# Subject, From, To are the information, which the receiver will see
# It's no problem, if you use a fake address here. That's the way, how phishing mail or spam mail works
msg['Subject'] = 'Subject of my email'
msg['From'] = "sender@email.com"
msg['To'] = "receiver@email.com"

# now use as_string() to convert your data to equivalent MIME format
# you can use `print msg.as_string()` to see how it is.
server.sendmail("placeholder", "placeholder", msg.as_string())

More examples email examples

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download