Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
15385 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
from dtr.storage import DataService
14
from dtr.storage.DataService import Users
15
from elixir import *
16
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
17
from sqlalchemy.sql import func
18
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
19
    between
20
import datetime
21
from datetime import date,timedelta
22
 
23
 
24
class Email:
25
    """
26
    This class handles the creation and sending of email messages
27
    via SMTP.  This class also handles attachments and can send
28
    HTML messages.  The code comes from various places around
29
    the net and from my own brain.
30
    """
31
    def __init__(self, smtpServer):
32
        """
33
        Create a new empty email message object.
34
 
35
        @param smtpServer: The address of the SMTP server
36
        @type smtpServer: String
37
        """
38
        self._textBody = None
39
        self._htmlBody = None
40
        self._subject = ""
41
        self._smtpServer = smtpServer
42
        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])?)$")
15417 manish.sha 43
        self._bcc = ['amit.sirohi@shop2020.in'] 
15385 manish.sha 44
        self.clearRecipients()
45
        self.clearAttachments()
46
 
47
    def send(self):
48
        """
49
        Send the email message represented by this object.
50
        """
51
        # Validate message
52
        if self._textBody is None and self._htmlBody is None:
53
            raise Exception("Error! Must specify at least one body type (HTML or Text)")
54
        if len(self._to) == 0:
55
            raise Exception("Must specify at least one recipient")
56
 
57
        # Create the message part
58
        if self._textBody is not None and self._htmlBody is None:
59
            msg = MIMEText(self._textBody, "plain")
60
        elif self._textBody is None and self._htmlBody is not None:
61
            msg = MIMEText(self._htmlBody, "html")
62
        else:
63
            msg = MIMEMultipart("alternative")
64
            msg.attach(MIMEText(self._textBody, "plain"))
65
            msg.attach(MIMEText(self._htmlBody, "html"))
66
        # Add attachments, if any
67
        if len(self._attach) != 0:
68
            tmpmsg = msg
69
            msg = MIMEMultipart()
70
            msg.attach(tmpmsg)
71
        for fname,attachname in self._attach:
72
            if not os.path.exists(fname):
73
                print "File '%s' does not exist.  Not attaching to email." % fname
74
                continue
75
            if not os.path.isfile(fname):
76
                print "Attachment '%s' is not a file.  Not attaching to email." % fname
77
                continue
78
            # Guess at encoding type
79
            ctype, encoding = mimetypes.guess_type(fname)
80
            if ctype is None or encoding is not None:
81
                # No guess could be made so use a binary type.
82
                ctype = 'application/octet-stream'
83
            maintype, subtype = ctype.split('/', 1)
84
            if maintype == 'text':
85
                fp = open(fname)
86
                attach = MIMEText(fp.read(), _subtype=subtype)
87
                fp.close()
88
            elif maintype == 'image':
89
                fp = open(fname, 'rb')
90
                attach = MIMEImage(fp.read(), _subtype=subtype)
91
                fp.close()
92
            elif maintype == 'audio':
93
                fp = open(fname, 'rb')
94
                attach = MIMEAudio(fp.read(), _subtype=subtype)
95
                fp.close()
96
            else:
97
                fp = open(fname, 'rb')
98
                attach = MIMEBase(maintype, subtype)
99
                attach.set_payload(fp.read())
100
                fp.close()
101
                # Encode the payload using Base64
102
                encoders.encode_base64(attach)
103
            # Set the filename parameter
104
            if attachname is None:
105
                filename = os.path.basename(fname)
106
            else:
107
                filename = attachname
108
            attach.add_header('Content-Disposition', 'attachment', filename=filename)
109
            msg.attach(attach)
110
        # Some header stuff
111
        msg['Subject'] = self._subject
112
        msg['From'] = self._from
113
        msg['To'] = ", ".join(self._to)
15416 manish.sha 114
        msg['Bcc'] = ", ".join(self._bcc)
15385 manish.sha 115
        msg.preamble = "You need a MIME enabled mail reader to see this message"
116
        # Send message
117
        msg = msg.as_string()
118
        server = smtplib.SMTP(self._smtpServer)
15417 manish.sha 119
        self._to.append(self._bcc)
15385 manish.sha 120
        server.sendmail(self._from, self._to, msg)
121
        server.quit()
122
 
123
    def setSubject(self, subject):
124
        """
125
        Set the subject of the email message.
126
        """
127
        self._subject = subject
128
 
129
    def setFrom(self, address):
130
        """
131
        Set the email sender.
132
        """
133
        if not self.validateEmailAddress(address):
134
            raise Exception("Invalid email address '%s'" % address)
135
        self._from = address
136
 
137
    def clearRecipients(self):
138
        """
139
        Remove all currently defined recipients for
140
        the email message.
141
        """
142
        self._to = []
143
 
144
    def addRecipient(self, address):
145
        """
146
        Add a new recipient to the email message.
147
        """
148
        if not self.validateEmailAddress(address):
149
            raise Exception("Invalid email address '%s'" % address)
150
        self._to.append(address)
151
 
152
    def setTextBody(self, body):
153
        """
154
        Set the plain text body of the email message.
155
        """
156
        self._textBody = body
157
 
158
    def setHtmlBody(self, body):
159
        """
160
        Set the HTML portion of the email message.
161
        """
162
        self._htmlBody = body
163
 
164
    def clearAttachments(self):
165
        """
166
        Remove all file attachments.
167
        """
168
        self._attach = []
169
 
170
    def addAttachment(self, fname, attachname=None):
171
        """
172
        Add a file attachment to this email message.
173
 
174
        @param fname: The full path and file name of the file
175
                      to attach.
176
        @type fname: String
177
        @param attachname: This will be the name of the file in
178
                           the email message if set.  If not set
179
                           then the filename will be taken from
180
                           the fname parameter above.
181
        @type attachname: String
182
        """
183
        if fname is None:
184
            return
185
        self._attach.append( (fname, attachname) )
186
 
187
    def validateEmailAddress(self, address):
188
        """
189
        Validate the specified email address.
190
 
191
        @return: True if valid, False otherwise
192
        @rtype: Boolean
193
        """
194
        if self._reEmail.search(address) is None:
195
            return False
196
        return True
197
 
198
if __name__ == "__main__":
199
    # Run some tests
200
    DataService.initialize(db_hostname="localhost")
201
    currentTime = datetime.datetime.date(datetime.datetime.now())
202
    previousDay = datetime.datetime(currentTime.year,currentTime.month, currentTime.day, 0, 0)- timedelta(days=1)
203
    mTo = session.query(Users.email).filter(Users.mobile_number == None).filter(Users.created >= previousDay).all()
204
    #mTo = ["manish.sharma@shop2020.in", "manas.kapoor@shop2020.in"]
205
    mFrom = "ProfitMandi<help@profitmandi.com>"
15417 manish.sha 206
    #mTo = ["manish.sharma@shop2020.in"]
15385 manish.sha 207
 
208
    for receipient in mTo:
209
        m = Email('localhost')
210
        m.setFrom(mFrom)
211
        print receipient[0]
15417 manish.sha 212
        m.addRecipient(receipient[0])
213
        #m.addRecipient('manish.sharma@shop2020.in')
15416 manish.sha 214
 
15385 manish.sha 215
        message="""
216
<html>
217
    <body>
218
    <pre>		
219
    Dear Customer,
220
 
221
Thanks for showing your interest in Profitmandi android App.
222
 
223
This app is useful for frequent buyers of mobiles, tabs ad related products. Profitmandi recommends the most profitable online deals.
224
 
225
Only users having an invite code can use this app.
226
 
227
Request you to please provide your contact no so that we can get in touch with you and activate you on this app.
228
 
229
Regards,
230
Profitmandi Team
231
+91-8826894203
232
</pre>
233
    </body>
234
    </html>"""
235
 
236
        m.setSubject("ProfitMandi")
237
        m.setTextBody(None)
238
        m.setHtmlBody(message)
239
        m.send()
15417 manish.sha 240
 
15385 manish.sha 241
 
242
    if session.is_active:
243
        print "session is active. closing it."
244
        session.close()