python

Sending mail in python

A quick Python function that shows how to send an email.

def send_mail(destination, source, subject, text, smtp_addr='localhost'):
    """Simple function to send an email.
   
    destination
        The email address that the message should be sent to.
    source
        The 'From' address that will be used for the email.
    subject
        The subject/ title of the email.
    text
        The actual message/ content of the email.
    smtp_addr
        The hostname or IP address of the SMTP server that will deliver the
        email.
   
    Example usage:
        send_mail('my_friend@test.com', 'bgates@microsoft.com',
                'Hi!', 'Just checking in.')
   
    "
""
    import email.Message
    import smtplib
    mail = email.Message.Message()
    mail['To'] = destination
    mail['From'] = source
    mail['Subject'] = subject
    mail.set_payload(text)
    server = smtplib.SMTP(smtp_addr)
    server.sendmail(source, destination, mail.as_string())
    server.quit()

Python Tips and Guidelines

This is a must-read for any Python developer:

http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

Syndicate content