How to send Email by Python

Posted: September 19, 2013 in FX Pipeline, Linux, Python for VFX

Python

email

How to send Email by Python

Following are the two ways to send email notifications by python

“””
This Script Will Send Email Using Internal Email System

In this no need any authentication or password required to send Email

Python Version 2.6

“””

from email.mime.text import MIMEText
import email.Utils
import smtplib

emailList = [“recepient1@gmail.com”, “recepient2@gmail.com”] # this is List of Email Ids

for emailID in emailList:
try:
print “Sending email to … “, emailID

FROM = “email@gmail.com”
TO = emailID
message = “This Email is send by Python\n Python is Great !!!”
msg = MIMEText(message)
msg[“Subject”] = “Email Notification by Python”
msg[“Message-id”] = email.Utils.make_msgid()
msg[“From”] = FROM
msg[“To”] = TO
host = “smtp.gmail.com”
server = smtplib.SMTP(host)
server.sendmail(FROM, TO, msg.as_string())
server.quit()
print “Email Send”

except Exception, e:
print e

 

 

“””

This Script Will Send Email Using Gmail

This Required Username and password

Python Version 2.6

“””

from email.mime.text import MIMEText
from datetime import date
import smtplib

SMTP_SERVER = “smtp.gmail.com”
SMTP_PORT = 587
SMTP_USERNAME = “email@gmail.com”
SMTP_PASSWORD = “password”

EMAIL_TO = [“recepient1@gmail.com”, “recepient2@gmail.com”]
EMAIL_FROM = “email@gmail.com”
EMAIL_SUBJECT = “Demo Email : “

DATE_FORMAT = “%d/%m/%Y”
EMAIL_SPACE = “, “

DATA=’This is the content of the email.’

def send_email():
msg = MIMEText(DATA)
msg[‘Subject’] = EMAIL_SUBJECT + ” %s” % (date.today().strftime(DATE_FORMAT))
msg[‘To’] = EMAIL_SPACE.join(EMAIL_TO)
msg[‘From’] = EMAIL_FROM
mail = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mail.starttls()
mail.login(SMTP_USERNAME, SMTP_PASSWORD)
mail.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
mail.quit()
print “Email Send”

if __name__==’__main__’:
send_email()

Advertisements
Comments
  1. San Luthra says:

    It is easy to send a text mail, but to send an attachment requires hell lot of lines of codes.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s