Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
15114 manish.sha 1
from email import encoders
2
from email.mime.audio import MIMEAudio
3
from email.mime.base import MIMEBase
4
from email.mime.image import MIMEImage
5
from email.mime.multipart import MIMEMultipart
6
from email.mime.text import MIMEText
7
import mimetypes
8
import os
9
import re
10
import smtplib
11
import csv
12
import MySQLdb
13
 
14
class Email:
15
    """
16
    This class handles the creation and sending of email messages
17
    via SMTP.  This class also handles attachments and can send
18
    HTML messages.  The code comes from various places around
19
    the net and from my own brain.
20
    """
21
    def __init__(self, smtpServer):
22
        """
23
        Create a new empty email message object.
24
 
25
        @param smtpServer: The address of the SMTP server
26
        @type smtpServer: String
27
        """
28
        self._textBody = None
29
        self._htmlBody = None
30
        self._subject = ""
31
        self._smtpServer = smtpServer
32
        self._reEmail = re.compile("^([\\w \\._]+\\<[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\>|[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)$")
33
        self.clearRecipients()
34
        self.clearAttachments()
35
 
36
    def send(self):
37
        """
38
        Send the email message represented by this object.
39
        """
40
        # Validate message
41
        if self._textBody is None and self._htmlBody is None:
42
            raise Exception("Error! Must specify at least one body type (HTML or Text)")
43
        if len(self._to) == 0:
44
            raise Exception("Must specify at least one recipient")
45
 
46
        # Create the message part
47
        if self._textBody is not None and self._htmlBody is None:
48
            msg = MIMEText(self._textBody, "plain")
49
        elif self._textBody is None and self._htmlBody is not None:
50
            msg = MIMEText(self._htmlBody, "html")
51
        else:
52
            msg = MIMEMultipart("alternative")
53
            msg.attach(MIMEText(self._textBody, "plain"))
54
            msg.attach(MIMEText(self._htmlBody, "html"))
55
        # Add attachments, if any
56
        if len(self._attach) != 0:
57
            tmpmsg = msg
58
            msg = MIMEMultipart()
59
            msg.attach(tmpmsg)
60
        for fname,attachname in self._attach:
61
            if not os.path.exists(fname):
62
                print "File '%s' does not exist.  Not attaching to email." % fname
63
                continue
64
            if not os.path.isfile(fname):
65
                print "Attachment '%s' is not a file.  Not attaching to email." % fname
66
                continue
67
            # Guess at encoding type
68
            ctype, encoding = mimetypes.guess_type(fname)
69
            if ctype is None or encoding is not None:
70
                # No guess could be made so use a binary type.
71
                ctype = 'application/octet-stream'
72
            maintype, subtype = ctype.split('/', 1)
73
            if maintype == 'text':
74
                fp = open(fname)
75
                attach = MIMEText(fp.read(), _subtype=subtype)
76
                fp.close()
77
            elif maintype == 'image':
78
                fp = open(fname, 'rb')
79
                attach = MIMEImage(fp.read(), _subtype=subtype)
80
                fp.close()
81
            elif maintype == 'audio':
82
                fp = open(fname, 'rb')
83
                attach = MIMEAudio(fp.read(), _subtype=subtype)
84
                fp.close()
85
            else:
86
                fp = open(fname, 'rb')
87
                attach = MIMEBase(maintype, subtype)
88
                attach.set_payload(fp.read())
89
                fp.close()
90
                # Encode the payload using Base64
91
                encoders.encode_base64(attach)
92
            # Set the filename parameter
93
            if attachname is None:
94
                filename = os.path.basename(fname)
95
            else:
96
                filename = attachname
97
            attach.add_header('Content-Disposition', 'attachment', filename=filename)
98
            msg.attach(attach)
99
        # Some header stuff
100
        msg['Subject'] = self._subject
101
        msg['From'] = self._from
102
        msg['To'] = ", ".join(self._to)
103
        msg.preamble = "You need a MIME enabled mail reader to see this message"
104
        # Send message
105
        msg = msg.as_string()
106
        server = smtplib.SMTP(self._smtpServer)
107
        server.sendmail(self._from, self._to, msg)
108
        server.quit()
109
 
110
    def setSubject(self, subject):
111
        """
112
        Set the subject of the email message.
113
        """
114
        self._subject = subject
115
 
116
    def setFrom(self, address):
117
        """
118
        Set the email sender.
119
        """
120
        if not self.validateEmailAddress(address):
121
            raise Exception("Invalid email address '%s'" % address)
122
        self._from = address
123
 
124
    def clearRecipients(self):
125
        """
126
        Remove all currently defined recipients for
127
        the email message.
128
        """
129
        self._to = []
130
 
131
    def addRecipient(self, address):
132
        """
133
        Add a new recipient to the email message.
134
        """
135
        if not self.validateEmailAddress(address):
136
            raise Exception("Invalid email address '%s'" % address)
137
        self._to.append(address)
138
 
139
    def setTextBody(self, body):
140
        """
141
        Set the plain text body of the email message.
142
        """
143
        self._textBody = body
144
 
145
    def setHtmlBody(self, body):
146
        """
147
        Set the HTML portion of the email message.
148
        """
149
        self._htmlBody = body
150
 
151
    def clearAttachments(self):
152
        """
153
        Remove all file attachments.
154
        """
155
        self._attach = []
156
 
157
    def addAttachment(self, fname, attachname=None):
158
        """
159
        Add a file attachment to this email message.
160
 
161
        @param fname: The full path and file name of the file
162
                      to attach.
163
        @type fname: String
164
        @param attachname: This will be the name of the file in
165
                           the email message if set.  If not set
166
                           then the filename will be taken from
167
                           the fname parameter above.
168
        @type attachname: String
169
        """
170
        if fname is None:
171
            return
172
        self._attach.append( (fname, attachname) )
173
 
174
    def validateEmailAddress(self, address):
175
        """
176
        Validate the specified email address.
177
 
178
        @return: True if valid, False otherwise
179
        @rtype: Boolean
180
        """
181
        if self._reEmail.search(address) is None:
182
            return False
183
        return True
184
 
185
if __name__ == "__main__":
186
    # Run some tests
187
    mFrom = "dtr@shop2020.in"
188
    mTo = ["manish.sharma@shop2020.in"]
189
    m = Email('localhost')
190
    m.setFrom(mFrom)
191
    for receipient in mTo:
192
        m.addRecipient(receipient)
193
    #reader = csv.reader(open('/root/UserGroupData.tsv'), delimiter="\t" )
194
 
15116 manish.sha 195
    db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
15114 manish.sha 196
    cursor = db.cursor()
197
 
198
    sql = "select  GROUP_CONCAT( distinct x.user_ids ) user_ids, x.mobileNos, GROUP_CONCAT( distinct x.imeis) imeis, GROUP_CONCAT(distinct x.referrers) referrers from (SELECT GROUP_CONCAT( distinct u.id ) user_ids, GROUP_CONCAT(distinct u.mobile_number) mobileNos, d.imeinumber imeis, GROUP_CONCAT(distinct u.referrer) referrers FROM  `users` u LEFT JOIN devices d ON u.id = d.user_id where d.imeinumber is not null and u.mobile_number is not null GROUP BY d.imeinumber) as x group by x.mobileNos UNION SELECT GROUP_CONCAT( distinct u.id ) user_ids, u.mobile_number mobileNos, GROUP_CONCAT( distinct d.imeinumber) imeis, GROUP_CONCAT(distinct u.referrer) referrers FROM  `users` u LEFT JOIN devices d ON u.id = d.user_id where d.imeinumber is null and u.mobile_number is not null GROUP BY u.mobile_number UNION SELECT GROUP_CONCAT( distinct u.id ) user_ids, u.mobile_number mobileNos, GROUP_CONCAT( distinct d.imeinumber) imeis, GROUP_CONCAT(distinct u.referrer) referrers FROM  `users` u LEFT JOIN devices d ON u.id = d.user_id where d.imeinumber is null and u.mobile_number is null and LOWER(u.referrer) not like 'emp%' and LOWER(u.referrer) not like 'crm%' and LOWER(u.referrer) not like 'fos%' GROUP BY u.referrer"
199
 
200
    cursor.execute(sql)
201
    result_data = cursor.fetchall()
202
    if result_data:
203
        for record_data in result_data:
204
            print record_data[0]
205
 
206
'''    
207
    # initialize rownum variable
208
    rownum = 0
209
 
210
    message="""<html>
211
                <body>"""
212
 
213
    message +="""<table>"""
214
 
215
    # generate table contents
216
    for row in reader: # Read a single row from the CSV file
217
        if rownum == 0:
218
            message +="""<tr>"""
219
            for column in row:
220
                message +="""<th> """ + column + """ </th>"""
221
            message +="""</tr>"""
222
 
223
        #write all other rows    
224
        else:
225
            message +="""<tr>"""   
226
            for column in row:
227
                message +="""<th> """ + column + """ </th>"""
228
            message +="""</tr>"""
229
 
230
        #increment row count    
231
        rownum += 1
232
 
233
    # write </table> tag
234
    message +="""</table>
235
                </body>
236
                </html>"""
237
 
238
    # Simple Plain Text Email
239
    m.setSubject("User Group Data")
240
    m.setTextBody(None)
241
    m.setHtmlBody(message)
242
    m.addAttachment("/root/Snapdeal_Pending_Orders_Report_Analysis.xls")
243
    m.send()
244
'''