Subversion Repositories SmartDukaan

Rev

Rev 581 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

'''
Created on 14-Jul-2010

@author: ashish
'''
from email.mime.multipart import MIMEMultipart
from shop2020.thriftpy.utils.ttypes import HelperServiceException, Mail
from email.mime.base import MIMEBase
from email import encoders
import os
import smtplib
from shop2020.helpers.impl.DataService import Message
from elixir import *

from shop2020.thriftpy.utils.ttypes import Message as Msg
from string import Template


def sendMail(mail):
    if not mail:
        raise HelperServiceException(101, "mail not present")
    msg = MIMEMultipart()
    mail = Mail()
    msg['From'] = mail.sender
    msg['Subject'] = mail.subject
    msg.attach(mail.data)
    
    #handle attachments in mail
    if mail.attachments:
        for attach in mail.attachments:
                   
            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)
     
    for to in mail.to:
        msg['To'] = to
        
        mailServer = smtplib.SMTP("smtp.gmail.com", 587)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(mail.sender, mail.password)
        mailServer.sendmail(mail.password, to, msg.as_string())
        # Should be mailServer.quit(), but that crashes...
        mailServer.close() 
        
def sendText(text):
    pass

def addMessage(message):
    msg = Message.get_by(message_id=message.id)
    if msg:
        raise HelperServiceException(101, "Message is already present. Please try updation api instead")
    msg = Message();
    msg.message_id = message.id
    msg.message = message.message
    session.commit()
    
def getMessage(message_id):
    msg = Message.get_by(id=message_id)
    message = Msg()
    message.id = msg.message_id
    message.message = msg.message
    return message

def updateMessage(id, message):
    msg = Message.get_by(message_id=id)
    if msg:
        msg.message = message
        session.commit()
    else:
        raise HelperServiceException(101, "message could not be found with id %d" %(id))

def getSubstitutedMessage(id, params):
    #get the message first
    msg = Message.get_by(message_id=id)
    
    if not msg:
        raise HelperServiceException(101, "message could not be found with id %d" %(id))
    if params:
        s = Template(msg.message)
        s = s.safe_substitute(params)
        return s
    else:
        return msg.message