Subversion Repositories SmartDukaan

Rev

Rev 15008 | Rev 15010 | 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
6906 rajveer 3
from shop2020.clients.TransactionClient import TransactionClient
1425 varun.gupt 4
from shop2020.thriftpy.utils.ttypes import Mail
4909 amar.kumar 5
from shop2020.utils.daemon import Daemon
5299 mandeep.dh 6
import optparse
4795 mandeep.dh 7
import sched
8
import smtplib
9
import sys
5299 mandeep.dh 10
import time
6906 rajveer 11
import os
12
from email.MIMEMultipart import MIMEMultipart
13
from email.MIMEBase import MIMEBase
14
from email.MIMEText import MIMEText
15
from email import Encoders
1425 varun.gupt 16
 
17
 
4909 amar.kumar 18
class EmailSender(Daemon):
8056 rajveer 19
    def __init__(self, logfile='/var/log/utils/emailsender/emailsender.log', pidfile='/var/run/email-sender.pid', count = 0):
4909 amar.kumar 20
        Daemon.__init__(self, pidfile, stdout=logfile, stderr=logfile)
3425 varun.gupt 21
        print 'EmailSender initiated at', time.time()
1425 varun.gupt 22
        self.email_schedular = sched.scheduler(time.time, time.sleep)
8111 anupam.sin 23
        self.time_to_sleep = 10
8056 rajveer 24
        self.count = count
8111 anupam.sin 25
        self.exceptionCount = {}
3425 varun.gupt 26
        self.authenticate()
27
 
28
    def authenticate(self):
3400 varun.gupt 29
        try:
5299 mandeep.dh 30
            print "Attempting authentication at ", time.time()
31
            self.sendGridMailServer = smtplib.SMTP("smtp.sendgrid.net", 587)
6016 rajveer 32
            self.sendGridSender = "euser"
5299 mandeep.dh 33
            self.sendGridPassword = "shop2020"
34
            self.sendGridMailServer.ehlo()
35
            self.sendGridMailServer.starttls()
36
            self.sendGridMailServer.ehlo()
37
            self.sendGridMailServer.login(self.sendGridSender, self.sendGridPassword)
38
 
8069 anupam.sin 39
#            self.gmailServer = smtplib.SMTP("smtp.gmail.com", 587)
40
#            self.gmailSender = "help@shop2020.in"
41
#            self.gmailPassword = "5h0p2o2o"
42
#            self.gmailServer.ehlo()
43
#            self.gmailServer.starttls()
44
#            self.gmailServer.ehlo()
45
#            self.gmailServer.login(self.gmailSender, self.gmailPassword)            
3425 varun.gupt 46
            print "Authentication successful", time.time()
3400 varun.gupt 47
 
48
        except smtplib.SMTPConnectError as e:
4795 mandeep.dh 49
            print 'Specified host did not respond correctly', e        
3400 varun.gupt 50
        except smtplib.SMTPHeloError as e:
51
            print 'The server did not reply properly to the HELO greeting.', e
52
        except smtplib.SMTPAuthenticationError as e:
53
            print 'The server did not accept the username/password combination.', e
54
        except smtplib.SMTPException as e:
55
            print e
4795 mandeep.dh 56
        except Exception as e:
57
            print sys.exc_info()[0]
58
            print e
3425 varun.gupt 59
 
6906 rajveer 60
    def get_attachment_part(self, document, filename):
61
        part = MIMEBase('application', 'octet-stream')
62
        part.set_payload(document)
63
        Encoders.encode_base64(part)
6947 rajveer 64
        part.add_header('Content-Disposition', 'attachment; filename=%s' % filename + "-insurance-policy.pdf")
6906 rajveer 65
        return part
66
 
1425 varun.gupt 67
    def sendMail(self, mail):
5864 rajveer 68
        msg = MIMEMultipart()
15009 manish.sha 69
        if not mail.emailFrom and mail.emailFrom.strip() != "" and mail.emailFrom is not None:
15006 manish.sha 70
            msg['From'] = mail.emailFrom
71
        else:
72
            msg['From'] = "Saholic <help@saholic.com>"
5864 rajveer 73
        msg['To'] = ', '.join(mail.emailTo)
74
        msg['Cc'] = ', '.join(mail.cc)
75
        #msg['Bcc'] = ', '.join(mail.bcc)
76
        msg['Subject'] = mail.subject
1425 varun.gupt 77
 
5864 rajveer 78
        html_msg = MIMEText(mail.body, 'html')
79
        msg.attach(html_msg)
6906 rajveer 80
 
81
        if mail.emailType == "DeliverySuccess":
82
            tclient = TransactionClient().get_client()
13363 manish.sha 83
            if '-' in mail.source:
84
                subOrders = tclient.getGroupOrdersByLogisticsTxnId(mail.source)
85
                singleOrderId = 0
86
                for order in subOrders:
87
                    if order.insurer:
88
                        singleOrderId = order.id
89
                        break
90
                if singleOrderId > 0:
13476 kshitij.so 91
                    document = tclient.getDocument(1, int(singleOrderId))
13363 manish.sha 92
                    if document != bin(0):
93
                        msg.attach(self.get_attachment_part(document, mail.source))
94
            else:
95
                document = tclient.getDocument(1, int(mail.source))
96
                if document != bin(0):
97
                    msg.attach(self.get_attachment_part(document, mail.source))
6906 rajveer 98
 
3425 varun.gupt 99
        try:
5299 mandeep.dh 100
            self.setMailServerAndPassword(mail)
7550 anupam.sin 101
            rs = self.mailServer.sendmail(self.password, mail.emailTo + mail.cc + mail.bcc + ['backup@saholic.com'], msg.as_string())
3425 varun.gupt 102
        except smtplib.SMTPServerDisconnected as e:
103
            print 'Server Disconnected at', time.time()
104
            self.authenticate()
8066 rajveer 105
            rs = self.mailServer.sendmail(self.password, mail.emailTo + mail.cc + mail.bcc + ['backup@saholic.com'], msg.as_string())
3425 varun.gupt 106
 
107
        print msg['To']
1425 varun.gupt 108
        # Should be mailServer.quit(), but that crashes...
109
        return rs
110
 
5299 mandeep.dh 111
    def setMailServerAndPassword(self, mail):
5828 rajveer 112
        self.mailServer = self.sendGridMailServer
113
        self.password = self.sendGridPassword
114
 
115
#        self.mailServer = self.gmailServer
116
#        self.password = self.gmailPassword
117
#
118
#        for receiver in mail.to:
119
#            if not receiver.endswith('@saholic.com') and not receiver.endswith('@shop2020.in'):
120
#                self.mailServer = self.sendGridMailServer
121
#                self.password = self.sendGridPassword
122
#                break
5299 mandeep.dh 123
 
1425 varun.gupt 124
    def send(self):
8111 anupam.sin 125
        '''
126
        If sending fails for a mail for more than 10 times then we will exit the sender.
127
        This is done to avoid sending a mail many times if one of the address in the 'emailTo' list is wrong.
128
        '''
8056 rajveer 129
        if self.count > 10:
130
            print str(self.count)
131
            print "Number of failed attempts is more than 10. Exiting"
132
            sys.exit()
8111 anupam.sin 133
 
134
        for emailId in self.exceptionCount.keys() :
135
            if self.exceptionCount[emailId] > 10:
8119 anupam.sin 136
                print "Number of exceptions for email id : " + str(emailId) + " is : " + str(self.exceptionCount[emailId]) + ". Exiting"
8111 anupam.sin 137
                sys.exit()
138
 
1425 varun.gupt 139
        print "Despatch stared at ", time.time()
140
        helper_client = HelperClient().get_client()
141
 
3086 rajveer 142
        emails_to_be_dispatched = helper_client.getEmailsToBeSent()
1425 varun.gupt 143
        print len(emails_to_be_dispatched)
144
 
145
        for email in emails_to_be_dispatched:
3977 varun.gupt 146
            try:
8069 anupam.sin 147
                send_result = "error"
5864 rajveer 148
                send_result = self.sendMail(email)
4796 mandeep.dh 149
            except Exception as e:
150
                print sys.exc_info()[0]
151
                print e
8119 anupam.sin 152
                print 'Error occurred sending email with id - ' + str(email.id)
8111 anupam.sin 153
                if self.exceptionCount.has_key(email.id) :
154
                    self.exceptionCount[email.id] = self.exceptionCount[email.id] + 1
155
                else :
156
                    self.exceptionCount[email.id] = 1
157
                continue
4971 mandeep.dh 158
 
159
            if len(send_result) == 0:
160
                print "Sent at", time.time()
161
                helper_client.markEmailAsSent(email.id)
8111 anupam.sin 162
                if self.exceptionCount.has_key(email.id) :
163
                    del self.exceptionCount[email.id]
4971 mandeep.dh 164
            else:
165
                print "Failed sending email. Id:", " Time:", time.time()
8056 rajveer 166
                self.count = self.count + 1
3977 varun.gupt 167
 
1425 varun.gupt 168
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
169
 
4909 amar.kumar 170
    def run(self):
1425 varun.gupt 171
        self.email_schedular.enter(self.time_to_sleep, 1, self.send, ())
172
        self.email_schedular.run()
173
 
4909 amar.kumar 174
if __name__ == "__main__":
175
    parser = optparse.OptionParser()
176
    parser.add_option("-l", "--logfile", dest="logfile",
177
                      type="string",
178
                      help="Log all output to LOG_FILE",
179
                      )
180
    parser.add_option("-i", "--pidfile", dest="pidfile",
181
                      type="string",
182
                      help="Write the PID to pidfile")
183
    (options, args) = parser.parse_args()
8056 rajveer 184
    daemon = EmailSender(options.logfile, options.pidfile, 0)
4909 amar.kumar 185
    if len(args) == 0:
186
        daemon.run()
187
    elif len(args) == 1:
188
        if 'start' == args[0]:
189
            daemon.start()
190
        elif 'stop' == args[0]:
191
            daemon.stop()
192
        elif 'restart' == args[0]:
193
            daemon.restart()
194
        else:
195
            print "Unknown command"
196
            sys.exit(2)
197
        sys.exit(0)
198
    else:
199
        print "usage: %s start|stop|restart" % sys.argv[0]
200
        sys.exit(2)