You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

164 lines
8.5 KiB

11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
  1. # -*- coding: utf-8 -*-
  2. import base64
  3. import logging
  4. from email.utils import formataddr
  5. from urlparse import urljoin
  6. from openerp import api, tools
  7. from openerp import SUPERUSER_ID
  8. from openerp.addons.base.ir.ir_mail_server import MailDeliveryException
  9. from openerp.osv import fields, osv
  10. from openerp.tools.safe_eval import safe_eval as eval
  11. from openerp.tools.translate import _
  12. _logger = logging.getLogger(__name__)
  13. import re
  14. class mail_mail(osv.Model):
  15. _inherit = "mail.mail"
  16. def send(self, cr, uid, ids, auto_commit=False, raise_exception=False, context=None):
  17. # copy-paste from addons/mail/mail_mail.py
  18. """ Sends the selected emails immediately, ignoring their current
  19. state (mails that have already been sent should not be passed
  20. unless they should actually be re-sent).
  21. Emails successfully delivered are marked as 'sent', and those
  22. that fail to be deliver are marked as 'exception', and the
  23. corresponding error mail is output in the server logs.
  24. :param bool auto_commit: whether to force a commit of the mail status
  25. after sending each mail (meant only for scheduler processing);
  26. should never be True during normal transactions (default: False)
  27. :param bool raise_exception: whether to raise an exception if the
  28. email sending process has failed
  29. :return: True
  30. """
  31. # NEW STUFF
  32. catchall_alias = self.pool['ir.config_parameter'].get_param(cr, uid, "mail.catchall.alias_from", context=context)
  33. catchall_domain = self.pool['ir.config_parameter'].get_param(cr, uid, "mail.catchall.domain", context=context)
  34. correct_email_from = '@%s>?\s*$'%catchall_domain
  35. default_email_from = '%s@%s' % (catchall_alias, catchall_domain)
  36. context = dict(context or {})
  37. ir_mail_server = self.pool.get('ir.mail_server')
  38. ir_attachment = self.pool['ir.attachment']
  39. for mail in self.browse(cr, SUPERUSER_ID, ids, context=context):
  40. try:
  41. # TDE note: remove me when model_id field is present on mail.message - done here to avoid doing it multiple times in the sub method
  42. if mail.model:
  43. model_id = self.pool['ir.model'].search(cr, SUPERUSER_ID, [('model', '=', mail.model)], context=context)[0]
  44. model = self.pool['ir.model'].browse(cr, SUPERUSER_ID, model_id, context=context)
  45. else:
  46. model = None
  47. if model:
  48. context['model_name'] = model.name
  49. # load attachment binary data with a separate read(), as prefetching all
  50. # `datas` (binary field) could bloat the browse cache, triggerring
  51. # soft/hard mem limits with temporary data.
  52. attachment_ids = [a.id for a in mail.attachment_ids]
  53. attachments = [(a['datas_fname'], base64.b64decode(a['datas']))
  54. for a in ir_attachment.read(cr, SUPERUSER_ID, attachment_ids,
  55. ['datas_fname', 'datas'])]
  56. # specific behavior to customize the send email for notified partners
  57. email_list = []
  58. if mail.email_to:
  59. email_list.append(self.send_get_email_dict(cr, uid, mail, context=context))
  60. for partner in mail.recipient_ids:
  61. email_list.append(self.send_get_email_dict(cr, uid, mail, partner=partner, context=context))
  62. # headers
  63. headers = {}
  64. bounce_alias = self.pool['ir.config_parameter'].get_param(cr, uid, "mail.bounce.alias", context=context)
  65. catchall_domain = self.pool['ir.config_parameter'].get_param(cr, uid, "mail.catchall.domain", context=context)
  66. if bounce_alias and catchall_domain:
  67. if mail.model and mail.res_id:
  68. headers['Return-Path'] = '%s-%d-%s-%d@%s' % (bounce_alias, mail.id, mail.model, mail.res_id, catchall_domain)
  69. else:
  70. headers['Return-Path'] = '%s-%d@%s' % (bounce_alias, mail.id, catchall_domain)
  71. if mail.headers:
  72. try:
  73. headers.update(eval(mail.headers))
  74. except Exception:
  75. pass
  76. # Writing on the mail object may fail (e.g. lock on user) which
  77. # would trigger a rollback *after* actually sending the email.
  78. # To avoid sending twice the same email, provoke the failure earlier
  79. mail.write({'state': 'exception'})
  80. mail_sent = False
  81. # build an RFC2822 email.message.Message object and send it without queuing
  82. res = None
  83. for email in email_list:
  84. # NEW STUFF
  85. email_from = mail.email_from
  86. if re.search(correct_email_from, email_from) is None:
  87. email_from = default_email_from
  88. msg = ir_mail_server.build_email(
  89. email_from=email_from, # NEW STUFF
  90. email_to=email.get('email_to'),
  91. subject=email.get('subject'),
  92. body=email.get('body'),
  93. body_alternative=email.get('body_alternative'),
  94. email_cc=tools.email_split(mail.email_cc),
  95. reply_to=mail.reply_to,
  96. attachments=attachments,
  97. message_id=mail.message_id,
  98. references=mail.references,
  99. object_id=mail.res_id and ('%s-%s' % (mail.res_id, mail.model)),
  100. subtype='html',
  101. subtype_alternative='plain',
  102. headers=headers)
  103. try:
  104. res = ir_mail_server.send_email(cr, uid, msg,
  105. mail_server_id=mail.mail_server_id.id,
  106. context=context)
  107. except AssertionError as error:
  108. if error.message == ir_mail_server.NO_VALID_RECIPIENT:
  109. # No valid recipient found for this particular
  110. # mail item -> ignore error to avoid blocking
  111. # delivery to next recipients, if any. If this is
  112. # the only recipient, the mail will show as failed.
  113. _logger.warning("Ignoring invalid recipients for mail.mail %s: %s",
  114. mail.message_id, email.get('email_to'))
  115. else:
  116. raise
  117. if res:
  118. mail.write({'state': 'sent', 'message_id': res})
  119. mail_sent = True
  120. # /!\ can't use mail.state here, as mail.refresh() will cause an error
  121. # see revid:odo@openerp.com-20120622152536-42b2s28lvdv3odyr in 6.1
  122. if mail_sent:
  123. _logger.info('Mail with ID %r and Message-Id %r successfully sent', mail.id, mail.message_id)
  124. self._postprocess_sent_message(cr, uid, mail, context=context, mail_sent=mail_sent)
  125. except MemoryError:
  126. # prevent catching transient MemoryErrors, bubble up to notify user or abort cron job
  127. # instead of marking the mail as failed
  128. _logger.exception('MemoryError while processing mail with ID %r and Msg-Id %r. '\
  129. 'Consider raising the --limit-memory-hard startup option',
  130. mail.id, mail.message_id)
  131. raise
  132. except Exception as e:
  133. _logger.exception('failed sending mail.mail %s', mail.id)
  134. mail.write({'state': 'exception'})
  135. self._postprocess_sent_message(cr, uid, mail, context=context, mail_sent=False)
  136. if raise_exception:
  137. if isinstance(e, AssertionError):
  138. # get the args of the original error, wrap into a value and throw a MailDeliveryException
  139. # that is an except_orm, with name and value as arguments
  140. value = '. '.join(e.args)
  141. raise MailDeliveryException(_("Mail Delivery Failed"), value)
  142. raise
  143. if auto_commit is True:
  144. cr.commit()
  145. return True