EmailDocument.py 27.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
##############################################################################
#
# Copyright (c) 2007 Nexedi SA and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

import re, types
from DateTime import DateTime
Yusei Tahara's avatar
Yusei Tahara committed
32
from AccessControl import ClassSecurityInfo, Unauthorized
33
from Products.ERP5Type.Accessor.Constant import PropertyGetter as ConstantGetter
34 35
from Products.CMFCore.utils import _checkPermission
from Products.ERP5Type import Permissions, PropertySheet
36 37
from Products.ERP5.Document.TextDocument import TextDocument
from Products.ERP5.Document.File import File
38 39
from Products.ERP5.Document.Document import ConversionError
from Products.ERP5.mixin.document_proxy import DocumentProxyMixin, DocumentProxyError
40
from Products.ERP5.Tool.NotificationTool import buildEmailMessage
41
from Products.ERP5Type.Utils import guessEncodingFromText
42
from MethodObject import Method
43 44
from zLOG import LOG, INFO

45 46 47 48 49 50 51 52
try:
  from Products.MimetypesRegistry.common import MimeTypeException
except ImportError:
  class MimeTypeException(Exception):
    """
    A dummy exception class which is used when MimetypesRegistry product is
    not installed yet.
    """
53 54

from email import message_from_string
55
from email.Header import decode_header, HeaderParseError
56
from email.Utils import parsedate_tz, mktime_tz
57 58 59 60 61

DEFAULT_TEXT_FORMAT = 'text/html'
COMMASPACE = ', '
_MARKER = []

Nicolas Delaby's avatar
Nicolas Delaby committed
62
filename_regexp = 'name="([^"]*)"'
63

64 65 66 67 68 69 70 71 72

class EmailDocumentProxyMixin(DocumentProxyMixin):
  """
  Provides access to documents referenced by the causality field
  """
  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  security.declareProtected(Permissions.AccessContentsInformation, 'hasFile')
  def hasFile(self):
    """
    hasFile is used in many parts of EmailDocument in order to know
    if there is some document content to manage. We define it here
    in order to say that there is no document if we are not able to
    get the proxy
    """
    has_file = False
    try:
      proxied_document = self.getProxiedDocument()
      has_file = proxied_document.hasFile()
    except DocumentProxyError:
      pass
    return has_file

  security.declareProtected(Permissions.AccessContentsInformation, 'getTextContent')
  def getTextContent(self, default=_MARKER):
    result = None
    try:
      proxied_document = self.getProxiedDocument()
      result = proxied_document.getTextContent(default=default)
    except DocumentProxyError:
      pass
    if default is _MARKER:
      return result
    return result or default
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

class ProxiedMethod(Method):
  """
  Accessort that retrieve methods directly on the proxy
  """

  def __init__(self, proxied_method_id):
    self.proxied_method_id = proxied_method_id

  def __call__(self, instance, *args, **kw):
    proxied_document = instance.getProxiedDocument()
    method = getattr(proxied_document, self.proxied_method_id)
    return method(*args, **kw)

# generate all proxy method on EmailDocumentProxyMixin
115
for method_id in ('getContentType',
116 117 118 119 120 121 122 123
                  'getContentInformation', 'getAttachmentData',
                  'getAttachmentInformationList'):
  EmailDocumentProxyMixin.security.declareProtected(
       Permissions.AccessContentsInformation,
       method_id)
  setattr(EmailDocumentProxyMixin, method_id,
      ProxiedMethod(method_id))

124
class EmailDocument(TextDocument):
125 126 127 128 129 130 131 132 133 134
  """
    EmailDocument is a File which stores its metadata in a form which
    is similar to a TextDocument.
    A Text Document which stores raw HTML and can 
    convert it to various formats.
  """

  meta_type = 'ERP5 Email Document'
  portal_type = 'Email Document'
  add_permission = Permissions.AddPortalContent
135 136
  # XXX must be removed later - only event is a delivery
  isDelivery = ConstantGetter('isDelivery', value=True)
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Version
                    , PropertySheet.Document
                    , PropertySheet.ExternalDocument
                    , PropertySheet.Url
                    , PropertySheet.TextDocument
                    , PropertySheet.Arrow
                    , PropertySheet.Task
                    , PropertySheet.ItemAggregation
155 156
                    , PropertySheet.EmailHeader
                    , PropertySheet.Reference
Nicolas Delaby's avatar
Nicolas Delaby committed
157
                    , PropertySheet.Data
158 159 160 161 162 163 164 165 166 167
                    )

  # Mail processing API
  def _getMessage(self):
    result = getattr(self, '_v_message', None)
    if result is None:
      result = message_from_string(str(self.getData()))
      self._v_message = result
    return result

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
  def _getMessageTextPart(self):
    """
    Return the main text part of the message data

    Based on rfc: http://tools.ietf.org/html/rfc2046#section-5.1.4)
    """
    # Default value if no text is found
    found_part = None

    part_list = [self._getMessage()]
    while part_list:
      part = part_list.pop(0)
      if part.is_multipart():
        if part.get_content_subtype() == 'alternative':
          # Try to get the favourite text format defined on preference
          preferred_content_type = self.getPortalObject().portal_preferences.\
                                         getPreferredTextFormat('text/html')
          favourite_part = None
          for subpart in part.get_payload():
            if subpart.get_content_type() == preferred_content_type:
              part_list.insert(0, subpart)
            else:
              part_list.append(subpart)
        else:
          part_list.extend(part.get_payload())
      elif part.get_content_maintype() == 'text':
        found_part = part
        break

    return found_part

Nicolas Delaby's avatar
Nicolas Delaby committed
199 200
  security.declareProtected(Permissions.AccessContentsInformation,
                            'isSupportBaseDataConversion')
201 202 203 204 205
  def isSupportBaseDataConversion(self):
    """
    """
    return False

206 207 208 209 210
  security.declareProtected(Permissions.AccessContentsInformation, 'getContentInformation')
  def getContentInformation(self):
    """
    Returns the content information from the header information.
    This is used by the metadata discovery system.
211 212 213

    Header information is converted in UTF-8 since this is the standard
    way of representing strings in ERP5.
214 215 216
    """
    result = {}
    for (name, value) in self._getMessage().items():
217 218 219 220 221 222 223 224
      try: 
        decoded_header = decode_header(value)
      except HeaderParseError, error_message:
        decoded_header = ()
        LOG('EmailDocument.getContentInformation', INFO,
            'Failed to decode %s header of %s with error: %s' %
            (name, self.getPath(), error_message))
      for text, encoding in decoded_header:
225 226
        try:
          if encoding is not None:
227
            text = text.decode(encoding).encode('utf-8')
228 229
          else:
            text = text.decode().encode('utf-8')
230
        except (UnicodeDecodeError, LookupError), error_message:
231
          encoding = guessEncodingFromText(text, content_type='text/plain')
232
          if encoding is not None:
233 234 235 236
            try:
              text = text.decode(encoding).encode('utf-8')
            except (UnicodeDecodeError, LookupError), error_message:
              text = repr(text)[1:-1]
237
          else:
238
            text = repr(text)[1:-1]
239 240
        if name in result:
          result[name] = '%s %s' % (result[name], text)
241
        else:
242
          result[name] = text
243 244 245 246 247 248 249 250 251 252
    return result

  security.declareProtected(Permissions.AccessContentsInformation, 'getAttachmentInformationList')
  def getAttachmentInformationList(self, **kw):
    """
    Returns a list of dictionnaries for every attachment. Each dictionnary
    represents the metadata of the attachment.
    **kw - support for listbox (TODO: improve it)
    """
    result = []
253
    for i, part in enumerate(self._getMessage().walk()):
254 255 256 257
      if not part.is_multipart():
        kw = dict(part.items())
        kw['uid'] = 'part_%s' % i
        kw['index'] = i
Nicolas Delaby's avatar
Nicolas Delaby committed
258 259
        filename = part.get_filename()
        if not filename:
260 261 262
          # get_filename return name only from Content-Disposition header
          # of the message but sometimes this value is stored in
          # Content-Type header
263 264
          content_type_header = kw.get('Content-Type',
                                                    kw.get('Content-type', ''))
Nicolas Delaby's avatar
Nicolas Delaby committed
265
          filename_list = re.findall(filename_regexp,
266 267
                                      content_type_header,
                                      re.MULTILINE)
Nicolas Delaby's avatar
Nicolas Delaby committed
268 269 270 271
          if filename_list:
            filename = filename_list[0]
        if filename:
          kw['filename'] = filename
272
        else:
273
          content_disposition = kw.get('Content-Disposition', 
Nicolas Delaby's avatar
typo  
Nicolas Delaby committed
274
                                           kw.get('Content-disposition', None))
275 276 277 278 279 280
          prefix = 'part_'
          if content_disposition:
            if content_disposition.split(';')[0] == 'attachment':
              prefix = 'attachment_'
            elif content_disposition.split(';')[0] == 'inline':
              prefix = 'inline_'
Nicolas Delaby's avatar
Nicolas Delaby committed
281
          kw['filename'] = '%s%s' % (prefix, i)
282
        kw['content_type'] = part.get_content_type()
283 284 285 286
        result.append(kw)
    return result

  security.declareProtected(Permissions.AccessContentsInformation, 'getAttachmentData')
287
  def getAttachmentData(self, index, REQUEST=None):
288 289 290
    """
    Returns the decoded data of an attachment.
    """
Nicolas Delaby's avatar
Nicolas Delaby committed
291
    for i, part in enumerate(self._getMessage().walk()):
292
      if index == i:
293 294
        # This part should be handled in skin script
        # but it was a bit easier to access items here
295 296
        kw = dict(part.items())
        content_type = part.get_content_type()
297
        if REQUEST is not None:
Nicolas Delaby's avatar
Nicolas Delaby committed
298 299
          filename = part.get_filename()
          if not filename:
300 301 302
            # get_filename return name only from Content-Disposition header
            # of the message but sometimes this value is stored in
            # Content-Type header
303 304
            content_type_header = kw.get('Content-Type',
                                                    kw.get('Content-type', ''))
Nicolas Delaby's avatar
Nicolas Delaby committed
305
            filename_list = re.findall(filename_regexp,
306 307
                                        content_type_header,
                                        re.MULTILINE)
Nicolas Delaby's avatar
Nicolas Delaby committed
308 309
            if filename_list:
              filename = filename_list[0]
310 311
          RESPONSE = REQUEST.RESPONSE
          RESPONSE.setHeader('Accept-Ranges', 'bytes')
Nicolas Delaby's avatar
Nicolas Delaby committed
312
          if content_type and filename:
Nicolas Delaby's avatar
Nicolas Delaby committed
313 314
            RESPONSE.setHeader('Content-Type', content_type)
            RESPONSE.setHeader('Content-disposition',
Nicolas Delaby's avatar
Nicolas Delaby committed
315
                               'attachment; filename="%s"' % filename)
Nicolas Delaby's avatar
Nicolas Delaby committed
316 317 318 319 320 321 322 323 324
        if 'text/html' in content_type:
          # Strip out html content in safe mode.
          mime, content = self.convert(format='html',
                                       text_content=part.get_payload(decode=1),
                                       index=index) # add index to generate
                                       # a unique cache key per attachment
        else:
          content = part.get_payload(decode=1)
        return content
325 326
    return KeyError, "No attachment with index %s" % index

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
  # Helper methods which override header property sheet
  security.declareProtected(Permissions.AccessContentsInformation, 'getSender')
  def getSender(self, *args):
    """
    """
    if not self.hasData():
      return self._baseGetSender(*args)
    return self.getContentInformation().get('From', *args)

  security.declareProtected(Permissions.AccessContentsInformation, 'getRecipient')
  def getRecipient(self, *args):
    """
    """
    if not self.hasData():
      return self._baseGetRecipient(*args)
    return self.getContentInformation().get('To', *args)

  security.declareProtected(Permissions.AccessContentsInformation, 'getCcRecipient')
  def getCcRecipient(self, *args):
    """
    """
    if not self.hasData():
      return self._baseGetCcRecipient(*args)
    return self.getContentInformation().get('Cc', *args)

  security.declareProtected(Permissions.AccessContentsInformation, 'getGroupingReference')
  def getGroupingReference(self, *args):
    """
      The reference refers here to the Thread of messages.
    """
    if not self.hasData():
      result = self._baseGetGroupingReference(*args)
    else:
      if not len(args):
361
        args = (self._baseGetGroupingReference(),)
362 363
      result = self.getContentInformation().get('References', *args)
      if result:
364 365 366
        result = result.split() # Only take the first reference
        if result:
          result = result[0]
367 368
    if result:
      return result
Nicolas Delaby's avatar
Nicolas Delaby committed
369
    return self.getFilename(*args)
370

371 372 373
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getSourceReference')
  def getSourceReference(self, *args):
374 375 376 377 378
    """
      The Message-ID is considered here as the source reference
      of the message on the sender side (source)
    """
    if not self.hasData():
379
      return self._baseGetSourceReference(*args)
380
    if not len(args):
381
      args = (self._baseGetSourceReference(),)
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    content_information = self.getContentInformation()
    return content_information.get('Message-ID') or content_information.get('Message-Id', *args)

  security.declareProtected(Permissions.AccessContentsInformation, 'getDestinationReference')
  def getDestinationReference(self, *args):
    """
      The In-Reply-To is considered here as the reference
      of the thread on the side of a former sender (destination)

      This is a hack which can be acceptable since 
      the reference of an email is shared.
    """
    if not self.hasData():
      return self._baseGetDestinationReference(*args)
    if not len(args):
      args = (self._baseGetDestinationReference(),)
    return self.getContentInformation().get('In-Reply-To', *args)

400 401 402 403
  # Overriden methods
  security.declareProtected(Permissions.AccessContentsInformation, 'getTitle')
  def getTitle(self, default=_MARKER):
    """
404
    Returns the title from the mail subject
405 406 407 408 409 410 411
    """
    if not self.hasFile():
      # Return the standard text content if no file was provided
      if default is _MARKER:
        return self._baseGetTitle()
      else:
        return self._baseGetTitle(default)
Yusei Tahara's avatar
Yusei Tahara committed
412 413
    subject = self.getContentInformation().get('Subject', '')
    # Remove all newlines
Nicolas Delaby's avatar
Nicolas Delaby committed
414 415
    subject = subject.replace('\r', '')
    subject = subject.replace('\n', '')
Yusei Tahara's avatar
Yusei Tahara committed
416
    return subject
417
  
418 419 420
  security.declareProtected(Permissions.AccessContentsInformation, 'getStartDate')
  def getStartDate(self, default=_MARKER):
    """
421
    Returns the date from the mail date
422 423 424 425 426 427 428 429 430
    """
    if not self.hasFile():
      # Return the standard start date if no file was provided
      if default is _MARKER:
        return self._baseGetStartDate()
      else:
        return self._baseGetStartDate(default)
    date_string = self.getContentInformation().get('Date', None)
    if date_string:
431
      parsed_date_string = parsedate_tz(date_string)
432
      if parsed_date_string is not None:
433
        time = mktime_tz(parsed_date_string)
434 435
        if time:
          return DateTime(time)
436 437 438 439 440 441 442 443
    return self.getCreationDate()

  security.declareProtected(Permissions.AccessContentsInformation, 'getTextContent')
  def getTextContent(self, default=_MARKER):
    """
    Returns the content of the email as text. This is useful
    to display the content of an email.
    """
444
    self._checkConversionFormatPermission(None)
445
    if not self.hasFile():
446
      # Return the standard text content if no file was provided
447
      # Or standard text content is not empty.
448 449 450 451
      if default is _MARKER:
        return self._baseGetTextContent()
      else:
        return self._baseGetTextContent(default)
452

453 454 455 456 457
    else:
      part = self._getMessageTextPart()
      if part is None:
        text_result = ""
      else:
458
        part_encoding = part.get_content_charset()
459
        message_text = part.get_payload(decode=1)
460 461 462 463
        if part.get_content_type() == 'text/html':
          mime, text_result = self.convert(format='html',
                                           text_content=message_text,
                                           charset=part_encoding)
464
        else:
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
          if part_encoding != 'utf-8':
            try:
              if part_encoding is not None:
                text_result = message_text.decode(part_encoding).encode('utf-8')
              else:
                text_result = message_text.decode().encode('utf-8')
            except (UnicodeDecodeError, LookupError), error_message:
              LOG('EmailDocument.getTextContent', INFO, 
                  'Failed to decode %s TEXT message of %s with error: %s' % 
                  (part_encoding, self.getPath(), error_message))
              codec = guessEncodingFromText(message_text,
                                            content_type=part.get_content_type())
              if codec is not None:
                try:
                  text_result = message_text.decode(codec).encode('utf-8')
                except (UnicodeDecodeError, LookupError):
                  text_result = repr(message_text)
              else:
                text_result = repr(message_text)
          else:
            text_result = message_text
486

487 488 489
    if default is _MARKER:
      return text_result
    return text_result or default
490

491 492
  security.declareProtected(Permissions.AccessContentsInformation, 'getContentType')
  def getContentType(self, default=_MARKER):
493 494 495 496 497 498 499 500
    """
    Returns the format of the email (text or html).
    
    TODO: add support for legacy objects
    """
    if not self.hasFile():
      # Return the standard text format if no file was provided
      if default is _MARKER:
501
        return TextDocument.getContentType(self)
502
      else:
503
        return TextDocument.getContentType(self, default)
504 505 506 507 508 509
    else:
      part = self._getMessageTextPart()
      if part is None:
        return 'text/plain'
      else:
        return part.get_content_type()
510 511 512 513 514 515 516 517 518 519 520 521 522 523

  email_parser = re.compile('[ ;,<>\'"]*([^<> ;,\'"]+?\@[^<> ;,\'"]+)[ ;,<>\'"]*',re.IGNORECASE)
  security.declareProtected(Permissions.AccessContentsInformation, 'getContentURLList')
  def getContentURLList(self):
    """
      Overriden to include emails as URLs
    """
    result = TextDocument.getContentURLList(self)
    result.extend(re.findall(self.email_parser, self.getSender('')))
    result.extend(re.findall(self.email_parser, self.getRecipient('')))
    result.extend(re.findall(self.email_parser, self.getCcRecipient('')))
    result.extend(re.findall(self.email_parser, self.getBccRecipient('')))
    return result

524
  # Conversion API Implementation
525 526 527 528 529 530 531 532
  def _convertToBaseFormat(self):
    """
      Build a structure which can be later used
      to extract content information from this mail
      message.
    """
    pass

533
  security.declareProtected(Permissions.View, 'index_html')
534 535
  index_html = TextDocument.index_html

536
  security.declareProtected(Permissions.AccessContentsInformation, 'convert')
537
  convert = TextDocument.convert
538 539 540

  security.declareProtected(Permissions.AccessContentsInformation, 'hasBaseData')
  def hasBaseData(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
541
    """
542
      Since there is no need to convert to a base format, we consider that 
Jean-Paul Smets's avatar
Jean-Paul Smets committed
543 544
      we always have the base format data if and only is we have
      some text defined or a file.
545 546 547 548 549 550 551 552 553 554
    """
    return self.hasFile() or self.hasTextContent()

  # Methods which can be useful to prepare a reply by email to an event
  security.declareProtected(Permissions.AccessContentsInformation, 'getReplyBody')
  def getReplyBody(self):
    """
      This is used in order to respond to a mail,
      this put a '> ' before each line of the body
    """
555
    if self.getContentType() == 'text/plain':
556 557 558
      body = self.asText()
      if body:
        return '> ' + str(body).replace('\n', '\n> ')
559
    elif self.getContentType() == 'text/html':
560
      return '<br/><blockquote type="cite">\n%s\n</blockquote>' %\
561
                                self.asStrippedHTML()
562 563 564 565 566 567 568
    return ''

  security.declareProtected(Permissions.AccessContentsInformation, 'getReplySubject')
  def getReplySubject(self):
    """
      This is used in order to respond to a mail,
      this put a 'Re: ' before the orignal subject
569 570

      XXX - not multilingual
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
    """
    reply_subject = self.getTitle()
    if reply_subject.find('Re: ') != 0:
      reply_subject = 'Re: ' + reply_subject
    return reply_subject

  security.declareProtected(Permissions.AccessContentsInformation, 'getReplyTo')
  def getReplyTo(self):
    """
      Returns the send of this message based on getContentInformation
    """
    content_information = self.getContentInformation()
    return content_information.get('Return-Path', content_information.get('From'))

  security.declareProtected(Permissions.UseMailhostServices, 'send')
  def send(self, from_url=None, to_url=None, reply_url=None, subject=None,
Yusei Tahara's avatar
Yusei Tahara committed
587
           body=None, attachment_format=None, attachment_list=None, download=False):
588 589 590 591
    """
      Sends the current event content by email. If documents are
      attached through the aggregate category, enclose them.

592 593
      XXX - needs to be unified with Event methods

594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
      from_url - the sender of this email. If not provided
                 we will use source to find a valid
                 email address

      to_url   - the recipients of this email. If not provided
                 we will use destination category to 
                 find a list of valid email addresses

      reply_url - the email address to reply to. If nothing
                 is provided, use the email defined in 
                 preferences.

      subject  - a custom title. If not provided, we will use
                 getTitle

      body     - a body message If not provided, we will
                 use the text representation of the event
611
                 as body (UTF-8)
612

Yusei Tahara's avatar
Yusei Tahara committed
613 614 615 616
      attachment_list -- list of dictionary which contains raw data and
                         name and mimetype for attachment.
                         See NotificationTool.buildEmailMessage.

617 618 619 620 621 622 623 624 625 626 627 628
      attachment_format - defines an option format
                 to convet attachments to (ex. application/pdf)

      download - if set to True returns, the message online
                rather than sending it.

      TODO: support conversion to base format and use
      base format rather than original format

      TODO2: consider turning this method into a general method for
      any ERP5 document.
    """
Yusei Tahara's avatar
Yusei Tahara committed
629 630 631
    if not _checkPermission(Permissions.View, self):
      raise Unauthorized

632 633
    additional_headers = {}

634
    #
635
    # Build mail message
636
    # This part will be replaced with MailTemplate soon.
637
    #
638 639
    if body is None:
      body = self.asText()
640 641

    # Subject
642 643
    if subject is None:
      subject = self.getTitle()
644 645

    # From
646
    if from_url is None:
647
      sender = self.getSourceValue()
648 649 650 651 652 653
      if sender is not None:
        if sender.getTitle():
          from_url = '"%s" <%s>' % (sender.getTitle(),
                                  sender.getDefaultEmailText())
        else:
          from_url = sender.getDefaultEmailText()
654
      else:
655
        from_url = self.getSender() # Access sender directly
656 657

    # Return-Path
658 659
    if reply_url is None:
      reply_url = self.portal_preferences.getPreferredEventSenderEmail()
660
    if reply_url:
661 662 663 664 665 666
      additional_headers['Return-Path'] = reply_url

    # Reply-To
    destination_reference = self.getDestinationReference()
    if destination_reference is not None:
      additional_headers['In-Reply-To'] = destination_reference
667 668 669

    # To (multiple)
    to_url_list = []
670 671 672 673
    if to_url is None:
      for recipient in self.getDestinationValueList():
        email = recipient.getDefaultEmailText()
        if email:
674
          if recipient.getTitle():
675
            to_url_list.append('"%s" <%s>' % (recipient.getTitle(), email))
676
          else:
677
            to_url_list.append(email)
678 679
        else:
          raise ValueError, 'Recipient %s has no defined email' % recipient
680 681
      if not to_url_list:
        to_url_list.append(self.getRecipient())
682
    elif type(to_url) in types.StringTypes:
683 684 685
      to_url_list.append(to_url)

    # Attachments
Yusei Tahara's avatar
Yusei Tahara committed
686 687
    if attachment_list is None:
      attachment_list = []
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
    document_type_list = self.getPortalDocumentTypeList()
    for attachment in self.getAggregateValueList():
      mime_type = None
      content = None
      name = None
      if not attachment.getPortalType() in document_type_list:
        mime_type = 'application/pdf'
        content = attachment.asPDF() # XXX - Not implemented yet
      else:
        #
        # Document type attachment
        #

        # WARNING - this could fail since getContentType
        # is not (yet) part of Document API
        if getattr(attachment, 'getContentType', None) is not None:
          mime_type = attachment.getContentType()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
705
        else:
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
          raise ValueError, "Cannot find mimetype of the document."

        if mime_type is not None:
          try:
            mime_type, content = attachment.convert(mime_type)
          except ConversionError:
            mime_type = attachment.getBaseContentType()
            content = attachment.getBaseData()
          except (NotImplementedError, MimeTypeException):
            pass

        if content is None:
          if getattr(attachment, 'getTextContent', None) is not None:
            content = attachment.getTextContent()
          elif getattr(attachment, 'getData', None) is not None:
            content = attachment.getData()
          elif getattr(attachment, 'getBaseData', None) is not None:
            content = attachment.getBaseData()

      if not isinstance(content, str):
        content = str(content)

      attachment_list.append({'mime_type':mime_type,
                              'content':content,
                              'name':attachment.getReference()}
                             )

733
    mail_message = None
734 735 736 737 738 739
    for to_url in to_url_list:
      mime_message = buildEmailMessage(from_url=from_url, to_url=to_url,
                                       msg=body, subject=subject,
                                       attachment_list=attachment_list,
                                       additional_headers=additional_headers)
      mail_message = mime_message.as_string()
740
      self.activate(activity='SQLQueue').sendMailHostMessage(mail_message)
741

742
    # Save one of mail messages.
743 744
    if mail_message is not None:
      self.setData(mail_message)
745

746 747
    # Only for debugging purpose
    if download:
748
      return mail_message
749 750 751 752 753

  security.declareProtected(Permissions.UseMailhostServices, 'sendMailHostMessage')
  def sendMailHostMessage(self, message):
    """
      Send one by one
754 755

      XXX - Needs to be unified with Event methods
756 757
    """
    self.MailHost.send(message)
758 759 760 761 762

  # Because TextDocument is base_convertable and not EmailDocument.
  # getData must be implemented like File.getData is.
  security.declareProtected(Permissions.AccessContentsInformation, 'getData')
  getData = File.getData