(Almost) command line simulation with execfile

Stefan Schwarzer s.schwarzer at ndh.net
Sun Dec 30 21:02:09 EST 2001


Hello Brad

Brad Clements wrote:
> Please post internet.py

Here it is:

'''
Some internet-related modules
'''

import socket
import urllib
import smtplib
import time

def url_content_part(url, count=None):
    '''Return a number of bytes from an URL.'''
    fetched = urllib.urlopen(url)
    if count is None:
        text = fetched.read()
    else:
        text = fetched.read(count)
    fetched.close()
    return text

def send_example_email(server, from_addr, to_addr):
    '''Send an email (with fixed text).'''
    date = time.strftime( '%a, %d %b %Y %H:%M:%S', time.localtime() )
    text = '''\
From: %(from_addr)s
To: %(to_addr)s
Date: %(date)s
Subject: A little Python example for sending mails

Hello user

This is a mail from %(from_addr)s to %(to_addr)s
via server %(server)s

Best regards
Your Python interpreter ;-)\n''' % vars()
    host = smtplib.SMTP(server)
    host.sendmail(from_addr, [to_addr], text)
    host.quit()


raw_input(
  'Please ensure you are connected to the internet and press [Return]: ')

print

try:
    url = 'http://www.python.org/'
    count = 150
    print 'The first %s characters from %s:' % (count, url)
    print url_content_part(url, count)

    print

    print 'Sending an email:'
    server = raw_input('Enter a valid mailserver (full name) for your domain: ')
    from_addr = raw_input('Enter FROM email address: ')
    to_addr = raw_input('Enter TO email address: ')
    send_example_email(server, from_addr, to_addr)
    print 'Mail has been sent.'
except (IOError, socket.error):
    print
    print 'There seems to be a problem with your internet connection.'
    print 'Are you really online? Is all set up?'
except smtplib.SMTPException:
    print
    print 'Sending your mail failed. Please check your parameters and'
    print 're-execute the program with the correct ones.'



More information about the Python-list mailing list