Beginner's Guide to Programming - guidetoprogramming.com

  • Increase font size
  • Default font size
  • Decrease font size

Send email from Python

The function below will send an email directly from a Python script.  This can be useful to automatically email yourself output upon completion of the script.

I've only used this successfully on Linux.  I tested this on Windows and it did not work as written - I believe a Windows version would work with changes, but I am not sure what those changes are!

#!/usr/bin/python

import smtplib

#send email from python
#this creates a text email and sends it to an address of your choosing directly from python

def mailsend (toaddress,fromaddress,subject,message):
    #you need to know your correct smtp server for this to work, mine is in the function below
    smtpserver = smtplib.SMTP("smtp.east.cox.net",25)
    header = 'To:' + toaddress + '\n' + 'From:' + fromaddress + '\n' + 'Subject: ' + subject +'\n'
    msg = header + '\n' + message
    smtpserver.sendmail(fromaddress, toaddress, msg)
    smtpserver.close()
"""   
the below calls the function - you should change the address settings for your purposes, and you can change the subject and message details as well to send the message information you want to send
"""

mailsend (' This e-mail address is being protected from spambots. You need JavaScript enabled to view it ',' This e-mail address is being protected from spambots. You need JavaScript enabled to view it ','test from python','this is the test message')