[FIX] mail: partners with missing/invalid emails must not halt notifications to others
[odoo/odoo.git] / openerp / addons / base / ir / ir_mail_server.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2011-2012 OpenERP S.A (<http://www.openerp.com>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
19 #
20 ##############################################################################
21
22 from email.MIMEText import MIMEText
23 from email.MIMEBase import MIMEBase
24 from email.MIMEMultipart import MIMEMultipart
25 from email.Charset import Charset
26 from email.Header import Header
27 from email.utils import formatdate, make_msgid, COMMASPACE, getaddresses, formataddr
28 from email import Encoders
29 import logging
30 import re
31 import smtplib
32 import threading
33
34 from openerp import SUPERUSER_ID
35 from openerp.osv import osv, fields
36 from openerp.tools.translate import _
37 from openerp.tools import html2text
38 import openerp.tools as tools
39
40 # ustr was originally from tools.misc.
41 # it is moved to loglevels until we refactor tools.
42 from openerp.loglevels import ustr
43
44 _logger = logging.getLogger(__name__)
45
46 class MailDeliveryException(osv.except_osv):
47     """Specific exception subclass for mail delivery errors"""
48     def __init__(self, name, value):
49         super(MailDeliveryException, self).__init__(name, value)
50
51 class WriteToLogger(object):
52     """debugging helper: behave as a fd and pipe to logger at the given level"""
53     def __init__(self, logger, level=logging.DEBUG):
54         self.logger = logger
55         self.level = level
56
57     def write(self, s):
58         self.logger.log(self.level, s)
59
60
61 def try_coerce_ascii(string_utf8):
62     """Attempts to decode the given utf8-encoded string
63        as ASCII after coercing it to UTF-8, then return
64        the confirmed 7-bit ASCII string.
65
66        If the process fails (because the string
67        contains non-ASCII characters) returns ``None``.
68     """
69     try:
70         string_utf8.decode('ascii')
71     except UnicodeDecodeError:
72         return
73     return string_utf8
74
75 def encode_header(header_text):
76     """Returns an appropriate representation of the given header value,
77        suitable for direct assignment as a header value in an
78        email.message.Message. RFC2822 assumes that headers contain
79        only 7-bit characters, so we ensure it is the case, using
80        RFC2047 encoding when needed.
81
82        :param header_text: unicode or utf-8 encoded string with header value
83        :rtype: string | email.header.Header
84        :return: if ``header_text`` represents a plain ASCII string,
85                 return the same 7-bit string, otherwise returns an email.header.Header
86                 that will perform the appropriate RFC2047 encoding of
87                 non-ASCII values.
88     """
89     if not header_text: return ""
90     # convert anything to utf-8, suitable for testing ASCIIness, as 7-bit chars are
91     # encoded as ASCII in utf-8
92     header_text_utf8 = tools.ustr(header_text).encode('utf-8')
93     header_text_ascii = try_coerce_ascii(header_text_utf8)
94     # if this header contains non-ASCII characters,
95     # we'll need to wrap it up in a message.header.Header
96     # that will take care of RFC2047-encoding it as
97     # 7-bit string.
98     return header_text_ascii if header_text_ascii\
99          else Header(header_text_utf8, 'utf-8')
100
101 def encode_header_param(param_text):
102     """Returns an appropriate RFC2047 encoded representation of the given
103        header parameter value, suitable for direct assignation as the
104        param value (e.g. via Message.set_param() or Message.add_header())
105        RFC2822 assumes that headers contain only 7-bit characters,
106        so we ensure it is the case, using RFC2047 encoding when needed.
107
108        :param param_text: unicode or utf-8 encoded string with header value
109        :rtype: string
110        :return: if ``param_text`` represents a plain ASCII string,
111                 return the same 7-bit string, otherwise returns an
112                 ASCII string containing the RFC2047 encoded text.
113     """
114     # For details see the encode_header() method that uses the same logic
115     if not param_text: return ""
116     param_text_utf8 = tools.ustr(param_text).encode('utf-8')
117     param_text_ascii = try_coerce_ascii(param_text_utf8)
118     return param_text_ascii if param_text_ascii\
119          else Charset('utf8').header_encode(param_text_utf8)
120
121 # TODO master, remove me, no longer used internaly
122 name_with_email_pattern = re.compile(r'("[^<@>]+")\s*<([^ ,<@]+@[^> ,]+)>')
123 address_pattern = re.compile(r'([^ ,<@]+@[^> ,]+)')
124
125 def extract_rfc2822_addresses(text):
126     """Returns a list of valid RFC2822 addresses
127        that can be found in ``source``, ignoring 
128        malformed ones and non-ASCII ones.
129     """
130     if not text: return []
131     candidates = address_pattern.findall(tools.ustr(text).encode('utf-8'))
132     return filter(try_coerce_ascii, candidates)
133
134 def encode_rfc2822_address_header(header_text):
135     """If ``header_text`` contains non-ASCII characters,
136        attempts to locate patterns of the form
137        ``"Name" <address@domain>`` and replace the
138        ``"Name"`` portion by the RFC2047-encoded
139        version, preserving the address part untouched.
140     """
141     def encode_addr(addr):
142         name, email = addr
143         if not try_coerce_ascii(name):
144             name = str(Header(name, 'utf-8'))
145         return formataddr((name, email))
146
147     addresses = getaddresses([tools.ustr(header_text).encode('utf-8')])
148     return COMMASPACE.join(map(encode_addr, addresses))
149
150
151 class ir_mail_server(osv.osv):
152     """Represents an SMTP server, able to send outgoing emails, with SSL and TLS capabilities."""
153     _name = "ir.mail_server"
154
155     NO_VALID_RECIPIENT = ("At least one valid recipient address should be "
156                           "specified for outgoing emails (To/Cc/Bcc)")
157
158     _columns = {
159         'name': fields.char('Description', size=64, required=True, select=True),
160         'smtp_host': fields.char('SMTP Server', size=128, required=True, help="Hostname or IP of SMTP server"),
161         'smtp_port': fields.integer('SMTP Port', size=5, required=True, help="SMTP Port. Usually 465 for SSL, and 25 or 587 for other cases."),
162         'smtp_user': fields.char('Username', size=64, help="Optional username for SMTP authentication"),
163         'smtp_pass': fields.char('Password', size=64, help="Optional password for SMTP authentication"),
164         'smtp_encryption': fields.selection([('none','None'),
165                                              ('starttls','TLS (STARTTLS)'),
166                                              ('ssl','SSL/TLS')],
167                                             string='Connection Security', required=True,
168                                             help="Choose the connection encryption scheme:\n"
169                                                  "- None: SMTP sessions are done in cleartext.\n"
170                                                  "- TLS (STARTTLS): TLS encryption is requested at start of SMTP session (Recommended)\n"
171                                                  "- SSL/TLS: SMTP sessions are encrypted with SSL/TLS through a dedicated port (default: 465)"),
172         'smtp_debug': fields.boolean('Debugging', help="If enabled, the full output of SMTP sessions will "
173                                                        "be written to the server log at DEBUG level"
174                                                        "(this is very verbose and may include confidential info!)"),
175         'sequence': fields.integer('Priority', help="When no specific mail server is requested for a mail, the highest priority one "
176                                                     "is used. Default priority is 10 (smaller number = higher priority)"),
177         'active': fields.boolean('Active')
178     }
179
180     _defaults = {
181          'smtp_port': 25,
182          'active': True,
183          'sequence': 10,
184          'smtp_encryption': 'none',
185      }
186
187     def __init__(self, *args, **kwargs):
188         # Make sure we pipe the smtplib outputs to our own DEBUG logger
189         if not isinstance(smtplib.stderr, WriteToLogger):
190             logpiper = WriteToLogger(_logger)
191             smtplib.stderr = logpiper
192             smtplib.stdout = logpiper
193         super(ir_mail_server, self).__init__(*args,**kwargs)
194
195     def name_get(self, cr, uid, ids, context=None):
196         return [(a["id"], "(%s)" % (a['name'])) for a in self.read(cr, uid, ids, ['name'], context=context)]
197
198     def test_smtp_connection(self, cr, uid, ids, context=None):
199         for smtp_server in self.browse(cr, uid, ids, context=context):
200             smtp = False
201             try:
202                 smtp = self.connect(smtp_server.smtp_host, smtp_server.smtp_port, user=smtp_server.smtp_user,
203                                     password=smtp_server.smtp_pass, encryption=smtp_server.smtp_encryption,
204                                     smtp_debug=smtp_server.smtp_debug)
205             except Exception, e:
206                 raise osv.except_osv(_("Connection Test Failed!"), _("Here is what we got instead:\n %s") % tools.ustr(e))
207             finally:
208                 try:
209                     if smtp: smtp.quit()
210                 except Exception:
211                     # ignored, just a consequence of the previous exception
212                     pass
213         raise osv.except_osv(_("Connection Test Succeeded!"), _("Everything seems properly set up!"))
214
215     def connect(self, host, port, user=None, password=None, encryption=False, smtp_debug=False):
216         """Returns a new SMTP connection to the give SMTP server, authenticated
217            with ``user`` and ``password`` if provided, and encrypted as requested
218            by the ``encryption`` parameter.
219         
220            :param host: host or IP of SMTP server to connect to
221            :param int port: SMTP port to connect to
222            :param user: optional username to authenticate with
223            :param password: optional password to authenticate with
224            :param string encryption: optional, ``'ssl'`` | ``'starttls'``
225            :param bool smtp_debug: toggle debugging of SMTP sessions (all i/o
226                               will be output in logs)
227         """
228         if encryption == 'ssl':
229             if not 'SMTP_SSL' in smtplib.__all__:
230                 raise osv.except_osv(
231                              _("SMTP-over-SSL mode unavailable"),
232                              _("Your OpenERP Server does not support SMTP-over-SSL. You could use STARTTLS instead."
233                                "If SSL is needed, an upgrade to Python 2.6 on the server-side should do the trick."))
234             connection = smtplib.SMTP_SSL(host, port)
235         else:
236             connection = smtplib.SMTP(host, port)
237         connection.set_debuglevel(smtp_debug)
238         if encryption == 'starttls':
239             # starttls() will perform ehlo() if needed first
240             # and will discard the previous list of services
241             # after successfully performing STARTTLS command,
242             # (as per RFC 3207) so for example any AUTH
243             # capability that appears only on encrypted channels
244             # will be correctly detected for next step
245             connection.starttls()
246
247         if user:
248             # Attempt authentication - will raise if AUTH service not supported
249             # The user/password must be converted to bytestrings in order to be usable for
250             # certain hashing schemes, like HMAC.
251             # See also bug #597143 and python issue #5285
252             user = tools.ustr(user).encode('utf-8')
253             password = tools.ustr(password).encode('utf-8') 
254             connection.login(user, password)
255         return connection
256
257     def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False,
258                attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None,
259                body_alternative=None, subtype_alternative='plain'):
260         """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it.
261
262            :param string email_from: sender email address
263            :param list email_to: list of recipient addresses (to be joined with commas) 
264            :param string subject: email subject (no pre-encoding/quoting necessary)
265            :param string body: email body, of the type ``subtype`` (by default, plaintext).
266                                If html subtype is used, the message will be automatically converted
267                                to plaintext and wrapped in multipart/alternative, unless an explicit
268                                ``body_alternative`` version is passed.
269            :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative``
270            :param string reply_to: optional value of Reply-To header
271            :param string object_id: optional tracking identifier, to be included in the message-id for
272                                     recognizing replies. Suggested format for object-id is "res_id-model",
273                                     e.g. "12345-crm.lead".
274            :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'),
275                                   must match the format of the ``body`` parameter. Default is 'plain',
276                                   making the content part of the mail "text/plain".
277            :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain'
278                                               or 'html'). Default is 'plain'.
279            :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string
280                                     containing the bytes of the attachment
281            :param list email_cc: optional list of string values for CC header (to be joined with commas)
282            :param list email_bcc: optional list of string values for BCC header (to be joined with commas)
283            :param dict headers: optional map of headers to set on the outgoing mail (may override the
284                                 other headers, including Subject, Reply-To, Message-Id, etc.)
285            :rtype: email.message.Message (usually MIMEMultipart)
286            :return: the new RFC2822 email message
287         """
288         email_from = email_from or tools.config.get('email_from')
289         assert email_from, "You must either provide a sender address explicitly or configure "\
290                            "a global sender address in the server configuration or with the "\
291                            "--email-from startup parameter."
292
293         # Note: we must force all strings to to 8-bit utf-8 when crafting message,
294         #       or use encode_header() for headers, which does it automatically.
295
296         headers = headers or {} # need valid dict later
297
298         if not email_cc: email_cc = []
299         if not email_bcc: email_bcc = []
300         if not body: body = u''
301
302         email_body_utf8 = ustr(body).encode('utf-8')
303         email_text_part = MIMEText(email_body_utf8, _subtype=subtype, _charset='utf-8')
304         msg = MIMEMultipart()
305
306         if not message_id:
307             if object_id:
308                 message_id = tools.generate_tracking_message_id(object_id)
309             else:
310                 message_id = make_msgid()
311         msg['Message-Id'] = encode_header(message_id)
312         if references:
313             msg['references'] = encode_header(references)
314         msg['Subject'] = encode_header(subject)
315         msg['From'] = encode_rfc2822_address_header(email_from)
316         del msg['Reply-To']
317         if reply_to:
318             msg['Reply-To'] = encode_rfc2822_address_header(reply_to)
319         else:
320             msg['Reply-To'] = msg['From']
321         msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to))
322         if email_cc:
323             msg['Cc'] = encode_rfc2822_address_header(COMMASPACE.join(email_cc))
324         if email_bcc:
325             msg['Bcc'] = encode_rfc2822_address_header(COMMASPACE.join(email_bcc))
326         msg['Date'] = formatdate()
327         # Custom headers may override normal headers or provide additional ones
328         for key, value in headers.iteritems():
329             msg[ustr(key).encode('utf-8')] = encode_header(value)
330
331         if subtype == 'html' and not body_alternative and html2text:
332             # Always provide alternative text body ourselves if possible.
333             text_utf8 = tools.html2text(email_body_utf8.decode('utf-8')).encode('utf-8')
334             alternative_part = MIMEMultipart(_subtype="alternative")
335             alternative_part.attach(MIMEText(text_utf8, _charset='utf-8', _subtype='plain'))
336             alternative_part.attach(email_text_part)
337             msg.attach(alternative_part)
338         elif body_alternative:
339             # Include both alternatives, as specified, within a multipart/alternative part
340             alternative_part = MIMEMultipart(_subtype="alternative")
341             body_alternative_utf8 = ustr(body_alternative).encode('utf-8')
342             alternative_body_part = MIMEText(body_alternative_utf8, _subtype=subtype_alternative, _charset='utf-8')
343             alternative_part.attach(alternative_body_part)
344             alternative_part.attach(email_text_part)
345             msg.attach(alternative_part)
346         else:
347             msg.attach(email_text_part)
348
349         if attachments:
350             for (fname, fcontent) in attachments:
351                 filename_rfc2047 = encode_header_param(fname)
352                 part = MIMEBase('application', "octet-stream")
353
354                 # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail
355                 # so we fix it by using RFC2047 encoding for the filename instead.
356                 part.set_param('name', filename_rfc2047)
357                 part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047)
358
359                 part.set_payload(fcontent)
360                 Encoders.encode_base64(part)
361                 msg.attach(part)
362         return msg
363
364     def send_email(self, cr, uid, message, mail_server_id=None, smtp_server=None, smtp_port=None,
365                    smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False,
366                    context=None):
367         """Sends an email directly (no queuing).
368
369         No retries are done, the caller should handle MailDeliveryException in order to ensure that
370         the mail is never lost.
371
372         If the mail_server_id is provided, sends using this mail server, ignoring other smtp_* arguments.
373         If mail_server_id is None and smtp_server is None, use the default mail server (highest priority).
374         If mail_server_id is None and smtp_server is not None, use the provided smtp_* arguments.
375         If both mail_server_id and smtp_server are None, look for an 'smtp_server' value in server config,
376         and fails if not found.
377
378         :param message: the email.message.Message to send. The envelope sender will be extracted from the
379                         ``Return-Path`` or ``From`` headers. The envelope recipients will be
380                         extracted from the combined list of ``To``, ``CC`` and ``BCC`` headers.
381         :param mail_server_id: optional id of ir.mail_server to use for sending. overrides other smtp_* arguments.
382         :param smtp_server: optional hostname of SMTP server to use
383         :param smtp_encryption: optional TLS mode, one of 'none', 'starttls' or 'ssl' (see ir.mail_server fields for explanation)
384         :param smtp_port: optional SMTP port, if mail_server_id is not passed
385         :param smtp_user: optional SMTP user, if mail_server_id is not passed
386         :param smtp_password: optional SMTP password to use, if mail_server_id is not passed
387         :param smtp_debug: optional SMTP debug flag, if mail_server_id is not passed
388         :return: the Message-ID of the message that was just sent, if successfully sent, otherwise raises
389                  MailDeliveryException and logs root cause.
390         """
391         smtp_from = message['Return-Path'] or message['From']
392         assert smtp_from, "The Return-Path or From header is required for any outbound email"
393
394         # The email's "Envelope From" (Return-Path), and all recipient addresses must only contain ASCII characters.
395         from_rfc2822 = extract_rfc2822_addresses(smtp_from)
396         assert from_rfc2822, ("Malformed 'Return-Path' or 'From' address: %r - "
397                               "It should contain one valid plain ASCII email") % smtp_from
398         # use last extracted email, to support rarities like 'Support@MyComp <support@mycompany.com>'
399         smtp_from = from_rfc2822[-1]
400         email_to = message['To']
401         email_cc = message['Cc']
402         email_bcc = message['Bcc']
403         smtp_to_list = filter(None, tools.flatten(map(extract_rfc2822_addresses,[email_to, email_cc, email_bcc])))
404         assert smtp_to_list, self.NO_VALID_RECIPIENT
405
406         # Do not actually send emails in testing mode!
407         if getattr(threading.currentThread(), 'testing', False):
408             _logger.log(logging.TEST, "skip sending email in test mode")
409             return message['Message-Id']
410
411         # Get SMTP Server Details from Mail Server
412         mail_server = None
413         if mail_server_id:
414             mail_server = self.browse(cr, SUPERUSER_ID, mail_server_id)
415         elif not smtp_server:
416             mail_server_ids = self.search(cr, SUPERUSER_ID, [], order='sequence', limit=1)
417             if mail_server_ids:
418                 mail_server = self.browse(cr, SUPERUSER_ID, mail_server_ids[0])
419
420         if mail_server:
421             smtp_server = mail_server.smtp_host
422             smtp_user = mail_server.smtp_user
423             smtp_password = mail_server.smtp_pass
424             smtp_port = mail_server.smtp_port
425             smtp_encryption = mail_server.smtp_encryption
426             smtp_debug = smtp_debug or mail_server.smtp_debug
427         else:
428             # we were passed an explicit smtp_server or nothing at all
429             smtp_server = smtp_server or tools.config.get('smtp_server')
430             smtp_port = tools.config.get('smtp_port', 25) if smtp_port is None else smtp_port
431             smtp_user = smtp_user or tools.config.get('smtp_user')
432             smtp_password = smtp_password or tools.config.get('smtp_password')
433             if smtp_encryption is None and tools.config.get('smtp_ssl'):
434                 smtp_encryption = 'starttls' # STARTTLS is the new meaning of the smtp_ssl flag as of v7.0
435
436         if not smtp_server:
437             raise osv.except_osv(
438                          _("Missing SMTP Server"),
439                          _("Please define at least one SMTP server, or provide the SMTP parameters explicitly."))
440
441         try:
442             message_id = message['Message-Id']
443
444             # Add email in Maildir if smtp_server contains maildir.
445             if smtp_server.startswith('maildir:/'):
446                 from mailbox import Maildir
447                 maildir_path = smtp_server[8:]
448                 mdir = Maildir(maildir_path, factory=None, create = True)
449                 mdir.add(message.as_string(True))
450                 return message_id
451
452             try:
453                 smtp = self.connect(smtp_server, smtp_port, smtp_user, smtp_password, smtp_encryption or False, smtp_debug)
454                 smtp.sendmail(smtp_from, smtp_to_list, message.as_string())
455             finally:
456                 try:
457                     # Close Connection of SMTP Server
458                     smtp.quit()
459                 except Exception:
460                     # ignored, just a consequence of the previous exception
461                     pass
462         except Exception, e:
463             msg = _("Mail delivery failed via SMTP server '%s'.\n%s: %s") % (tools.ustr(smtp_server),
464                                                                              e.__class__.__name__,
465                                                                              tools.ustr(e))
466             _logger.exception(msg)
467             raise MailDeliveryException(_("Mail delivery failed"), msg)
468         return message_id
469
470     def on_change_encryption(self, cr, uid, ids, smtp_encryption):
471         if smtp_encryption == 'ssl':
472             result = {'value': {'smtp_port': 465}}
473             if not 'SMTP_SSL' in smtplib.__all__:
474                 result['warning'] = {'title': _('Warning'),
475                                      'message': _('Your server does not seem to support SSL, you may want to try STARTTLS instead')}
476         else:
477             result = {'value': {'smtp_port': 25}}
478         return result
479
480 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: