2 """SMTP reporting for the Breadcrumb server."""
4 # Copyright (C) 2008 Laurens Van Houtven <lvh at laurensvh.be>
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 import email
.mime
.text
23 from common
import PointQueueHandler
, Renderer
25 class SMTPHandler(PointQueueHandler
, Renderer
):
26 """Sends mail digests of a number of points."""
27 def __init__(self
, source
, destinations
,
28 subject
= "Breadcrumb tracking report",
29 server
= 'localhost', port
= 25,
30 threshold
= 10, rendertype
= None,
32 PointQueueHandler
.__init
__(self
, threshold
= threshold
)
33 Renderer
.__init
__(self
, type = rendertype
)
36 self
.destinations
= destinations
.split(',')
38 self
.usetls
, self
.threshold
= usetls
, threshold
40 for id in ['\x30', '\x32']:
41 self
.identifiers
.add(id)
43 logging
.debug("Initialized SMTPHandler for %s:%s, from: %s, to: %s" \
44 % (host
, port
, source
, destinations
))
46 def send(self
, out_string
):
47 """Sends the given sring using SMTP."""
48 mime_string
= self
.mime_encode(out_string
)
49 self
._raw
_send
(mime_string
)
51 def mime_encode(self
, message
):
52 """Encodes a given message in MIME format."""
53 mime
= email
.mime
.text
.MIMEText(message
)
55 mime
.set_unixfrom('author')
56 destinations
= ', '.join(self
.destinations
)
57 mime
['To'] = email
.utils
.formataddr(('Recipient', destinations
))
58 mime
['From'] = email
.utils
.formataddr(('Author', self
.source
))
59 mime
['Subject'] = self
.subject
61 logging
.debug("Email message mime encoding finished...")
63 return mime
.as_string()
65 def _raw_send(self
, mimestring
):
66 """Passes the MIME string to the SMTP server for sending."""
67 server
= smtplib
.SMTP("%s:%s" % (self
.hostname
, self
.port
))
70 server
.set_debuglevel(True)
73 if self
.usetls
and server
.has_extn('STARTTLS'):
74 logging
.debug('SMTP server has TLS support, starting TLS...')
78 if self
.username
is not None:
79 logging
.debug("Sending SMTP credentials...")
80 server
.login(self
.username
, self
.password
)
82 server
.sendmail(self
.source
, self
.destinations
, message
)
85 logging
.error("Message sending failed!")