Send Email using Python…

Send mail with Python

Send Mail Through Gmail with Python

by MARK SANBORN on June 30, 2009

Python is a great scripting language for Linux and it is often used to automate tasks or check on overall system health. Discover how to send emails through Gmail with Python.

Good system admins get to know scripting languages well and sometimes use them for all kinds of purposes, from scripts that do backups to complex automated tasks. Often times it would be nice to get an email notification when the script finished or completed OK. Cron does a good job of sending emails when scripts run into errors or problems, but sometimes it is necessary to get custom email messages sent from the script itself. Python makes sending email alerts a breeze.

The Code

  1. import smtplib
  2. fromaddr = ’fromuser@gmail.com’
  3. toaddrs  = ’touser@gmail.com’
  4. msg = ’There was a terrible error that occured and I wanted you to know!’
  5. # Credentials (if needed)
  6. username = ’username’
  7. password = ’password’
  8. # The actual mail send
  9. server = smtplib.SMTP(‘smtp.gmail.com:587′)
  10. server.starttls()
  11. server.login(username,password)
  12. server.sendmail(fromaddr, toaddrs, msg)
  13. server.quit()

 

—————

Send email with attachment:

import os
import smtplib
from email.MIMEMultipart import MIMEMultipart 
from email.MIMEBase import MIMEBase 
from email.MIMEText import MIMEText 
from email.Utils import COMMASPACE, formatdate 
from email import Encoders

from_addr = 'qwerty@saywot.webfactional.com'
to_addrs = ['hellospam@gmail.com']
msg="here is sample mesage"

s = smtplib.SMTP() 
s.connect('smtp.webfaction.com') 
s.login('saywot','notmyrealpassword')
s.sendmail(from_addr, to_addrs, msg)

def sendMail(to, subject, text, files=[],server="localhost"): 
assert type(to)==list 
assert type(files)==list 
from = "qwerty@saywot.webfactional.com"

msg = MIMEMultipart()
msg['From'] = fro
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject

msg.attach( MIMEText(text) )

for file in files:
    part = MIMEBase('application', "octet-stream")
    part.set_payload( open(file,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"'
                   % os.path.basename(file))
    msg.attach(part)

#smtp = smtplib.SMTP(server)
s.sendmail(fro, to, msg.as_string() )
s.close()

sendMail( ['hellospam@gmail.com'], 
"hello","cheers there", 
["note1.txt","note2.txt"]
)