Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending email using email.mime.multipart in Python

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.

like image 844
DBWeinstein Avatar asked Nov 03 '22 16:11

DBWeinstein


1 Answers

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.

like image 158
Jeff Bauer Avatar answered Nov 09 '22 15:11

Jeff Bauer