Subversion Repositories SmartDukaan

Rev

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