Send Email using 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
- import smtplib
- fromaddr = ’fromuser@gmail.com’
- toaddrs = ’touser@gmail.com’
- msg = ’There was a terrible error that occured and I wanted you to know!’
- # Credentials (if needed)
- username = ’username’
- password = ’password’
- # The actual mail send
- server = smtplib.SMTP(‘smtp.gmail.com:587′)
- server.starttls()
- server.login(username,password)
- server.sendmail(fromaddr, toaddrs, msg)
- 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"] )