How To/python/MyMiscUtils/

# -*- coding: utf-8 -*-
 
"""
Sending email from python using GMail.
 
Original script from:
http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html
 
Sending email from python using GMail
 
None GMail(str gmailUserName, str gmailPassword[, str mode])
Mode can be 'one' (default) or 'many'. It is used when many recipcients are given.
In 'one' mode only one mail is send to all given recipients.
In 'many' mode for every recipient separate mail is send.
 
None GMail.addRecipients(list mailList)
Add mails to sending list.
 
GMail.send(str subject, str mailBody)
Send mail using subject and mailBody
 
 
Example:
 
gm = GMail(
    'gmail_user_name@gmail.com', 
    'gmail_user_password', 
    'one'
)
 
gm.addRecipients([
    "mail1@example.com",
    "mail2@example.com",
    "mail3@example.com"
])
 
gm.setCharset('utf-8')
 
content = u'This is email content!'
subject = 'This is subject!'
 
gm.send(subject, content.encode('utf-8'))
"""
 
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
import os
 
class GMail:
 
    def __init__(self, user, passwd, mode = 'one'):
        """
        Create GMail object and connect to SMTP given using user name and password. 
        Mode ('one'|'many') is optional. 'one' is default. 
        'one': one mail to all recipients, 'many': one mail per each recipient.
        """
 
        self.__user = ""
        self.__pwd = ""
        self.__mails = []
        self.__mode = 'one'
        self.__charset = 'utf-8'
 
        self.__user=user
        self.__pwd=passwd
        if mode == 'many':
            self.__mode = mode
 
    def addRecipients(self, m):
        """Add recipients to sending list"""
        if self.__mode == 'many':
            if type(m) is list:
                self.__mails.extend(m)
            else:
                self.__mails.append(m)
        else:
            if len(self.__mails) == 0:
                self.__mails.append([])
            if type(m) is list:
                self.__mails[0].extend(m)
            else:
                self.__mails[0].append(m)   
 
    def setRecipients(self, m):
        """Create new sending list with reciptients"""
        self.__mails = []
        self.addMails(m)
 
    def setCharset(self, charset):
        self.__charset = charset
 
    def __prepareAndSend(self, subject, text, attach):
        mailServer = smtplib.SMTP("smtp.gmail.com", 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(self.__user, self.__pwd)
 
        # create different mail for every recipient
        for to in self.__mails:
            msg = MIMEMultipart()
            msg.attach(MIMEText(text, _charset=self.__charset))
 
            # add atachement if defined
            if attach:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(attach))
                msg.attach(part)
 
            # set From, To and Subject headers
            msg['From'] = self.__user
            msg['Subject'] = subject
            if self.__mode == 'many':
                msg['To'] = to; 
                print ' '.join(['sending:', str(to)])
            else:
                msg['To'] = ', '.join(to); 
                print '\n'.join(['sending:', ',\n'.join(to)])
 
            #send mail
            mailServer.sendmail(self.__user, to, msg.as_string())
 
        # Should be mailServer.quit(), but that crashes...
        mailServer.close()
 
    def send(self, subject, text, attach=False):
        """Start sending emails"""
        self.__prepareAndSend(subject, text, attach)