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 used this both in Linux and Windows.  In both this can be used as-is, but in Windows the header for the location of Python ("#!/usr/bin/Python") is not necessary.  It still worked with it for me, but that is a header specifically for Linux.

#!/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')