Subversion Repositories SmartDukaan

Rev

Rev 5194 | Rev 5299 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
4795 mandeep.dh 1
from email.mime.text import MIMEText
2
from shop2020.clients.HelperClient import HelperClient
1425 varun.gupt 3
from shop2020.thriftpy.utils.ttypes import Mail
4909 amar.kumar 4
from shop2020.utils.daemon import Daemon
5
 
4795 mandeep.dh 6
import sched
7
import time
8
import smtplib
9
import sys
4909 amar.kumar 10
import optparse
1425 varun.gupt 11
 
12
 
4909 amar.kumar 13
class EmailSender(Daemon):
14
    def __init__(self, logfile='/var/log/utils/emailsender/emailsender.log', pidfile='/var/run/email-sender.pid'):
15
        Daemon.__init__(self, pidfile, stdout=logfile, stderr=logfile)
3425 varun.gupt 16
        print 'EmailSender initiated at', time.time()
1425 varun.gupt 17
        self.email_schedular = sched.scheduler(time.time, time.sleep)
3425 varun.gupt 18
        self.time_to_sleep = 2
19
        self.authenticate()
20
 
21
    def authenticate(self):
3400 varun.gupt 22
        try:
3425 varun.gupt 23
            print "Attempting authentication at", time.time()
3987 mandeep.dh 24
            self.mailServer = smtplib.SMTP("smtp.sendgrid.net", 587)
3400 varun.gupt 25
 
3987 mandeep.dh 26
            self.sender = "shop2020mail"
27
            self.password = "shop2020"
3400 varun.gupt 28
            self.mailServer.ehlo()
29
            self.mailServer.starttls()
30
            self.mailServer.ehlo()
31
            self.mailServer.login(self.sender, self.password)
3425 varun.gupt 32
            print "Authentication successful", time.time()
3400 varun.gupt 33
 
34
        except smtplib.SMTPConnectError as e:
4795 mandeep.dh 35
            print 'Specified host did not respond correctly', e        
3400 varun.gupt 36
        except smtplib.SMTPHeloError as e:
37
            print 'The server did not reply properly to the HELO greeting.', e
38
        except smtplib.SMTPAuthenticationError as e:
39
            print 'The server did not accept the username/password combination.', e
40
        except smtplib.SMTPException as e:
41
            print e
4795 mandeep.dh 42
        except Exception as e:
43
            print sys.exc_info()[0]
44
            print e
3425 varun.gupt 45
 
1425 varun.gupt 46
    def sendMail(self, mail):
47
        if mail.sender:
48
            mail.data = "This mail is sent by " + mail.sender + "\n" + mail.data
49
 
1560 varun.gupt 50
        msg = MIMEText(mail.data, 'html')
1425 varun.gupt 51
 
5194 anupam.sin 52
        msg['To'] = ';'.join(mail.to)
1566 varun.gupt 53
 
1425 varun.gupt 54
        if mail.sender:
55
            msg['From'] = mail.sender
56
        else:
57
            msg['From'] = "help@saholic.com"
58
        msg['Subject'] = mail.subject
59
 
3425 varun.gupt 60
        try:
5194 anupam.sin 61
            rs = self.mailServer.sendmail(self.password, mail.to, msg.as_string())
3425 varun.gupt 62
 
63
        except smtplib.SMTPServerDisconnected as e:
64
            print 'Server Disconnected at', time.time()
65
            self.authenticate()
5194 anupam.sin 66
            rs = self.mailServer.sendmail(self.password, mail.to, msg.as_string())
3425 varun.gupt 67
 
68
        print msg['To']
1425 varun.gupt 69
        # Should be mailServer.quit(), but that crashes...
70
        return rs
71
 
72
    def send(self):
73
        print "Despatch stared at ", time.time()
74
        helper_client = HelperClient().get_client()
75
 
3086 rajveer 76
        emails_to_be_dispatched = helper_client.getEmailsToBeSent()
1425 varun.gupt 77
        print len(emails_to_be_dispatched)
78
 
79
        for email in emails_to_be_dispatched:
5194 anupam.sin 80
            toList = []
81
            for to in email.emailTo.split(';') :
5197 anupam.sin 82
                if to.strip() :
83
                    toList.append(to.strip())
5194 anupam.sin 84
            mail = Mail( toList, email.subject, email.body, None, None, None)
1425 varun.gupt 85
 
3977 varun.gupt 86
            try:
87
                send_result = self.sendMail(mail)
4796 mandeep.dh 88
            except Exception as e:
89
                print sys.exc_info()[0]
90
                print e
3977 varun.gupt 91
                print 'Error occurred sending emails. Will retry.'
4971 mandeep.dh 92
                continue
93
 
94
            if len(send_result) == 0:
95
                print "Sent at", time.time()
96
                helper_client.markEmailAsSent(email.id)
97
            else:
98
                print "Failed sending email. Id:", " Time:", time.time()
3977 varun.gupt 99
 
1425 varun.gupt 100
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
101
 
4909 amar.kumar 102
    def run(self):
1425 varun.gupt 103
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
104
        self.email_schedular.run()
105
 
4909 amar.kumar 106
if __name__ == "__main__":
107
    parser = optparse.OptionParser()
108
    parser.add_option("-l", "--logfile", dest="logfile",
109
                      type="string",
110
                      help="Log all output to LOG_FILE",
111
                      )
112
    parser.add_option("-i", "--pidfile", dest="pidfile",
113
                      type="string",
114
                      help="Write the PID to pidfile")
115
    (options, args) = parser.parse_args()
116
    daemon = EmailSender(options.logfile, options.pidfile)
117
    if len(args) == 0:
118
        daemon.run()
119
    elif len(args) == 1:
120
        if 'start' == args[0]:
121
            daemon.start()
122
        elif 'stop' == args[0]:
123
            daemon.stop()
124
        elif 'restart' == args[0]:
125
            daemon.restart()
126
        else:
127
            print "Unknown command"
128
            sys.exit(2)
129
        sys.exit(0)
130
    else:
131
        print "usage: %s start|stop|restart" % sys.argv[0]
132
        sys.exit(2)