1
# [SNIPPET_NAME: Sending Email]
2
# [SNIPPET_CATEGORIES: smtplib, email]
3
# [SNIPPET_DESCRIPTION: Sending mail from gmail account with many attachements and to_many_mails_ids]
4
# [SNIPPET_AUTHOR: kutuma]
5
# [SNIPPET_LICENSE: GPL]
6
# [SNIPPET_UPLOADED_BY: Arulalan.T <tarulalan@gmail.com>]
8
# you need to set the gmail user name and its password at the line of 22 and 23 st (in gedit, line number) of this snippet.
10
# you need to set the to_mail_ids in a string array , subject, body , attachements_absolute_path in a string array from the line of 26 of this snippet.
14
# ref : http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html
16
from email.MIMEMultipart import MIMEMultipart
17
from email.MIMEBase import MIMEBase
18
from email.MIMEText import MIMEText
19
from email import Encoders
22
gmail_user = "username@gmail.com"
23
gmail_pwd = "gmail_password"
27
subject="I am Subject "
29
to_mail_ids=["friend1_mail_id","friend2_mail_id"]
30
attachements_path=["absolute_attachement1_with_extension","absolute_attachement2_with_extension"]# for eg : /home/arul/z/nnk.txt, /home/arul/python/sam.py
34
def mail(to, subject, text, attach=[]):
37
msg['From'] = gmail_user
39
msg['Subject'] = subject
41
msg.attach(MIMEText(text))
45
for i in range(len(attach)):
46
part = MIMEBase('application', 'octet-stream')
47
part.set_payload(open(attach[i], 'rb').read())
48
Encoders.encode_base64(part)
49
part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(str(attach[i])))
52
print " The attachments doesnt exist in the path %s and %s" % (attach[0],attach[1])
55
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
59
mailServer.login(gmail_user, gmail_pwd)
60
mailServer.sendmail(gmail_user, to, msg.as_string())
61
# Should be mailServer.quit(), but that crashes...
66
for to_mail_id in (to_mail_ids):
71
print "mail sent to :"+to_mail_id
73
print "\nmail sent successfully to all\n"