I'm trying to learn python from a book ("Hello! Python"). This code should, according to the book, send an email. no luck so far.
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
def send_message(message):
s = smtplib.SMTP('smtp.me.com')
s.sendmail(message['From'], message['To'], message.as_string())
s.quit()
def mail_report(to, ticker_name):
outer = MIMEMultipart()
outer['Subject'] = "Stock report for " + ticker_name
outer['From'] = "[email protected]"
outer['To'] = to
# Internal text container
inner = MIMEMultipart('alternative')
text = "Here is the stock report for " + ticker_name
html = """\
<html>
<head></head>
<body>
<p>Here is teh stock report for
<b> """ + ticker_name + """ </b>
</p>
</body>
</html>
"""
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
inner.attach(part1)
inner.attach(part2)
outer.attach(inner)
filename = 'stocktracker-%s.csv' % ticker_name
csv_text = ''.join(file(filename).readlines())
csv_part = MIMEText(csv_text, 'csv')
csv_part.add_header('Content-Disposition', 'attachment', filename=filename), outer.attach(csv_part)
return outer
if __name__ == '__main__':
email = mail_report('[email protected]', 'GOOG')
send_message(email)
I don't get an error, but I also don't get an email. (needless to say, i'm using my actual email, not '[email protected]') All suggestions and suggested reading appreciated.
You can run a local smtp debugging server. Find where smtpd.py is located, then run the command:
$ python /usr/lib/python2.7/smtpd.py -n -c DebuggingServer localhost:8025
Then on a second terminal screen run the Python interpreter:
>>> import smtplib
>>> s = smtplib.SMTP('localhost', 8025)
>>> s.sendmail('me', 'you', 'Hi!')
You should see 'Hi!' in the first screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With