root/trunk/umitCore/Email.py @ 3176

Revision 3176, 6.3 kB (checked in by luis, 5 years ago)

- Moved msgfmt.py from umitCore to utils/msgfmt.py (External libs now lives on utils/ )
- Added header in Email (all files have enviroment path )
- Added umit menu (xpm format) - necessary for alternatives window managers, like fluxbox, etc
- Added new files to manifest file
- Fixed deletion *.mo files in sdist (overwrite sdist.run ) and add xpm file to data_files - setup.py trunk/install_scripts/unix/setup.py

(Includes commit r3175)

Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Copyright (C) 2005-2006 Insecure.Com LLC.
5# Copyright (C) 2007-2008 Adriano Monteiro Marques
6#
7# Authors: Adriano Monteiro Marques <adriano@umitproject.org>
8#          Frederico Silva Ribeiro <ribeiro.fsilva@gmail.com>
9#          Guilherme Polo <ggpolo@gmail.com>
10#
11# This program is free software; you can redistribute it and/or modify
12# it under the terms of the GNU General Public License as published by
13# the Free Software Foundation; either version 2 of the License, or
14# (at your option) any later version.
15#
16# This program is distributed in the hope that it will be useful,
17# but WITHOUT ANY WARRANTY; without even the implied warranty of
18# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19# GNU General Public License for more details.
20#
21# You should have received a copy of the GNU General Public License
22# along with this program; if not, write to the Free Software
23# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24
25import os.path
26
27from smtplib import SMTP
28from socket import sslerror
29from email.MIMEMultipart import MIMEMultipart
30from email.MIMEBase import MIMEBase
31from email.MIMEText import MIMEText
32from email.Utils import formatdate
33from email import Encoders
34
35from umitCore.UmitLogging import log
36
37class Email(object):
38    """This class is intended to provide a simple interface for sending
39    Umit emails. The mailing system is going to be used for mailing results
40    to users, automatically. The arguments you should care about setting
41    are as follows:
42
43
44    from_addr - The address from which the email should be sent (Required)
45
46    login - If the mail server doesn't do relay, you should authenticate
47    with a login
48
49    login_passwd - If the mail server doesn't do relay, you should
50    authenticate on it
51
52    to_addr - The email address to where the scan result should be
53    sent (Required)
54
55    server - The address of the SMTP server which will deliver the
56    email (Required)
57
58    localdomain - If you want to send your email using your own domain,
59    set it here.
60
61    msg - The scan result or msg you want to send (Required)
62
63    tls - True if the server require tls. False if not.
64
65    port - The port which the SMTP server is listening
66
67    subject - The subject of the mail (Required)"""
68
69    def __init__(self,
70                 from_addr,
71                 to_addr,
72                 server,
73                 localdomain=None,
74                 login=None,
75                 login_passwd=None,
76                 tls=False,
77                 port=25):
78
79        self.from_addr = from_addr
80        self.to_addr = to_addr
81        self.server = server
82        self.localdomain = localdomain
83        self.login = login
84        self.login_passwd = login_passwd
85        self.tls = tls
86        self.port = port
87
88
89    def connect(self):
90        log.debug(">>> Connecting to smtp server at %s:%s as %s" \
91                  % (self.server, self.port, self.localdomain))
92
93        self.email_server = SMTP(self.server, self.port, self.localdomain)
94        log.debug(">>> Connected!")
95
96        log.debug(">>> EHLO %s" % self.from_addr)
97        self.email_server.ehlo(self.from_addr)
98
99        if self.tls:
100            log.debug(">>> STARTTLS")
101            self.email_server.starttls()
102           
103            log.debug(">>> EHLO %s" % self.from_addr)
104            self.email_server.ehlo(self.from_addr)
105
106        if self.login_passwd:
107            log.debug(">>> LOGIN %s@%s" % (self.login, self.login_passwd))
108            self.email_server.login(self.login, self.login_passwd)
109
110
111    def sendmail(self, subject, msg, attach=False):
112        try:
113            self.email_server
114        except AttributeError:
115            self.connect()
116
117        try:
118            mail = self.create_mail(subject, msg, attach)
119            log.debug(">>> SENDMAIL \n%s" % mail.as_string())
120
121            self.email_server.sendmail(self.from_addr, 
122                                       self.to_addr, 
123                                       mail.as_string())
124           
125            log.debug(">>> SENT!")
126            return True
127        except sslerror:
128            return True
129
130    def close(self):
131        log.debug(">>> CLOSE")
132        self.email_server.close()
133        del(self.email_server)
134
135
136    def __del__(self):
137        """Always close the connection when the instance turns into garbage
138        and is deleted or his reference counts turns to zero.
139        """
140        self.close()
141
142
143    def create_mail(self, subject, msg, attach=False):
144        mail = MIMEMultipart()
145        mail['From'] = self.from_addr
146
147        if type(self.to_addr) == type([]):
148            mail['To'] = ', '.join(self.to_addr)
149        else:
150            mail['To'] = self.to_addr
151
152        mail['Date'] = formatdate(localtime=True)
153        mail['Subject'] = subject
154        mail.attach(MIMEText(msg))
155
156        if attach:
157            if type(attach) == type(""):
158                attach = (attach,)
159           
160            for atc in attach:
161                part = MIMEBase('application', "octet-stream")
162                part.set_payload(open(atc,"rb").read())
163                Encoders.encode_base64(part)
164                part.add_header('Content-Disposition', 
165                        'attachment; filename="%s"' % os.path.basename(atc))
166                mail.attach(part)
167
168        return mail
169
170
171if __name__ == "__main__":
172    """msg = '''From: yourgmailhere@gmail.com\r
173To: targetgmailhere@gmail.com\r
174Subject: Farting a lot!\r
175\r
176
177Gotcha!
178
179\n.\n'''
180   
181    email = SMTP("smtp.gmail.com")
182    email.ehlo("yourgmailhere@gmail.com")
183    email.starttls()
184    email.ehlo("yourgmailhere@gmail.com")
185    email.login("yourgmailhere@gmail.com", "yourpasswdhere")
186    email.sendmail("yourgmailhere@gmail.com", "targetgmailhere@gmail.com", msg)
187    email.quit()"""
188   
189    email = Email("from_addr@gmail.com",
190                  "to_addr@gmail.com",
191                  "smtp.gmail.com",
192                  None,
193                  "login@gmail.com",
194                  "passwd",
195                  True)
196
197    email.sendmail("Teste1", 
198                   "Mensagem de teste 1", 
199                   ["/Users/adriano/umit/trunk/umit",
200                    "/Users/adriano/umit/trunk/setup.py"])
201
202    email.sendmail("Teste2", 
203                   "Mensagem de teste 2",
204                   "/Users/adriano/umit/trunk/setup.nsi")
205   
206    email.sendmail("Teste3", 
207                   "Mensagem de teste 3")
208
209    del(email)
Note: See TracBrowser for help on using the browser.