mail_compose_message.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. # -*- coding: utf-8 -*-
  2. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  3. import ast
  4. import base64
  5. import re
  6. from odoo import _, api, fields, models, tools, Command
  7. from odoo.exceptions import UserError
  8. from odoo.osv import expression
  9. def _reopen(self, res_id, model, context=None):
  10. # save original model in context, because selecting the list of available
  11. # templates requires a model in context
  12. context = dict(context or {}, default_model=model)
  13. return {'type': 'ir.actions.act_window',
  14. 'view_mode': 'form',
  15. 'res_id': res_id,
  16. 'res_model': self._name,
  17. 'target': 'new',
  18. 'context': context,
  19. }
  20. class MailComposer(models.TransientModel):
  21. """ Generic message composition wizard. You may inherit from this wizard
  22. at model and view levels to provide specific features.
  23. The behavior of the wizard depends on the composition_mode field:
  24. - 'comment': post on a record. The wizard is pre-populated via ``get_record_data``
  25. - 'mass_mail': wizard in mass mailing mode where the mail details can
  26. contain template placeholders that will be merged with actual data
  27. before being sent to each recipient.
  28. """
  29. _name = 'mail.compose.message'
  30. _inherit = 'mail.composer.mixin'
  31. _description = 'Email composition wizard'
  32. _log_access = True
  33. _batch_size = 500
  34. @api.model
  35. def default_get(self, fields):
  36. """ Handle composition mode. Some details about context keys:
  37. - comment: default mode, model and ID of a record the user comments
  38. - default_model or active_model
  39. - default_res_id or active_id
  40. - mass_mail: model and IDs of records the user mass-mails
  41. - active_ids: record IDs
  42. - default_model or active_model
  43. """
  44. # backward compatibility of context before addition of
  45. # email_layout_xmlid field: to remove in 15.1+
  46. if self._context.get('custom_layout') and 'default_email_layout_xmlid' not in self._context:
  47. self = self.with_context(default_email_layout_xmlid=self._context['custom_layout'])
  48. result = super(MailComposer, self).default_get(fields)
  49. # author
  50. missing_author = 'author_id' in fields and 'author_id' not in result
  51. missing_email_from = 'email_from' in fields and 'email_from' not in result
  52. if missing_author or missing_email_from:
  53. author_id, email_from = self.env['mail.thread']._message_compute_author(result.get('author_id'), result.get('email_from'), raise_on_email=False)
  54. if missing_email_from:
  55. result['email_from'] = email_from
  56. if missing_author:
  57. result['author_id'] = author_id
  58. if 'model' in fields and 'model' not in result:
  59. result['model'] = self._context.get('active_model')
  60. if 'res_id' in fields and 'res_id' not in result:
  61. result['res_id'] = self._context.get('active_id')
  62. if 'reply_to_mode' in fields and 'reply_to_mode' not in result and result.get('model'):
  63. # doesn't support threading
  64. if result['model'] not in self.env or not hasattr(self.env[result['model']], 'message_post'):
  65. result['reply_to_mode'] = 'new'
  66. if 'active_domain' in self._context: # not context.get() because we want to keep global [] domains
  67. result['active_domain'] = '%s' % self._context.get('active_domain')
  68. if result.get('composition_mode') == 'comment' and (set(fields) & set(['model', 'res_id', 'partner_ids', 'record_name', 'subject'])):
  69. result.update(self.get_record_data(result))
  70. # when being in new mode, create_uid is not granted -> ACLs issue may arise
  71. if 'create_uid' in fields and 'create_uid' not in result:
  72. result['create_uid'] = self.env.uid
  73. filtered_result = dict((fname, result[fname]) for fname in result if fname in fields)
  74. return filtered_result
  75. def _partner_ids_domain(self):
  76. return expression.OR([
  77. [('type', '!=', 'private')],
  78. [('id', 'in', self.env.context.get('default_partner_ids', []))],
  79. ])
  80. # content
  81. subject = fields.Char('Subject', compute=False)
  82. body = fields.Html('Contents', render_engine='qweb', compute=False, default='', sanitize_style=True)
  83. parent_id = fields.Many2one(
  84. 'mail.message', 'Parent Message', ondelete='set null')
  85. template_id = fields.Many2one('mail.template', 'Use template', domain="[('model', '=', model)]")
  86. attachment_ids = fields.Many2many(
  87. 'ir.attachment', 'mail_compose_message_ir_attachments_rel',
  88. 'wizard_id', 'attachment_id', 'Attachments')
  89. email_layout_xmlid = fields.Char('Email Notification Layout', copy=False)
  90. email_add_signature = fields.Boolean(default=True)
  91. # origin
  92. email_from = fields.Char('From', help="Email address of the sender. This field is set when no matching partner is found and replaces the author_id field in the chatter.")
  93. author_id = fields.Many2one(
  94. 'res.partner', 'Author',
  95. help="Author of the message. If not set, email_from may hold an email address that did not match any partner.")
  96. # composition
  97. composition_mode = fields.Selection(selection=[
  98. ('comment', 'Post on a document'),
  99. ('mass_mail', 'Email Mass Mailing'),
  100. ('mass_post', 'Post on Multiple Documents')], string='Composition mode', default='comment')
  101. model = fields.Char('Related Document Model')
  102. res_id = fields.Integer('Related Document ID')
  103. record_name = fields.Char('Message Record Name')
  104. use_active_domain = fields.Boolean('Use active domain')
  105. active_domain = fields.Text('Active domain', readonly=True)
  106. # characteristics
  107. message_type = fields.Selection([
  108. ('comment', 'Comment'),
  109. ('notification', 'System notification')],
  110. 'Type', required=True, default='comment',
  111. help="Message type: email for email message, notification for system "
  112. "message, comment for other messages such as user replies")
  113. is_log = fields.Boolean('Log as Internal Note')
  114. subtype_id = fields.Many2one(
  115. 'mail.message.subtype', 'Subtype', ondelete='set null',
  116. default=lambda self: self.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment'))
  117. notify = fields.Boolean('Notify followers', help='Notify followers of the document (mass post only)')
  118. mail_activity_type_id = fields.Many2one('mail.activity.type', 'Mail Activity Type', ondelete='set null')
  119. # destination
  120. reply_to = fields.Char('Reply To', help='Reply email address. Setting the reply_to bypasses the automatic thread creation.')
  121. reply_to_force_new = fields.Boolean(
  122. string='Considers answers as new thread',
  123. help='Manage answers as new incoming emails instead of replies going to the same thread.')
  124. reply_to_mode = fields.Selection([
  125. ('update', 'Store email and replies in the chatter of each record'),
  126. ('new', 'Collect replies on a specific email address')],
  127. string='Replies', compute='_compute_reply_to_mode', inverse='_inverse_reply_to_mode',
  128. help="Original Discussion: Answers go in the original document discussion thread. \n Another Email Address: Answers go to the email address mentioned in the tracking message-id instead of original document discussion thread. \n This has an impact on the generated message-id.")
  129. # recipients
  130. partner_ids = fields.Many2many(
  131. 'res.partner', 'mail_compose_message_res_partner_rel',
  132. 'wizard_id', 'partner_id', 'Additional Contacts',
  133. domain=_partner_ids_domain)
  134. # sending
  135. auto_delete = fields.Boolean('Delete Emails',
  136. help='This option permanently removes any track of email after it\'s been sent, including from the Technical menu in the Settings, in order to preserve storage space of your Odoo database.')
  137. auto_delete_message = fields.Boolean('Delete Message Copy', help='Do not keep a copy of the email in the document communication history (mass mailing only)')
  138. mail_server_id = fields.Many2one('ir.mail_server', 'Outgoing mail server')
  139. @api.depends('reply_to_force_new')
  140. def _compute_reply_to_mode(self):
  141. for composer in self:
  142. composer.reply_to_mode = 'new' if composer.reply_to_force_new else 'update'
  143. def _inverse_reply_to_mode(self):
  144. for composer in self:
  145. composer.reply_to_force_new = composer.reply_to_mode == 'new'
  146. # Overrides of mail.render.mixin
  147. @api.depends('model')
  148. def _compute_render_model(self):
  149. for composer in self:
  150. composer.render_model = composer.model
  151. # Onchanges
  152. @api.onchange('template_id')
  153. def _onchange_template_id_wrapper(self):
  154. self.ensure_one()
  155. values = self._onchange_template_id(self.template_id.id, self.composition_mode, self.model, self.res_id)['value']
  156. for fname, value in values.items():
  157. setattr(self, fname, value)
  158. def _compute_can_edit_body(self):
  159. """Can edit the body if we are not in "mass_mail" mode because the template is
  160. rendered before it's modified.
  161. """
  162. non_mass_mail = self.filtered(lambda m: m.composition_mode != 'mass_mail')
  163. non_mass_mail.can_edit_body = True
  164. super(MailComposer, self - non_mass_mail)._compute_can_edit_body()
  165. @api.model
  166. def get_record_data(self, values):
  167. """ Returns a defaults-like dict with initial values for the composition
  168. wizard when sending an email related a previous email (parent_id) or
  169. a document (model, res_id). This is based on previously computed default
  170. values. """
  171. result, subject = {}, False
  172. if values.get('parent_id'):
  173. parent = self.env['mail.message'].browse(values.get('parent_id'))
  174. result['record_name'] = parent.record_name
  175. subject = tools.ustr(parent.subject or parent.record_name or '')
  176. if not values.get('model'):
  177. result['model'] = parent.model
  178. if not values.get('res_id'):
  179. result['res_id'] = parent.res_id
  180. partner_ids = values.get('partner_ids', list()) + parent.partner_ids.ids
  181. result['partner_ids'] = partner_ids
  182. elif values.get('model') and values.get('res_id'):
  183. doc_name_get = self.env[values.get('model')].browse(values.get('res_id')).name_get()
  184. result['record_name'] = doc_name_get and doc_name_get[0][1] or ''
  185. subject = tools.ustr(result['record_name'])
  186. re_prefix = _('Re:')
  187. if subject and not (subject.startswith('Re:') or subject.startswith(re_prefix)):
  188. subject = "%s %s" % (re_prefix, subject)
  189. result['subject'] = subject
  190. return result
  191. # ------------------------------------------------------------
  192. # CRUD / ORM
  193. # ------------------------------------------------------------
  194. @api.autovacuum
  195. def _gc_lost_attachments(self):
  196. """ Garbage collect lost mail attachments. Those are attachments
  197. - linked to res_model 'mail.compose.message', the composer wizard
  198. - with res_id 0, because they were created outside of an existing
  199. wizard (typically user input through Chatter or reports
  200. created on-the-fly by the templates)
  201. - unused since at least one day (create_date and write_date)
  202. """
  203. limit_date = fields.Datetime.subtract(fields.Datetime.now(), days=1)
  204. self.env['ir.attachment'].search([
  205. ('res_model', '=', self._name),
  206. ('res_id', '=', 0),
  207. ('create_date', '<', limit_date),
  208. ('write_date', '<', limit_date)]
  209. ).unlink()
  210. # ------------------------------------------------------------
  211. # ACTIONS
  212. # ------------------------------------------------------------
  213. def action_send_mail(self):
  214. """ Used for action button that do not accept arguments. """
  215. self._action_send_mail(auto_commit=False)
  216. return {'type': 'ir.actions.act_window_close'}
  217. def _action_send_mail(self, auto_commit=False):
  218. """ Process the wizard content and proceed with sending the related
  219. email(s), rendering any template patterns on the fly if needed.
  220. :return tuple: (
  221. result_mails_su: in mass mode, sent emails (as sudo),
  222. result_messages: in comment mode, posted messages
  223. )
  224. """
  225. # Several custom layouts make use of the model description at rendering, e.g. in the
  226. # 'View <document>' button. Some models are used for different business concepts, such as
  227. # 'purchase.order' which is used for a RFQ and and PO. To avoid confusion, we must use a
  228. # different wording depending on the state of the object.
  229. # Therefore, we can set the description in the context from the beginning to avoid falling
  230. # back on the regular display_name retrieved in ``_notify_by_email_prepare_rendering_context()``.
  231. model_description = self._context.get('model_description')
  232. result_mails_su, result_messages = self.env['mail.mail'].sudo(), self.env['mail.message']
  233. for wizard in self:
  234. # Duplicate attachments linked to the email.template.
  235. # Indeed, basic mail.compose.message wizard duplicates attachments in mass
  236. # mailing mode. But in 'single post' mode, attachments of an email template
  237. # also have to be duplicated to avoid changing their ownership.
  238. if wizard.attachment_ids and wizard.composition_mode != 'mass_mail' and wizard.template_id:
  239. new_attachment_ids = []
  240. for attachment in wizard.attachment_ids:
  241. if attachment in wizard.template_id.attachment_ids:
  242. new_attachment_ids.append(attachment.copy({'res_model': 'mail.compose.message', 'res_id': wizard.id}).id)
  243. else:
  244. new_attachment_ids.append(attachment.id)
  245. new_attachment_ids.reverse()
  246. wizard.write({'attachment_ids': [Command.set(new_attachment_ids)]})
  247. # Mass Mailing
  248. mass_mode = wizard.composition_mode in ('mass_mail', 'mass_post')
  249. ActiveModel = self.env[wizard.model] if wizard.model and hasattr(self.env[wizard.model], 'message_post') else self.env['mail.thread']
  250. if wizard.composition_mode == 'mass_post':
  251. # do not send emails directly but use the queue instead
  252. # add context key to avoid subscribing the author
  253. ActiveModel = ActiveModel.with_context(mail_notify_force_send=False, mail_create_nosubscribe=True)
  254. # wizard works in batch mode: [res_id] or active_ids or active_domain
  255. if mass_mode and wizard.use_active_domain and wizard.model:
  256. res_ids = self.env[wizard.model].search(ast.literal_eval(wizard.active_domain)).ids
  257. elif mass_mode and wizard.model and self._context.get('active_ids'):
  258. res_ids = self._context['active_ids']
  259. else:
  260. res_ids = [wizard.res_id]
  261. batch_size = int(self.env['ir.config_parameter'].sudo().get_param('mail.batch_size')) or self._batch_size
  262. sliced_res_ids = [res_ids[i:i + batch_size] for i in range(0, len(res_ids), batch_size)]
  263. if wizard.composition_mode == 'mass_mail' or wizard.is_log or (wizard.composition_mode == 'mass_post' and not wizard.notify): # log a note: subtype is False
  264. subtype_id = False
  265. elif wizard.subtype_id:
  266. subtype_id = wizard.subtype_id.id
  267. else:
  268. subtype_id = self.env['ir.model.data']._xmlid_to_res_id('mail.mt_comment')
  269. for res_ids in sliced_res_ids:
  270. # mass mail mode: mail are sudo-ed, as when going through get_mail_values
  271. # standard access rights on related records will be checked when browsing them
  272. # to compute mail values. If people have access to the records they have rights
  273. # to create lots of emails in sudo as it is consdiered as a technical model.
  274. batch_mails_sudo = self.env['mail.mail'].sudo()
  275. all_mail_values = wizard.get_mail_values(res_ids)
  276. for res_id, mail_values in all_mail_values.items():
  277. if wizard.composition_mode == 'mass_mail':
  278. batch_mails_sudo += self.env['mail.mail'].sudo().create(mail_values)
  279. else:
  280. post_params = dict(
  281. subtype_id=subtype_id,
  282. email_layout_xmlid=wizard.email_layout_xmlid,
  283. email_add_signature=not bool(wizard.template_id) and wizard.email_add_signature,
  284. mail_auto_delete=wizard.template_id.auto_delete if wizard.template_id else self._context.get('mail_auto_delete', True),
  285. model_description=model_description)
  286. post_params.update(mail_values)
  287. if ActiveModel._name == 'mail.thread':
  288. if wizard.model:
  289. post_params['model'] = wizard.model
  290. post_params['res_id'] = res_id
  291. if not ActiveModel.message_notify(**post_params):
  292. # if message_notify returns an empty record set, no recipients where found.
  293. raise UserError(_("No recipient found."))
  294. else:
  295. result_messages += ActiveModel.browse(res_id).message_post(**post_params)
  296. result_mails_su += batch_mails_sudo
  297. if wizard.composition_mode == 'mass_mail':
  298. batch_mails_sudo.send(auto_commit=auto_commit)
  299. return result_mails_su, result_messages
  300. def action_save_as_template(self):
  301. """ hit save as template button: current form value will be a new
  302. template attached to the current document. """
  303. for record in self:
  304. model = self.env['ir.model']._get(record.model or 'mail.message')
  305. model_name = model.name or ''
  306. template_name = "%s: %s" % (model_name, tools.ustr(record.subject))
  307. values = {
  308. 'name': template_name,
  309. 'subject': record.subject or False,
  310. 'body_html': record.body or False,
  311. 'model_id': model.id or False,
  312. 'use_default_to': True,
  313. }
  314. template = self.env['mail.template'].create(values)
  315. if record.attachment_ids:
  316. attachments = self.env['ir.attachment'].sudo().browse(record.attachment_ids.ids).filtered(
  317. lambda a: a.res_model == 'mail.compose.message' and a.create_uid.id == self._uid)
  318. if attachments:
  319. attachments.write({'res_model': template._name, 'res_id': template.id})
  320. template.attachment_ids |= record.attachment_ids
  321. # generate the saved template
  322. record.write({'template_id': template.id})
  323. record._onchange_template_id_wrapper()
  324. return _reopen(self, record.id, record.model, context=self._context)
  325. # ------------------------------------------------------------
  326. # RENDERING / VALUES GENERATION
  327. # ------------------------------------------------------------
  328. def get_mail_values(self, res_ids):
  329. """Generate the values that will be used by send_mail to create mail_messages
  330. or mail_mails. """
  331. self.ensure_one()
  332. results = dict.fromkeys(res_ids, False)
  333. rendered_values = {}
  334. mass_mail_mode = self.composition_mode == 'mass_mail'
  335. # render all template-based value at once
  336. if mass_mail_mode and self.model:
  337. rendered_values = self.render_message(res_ids)
  338. # compute alias-based reply-to in batch
  339. reply_to_value = dict.fromkeys(res_ids, None)
  340. if mass_mail_mode and not self.reply_to_force_new:
  341. records = self.env[self.model].browse(res_ids)
  342. reply_to_value = records._notify_get_reply_to(default=False)
  343. # when having no specific reply-to, fetch rendered email_from value
  344. for res_id, reply_to in reply_to_value.items():
  345. if not reply_to:
  346. reply_to_value[res_id] = rendered_values.get(res_id, {}).get('email_from', False)
  347. for res_id in res_ids:
  348. # static wizard (mail.message) values
  349. mail_values = {
  350. 'subject': self.subject,
  351. 'body': self.body or '',
  352. 'parent_id': self.parent_id and self.parent_id.id,
  353. 'partner_ids': [partner.id for partner in self.partner_ids],
  354. 'attachment_ids': [attach.id for attach in self.attachment_ids],
  355. 'author_id': self.author_id.id,
  356. 'email_from': self.email_from,
  357. 'record_name': self.record_name,
  358. 'reply_to_force_new': self.reply_to_force_new,
  359. 'mail_server_id': self.mail_server_id.id,
  360. 'mail_activity_type_id': self.mail_activity_type_id.id,
  361. 'message_type': 'email' if mass_mail_mode else self.message_type,
  362. }
  363. # mass mailing: rendering override wizard static values
  364. if mass_mail_mode and self.model:
  365. record = self.env[self.model].browse(res_id)
  366. mail_values['headers'] = repr(record._notify_by_email_get_headers())
  367. # keep a copy unless specifically requested, reset record name (avoid browsing records)
  368. mail_values.update(is_notification=not self.auto_delete_message, model=self.model, res_id=res_id, record_name=False)
  369. # auto deletion of mail_mail
  370. if self.auto_delete or self.template_id.auto_delete:
  371. mail_values['auto_delete'] = True
  372. # rendered values using template
  373. email_dict = rendered_values[res_id]
  374. mail_values['partner_ids'] += email_dict.pop('partner_ids', [])
  375. mail_values.update(email_dict)
  376. if not self.reply_to_force_new:
  377. mail_values.pop('reply_to')
  378. if reply_to_value.get(res_id):
  379. mail_values['reply_to'] = reply_to_value[res_id]
  380. if self.reply_to_force_new and not mail_values.get('reply_to'):
  381. mail_values['reply_to'] = mail_values['email_from']
  382. # mail_mail values: body -> body_html, partner_ids -> recipient_ids
  383. mail_values['body_html'] = mail_values.get('body', '')
  384. mail_values['recipient_ids'] = [Command.link(id) for id in mail_values.pop('partner_ids', [])]
  385. # process attachments: should not be encoded before being processed by message_post / mail_mail create
  386. mail_values['attachments'] = [(name, base64.b64decode(enc_cont)) for name, enc_cont in email_dict.pop('attachments', list())]
  387. attachment_ids = []
  388. for attach_id in mail_values.pop('attachment_ids'):
  389. new_attach_id = self.env['ir.attachment'].browse(attach_id).copy({'res_model': self._name, 'res_id': self.id})
  390. attachment_ids.append(new_attach_id.id)
  391. attachment_ids.reverse()
  392. mail_values['attachment_ids'] = self.env['mail.thread'].with_context(attached_to=record)._message_post_process_attachments(
  393. mail_values.pop('attachments', []),
  394. attachment_ids,
  395. {'model': 'mail.message', 'res_id': 0}
  396. )['attachment_ids']
  397. results[res_id] = mail_values
  398. results = self._process_state(results)
  399. return results
  400. def _process_recipient_values(self, mail_values_dict):
  401. # Preprocess res.partners to batch-fetch from db if recipient_ids is present
  402. # it means they are partners (the only object to fill get_default_recipient this way)
  403. recipient_pids = [
  404. recipient_command[1]
  405. for mail_values in mail_values_dict.values()
  406. # recipient_ids is a list of x2m command tuples at this point
  407. for recipient_command in mail_values.get('recipient_ids') or []
  408. if recipient_command[1]
  409. ]
  410. recipient_emails = {
  411. p.id: p.email
  412. for p in self.env['res.partner'].browse(set(recipient_pids))
  413. } if recipient_pids else {}
  414. recipients_info = {}
  415. for record_id, mail_values in mail_values_dict.items():
  416. # add email from email_to; if unrecognized email in email_to keep
  417. # it as used for further processing
  418. mail_to = tools.email_split_and_format(mail_values.get('email_to'))
  419. if not mail_to and mail_values.get('email_to'):
  420. mail_to.append(mail_values['email_to'])
  421. # add email from recipients (res.partner)
  422. mail_to += [
  423. recipient_emails[recipient_command[1]]
  424. for recipient_command in mail_values.get('recipient_ids') or []
  425. if recipient_command[1]
  426. ]
  427. # uniquify, keep ordering
  428. seen = set()
  429. mail_to = [email for email in mail_to if email not in seen and not seen.add(email)]
  430. recipients_info[record_id] = {
  431. 'mail_to': mail_to,
  432. 'mail_to_normalized': [
  433. tools.email_normalize(mail, strict=False)
  434. for mail in mail_to
  435. if tools.email_normalize(mail, strict=False)
  436. ]
  437. }
  438. return recipients_info
  439. def _process_state(self, mail_values_dict):
  440. recipients_info = self._process_recipient_values(mail_values_dict)
  441. blacklist_ids = self._get_blacklist_record_ids(mail_values_dict, recipients_info)
  442. optout_emails = self._get_optout_emails(mail_values_dict)
  443. done_emails = self._get_done_emails(mail_values_dict)
  444. # in case of an invoice e.g.
  445. mailing_document_based = self.env.context.get('mailing_document_based')
  446. for record_id, mail_values in mail_values_dict.items():
  447. recipients = recipients_info[record_id]
  448. # when having more than 1 recipient: we cannot really decide when a single
  449. # email is linked to several to -> skip that part. Mass mailing should
  450. # anyway always have a single recipient per record as this is default behavior.
  451. if len(recipients['mail_to']) > 1:
  452. continue
  453. mail_to = recipients['mail_to'][0] if recipients['mail_to'] else ''
  454. mail_to_normalized = recipients['mail_to_normalized'][0] if recipients['mail_to_normalized'] else ''
  455. # prevent sending to blocked addresses that were included by mistake
  456. # blacklisted or optout or duplicate -> cancel
  457. if record_id in blacklist_ids:
  458. mail_values['state'] = 'cancel'
  459. mail_values['failure_type'] = 'mail_bl'
  460. # Do not post the mail into the recipient's chatter
  461. mail_values['is_notification'] = False
  462. elif optout_emails and mail_to in optout_emails:
  463. mail_values['state'] = 'cancel'
  464. mail_values['failure_type'] = 'mail_optout'
  465. elif done_emails and mail_to in done_emails and not mailing_document_based:
  466. mail_values['state'] = 'cancel'
  467. mail_values['failure_type'] = 'mail_dup'
  468. # void of falsy values -> error
  469. elif not mail_to:
  470. mail_values['state'] = 'cancel'
  471. mail_values['failure_type'] = 'mail_email_missing'
  472. elif not mail_to_normalized:
  473. mail_values['state'] = 'cancel'
  474. mail_values['failure_type'] = 'mail_email_invalid'
  475. elif done_emails is not None and not mailing_document_based:
  476. done_emails.append(mail_to)
  477. return mail_values_dict
  478. def _get_blacklist_record_ids(self, mail_values_dict, recipients_info=None):
  479. """Get record ids for which at least one recipient is black listed.
  480. :param dict mail_values_dict: mail values per record id
  481. :param dict recipients_info: optional dict of recipients info per record id
  482. Optional for backward compatibility but without, result can be incomplete.
  483. :return set: record ids with at least one black listed recipient.
  484. """
  485. blacklisted_rec_ids = set()
  486. if self.composition_mode == 'mass_mail':
  487. self.env['mail.blacklist'].flush_model(['email', 'active'])
  488. self._cr.execute("SELECT email FROM mail_blacklist WHERE active=true")
  489. blacklist = {x[0] for x in self._cr.fetchall()}
  490. if not blacklist:
  491. return blacklisted_rec_ids
  492. if issubclass(type(self.env[self.model]), self.pool['mail.thread.blacklist']):
  493. targets = self.env[self.model].browse(mail_values_dict.keys()).read(['email_normalized'])
  494. # First extract email from recipient before comparing with blacklist
  495. blacklisted_rec_ids.update(target['id'] for target in targets
  496. if target['email_normalized'] in blacklist)
  497. elif recipients_info:
  498. # Note that we exclude the record if at least one recipient is blacklisted (-> even if not all)
  499. # But as commented above: Mass mailing should always have a single recipient per record.
  500. blacklisted_rec_ids.update(res_id for res_id, recipient_info in recipients_info.items()
  501. if blacklist & set(recipient_info['mail_to_normalized']))
  502. return blacklisted_rec_ids
  503. def _get_done_emails(self, mail_values_dict):
  504. return []
  505. def _get_optout_emails(self, mail_values_dict):
  506. return []
  507. def _onchange_template_id(self, template_id, composition_mode, model, res_id):
  508. """ - mass_mailing: we cannot render, so return the template values
  509. - normal mode: return rendered values
  510. /!\ for x2many field, this onchange return command instead of ids
  511. """
  512. if template_id and composition_mode == 'mass_mail':
  513. template = self.env['mail.template'].browse(template_id)
  514. values = dict(
  515. (field, template[field])
  516. for field in ['subject', 'body_html',
  517. 'email_from',
  518. 'reply_to',
  519. 'mail_server_id']
  520. if template[field]
  521. )
  522. if template.attachment_ids:
  523. values['attachment_ids'] = [att.id for att in template.attachment_ids]
  524. if template.mail_server_id:
  525. values['mail_server_id'] = template.mail_server_id.id
  526. elif template_id:
  527. values = self.generate_email_for_composer(
  528. template_id, [res_id],
  529. ['subject', 'body_html',
  530. 'email_from',
  531. 'email_cc', 'email_to', 'partner_to', 'reply_to',
  532. 'attachment_ids', 'mail_server_id'
  533. ]
  534. )[res_id]
  535. # transform attachments into attachment_ids; not attached to the document because this will
  536. # be done further in the posting process, allowing to clean database if email not send
  537. attachment_ids = []
  538. Attachment = self.env['ir.attachment']
  539. for attach_fname, attach_datas in values.pop('attachments', []):
  540. data_attach = {
  541. 'name': attach_fname,
  542. 'datas': attach_datas,
  543. 'res_model': 'mail.compose.message',
  544. 'res_id': 0,
  545. 'type': 'binary', # override default_type from context, possibly meant for another model!
  546. }
  547. attachment_ids.append(Attachment.create(data_attach).id)
  548. if values.get('attachment_ids', []) or attachment_ids:
  549. values['attachment_ids'] = [Command.set(values.get('attachment_ids', []) + attachment_ids)]
  550. else:
  551. default_values = self.with_context(
  552. default_composition_mode=composition_mode,
  553. default_model=model,
  554. default_res_id=res_id
  555. ).default_get(['composition_mode', 'model', 'res_id', 'parent_id',
  556. 'subject', 'body',
  557. 'email_from',
  558. 'partner_ids', 'reply_to',
  559. 'attachment_ids', 'mail_server_id'
  560. ])
  561. values = dict(
  562. (key, default_values[key])
  563. for key in ['subject', 'body',
  564. 'email_from',
  565. 'partner_ids', 'reply_to',
  566. 'attachment_ids', 'mail_server_id'
  567. ] if key in default_values)
  568. if values.get('body_html'):
  569. values['body'] = values.pop('body_html')
  570. # This onchange should return command instead of ids for x2many field.
  571. values = self._convert_to_write(values)
  572. return {'value': values}
  573. def render_message(self, res_ids):
  574. """Generate template-based values of wizard, for the document records given
  575. by res_ids. This method is meant to be inherited by email_template that
  576. will produce a more complete dictionary, using qweb templates.
  577. Each template is generated for all res_ids, allowing to parse the template
  578. once, and render it multiple times. This is useful for mass mailing where
  579. template rendering represent a significant part of the process.
  580. Default recipients are also computed, based on mail_thread method
  581. _message_get_default_recipients. This allows to ensure a mass mailing has
  582. always some recipients specified.
  583. :param browse wizard: current mail.compose.message browse record
  584. :param list res_ids: list of record ids
  585. :return dict results: for each res_id, the generated template values for
  586. subject, body, email_from and reply_to
  587. """
  588. self.ensure_one()
  589. multi_mode = True
  590. if isinstance(res_ids, int):
  591. multi_mode = False
  592. res_ids = [res_ids]
  593. subjects = self._render_field('subject', res_ids)
  594. # We want to preserve comments in emails so as to keep mso conditionals
  595. bodies = self._render_field('body', res_ids, post_process=True, options={'preserve_comments': self.composition_mode == 'mass_mail'})
  596. emails_from = self._render_field('email_from', res_ids)
  597. replies_to = self._render_field('reply_to', res_ids)
  598. default_recipients = {}
  599. if not self.partner_ids:
  600. records = self.env[self.model].browse(res_ids).sudo()
  601. default_recipients = records._message_get_default_recipients()
  602. results = dict.fromkeys(res_ids, False)
  603. for res_id in res_ids:
  604. results[res_id] = {
  605. 'subject': subjects[res_id],
  606. 'body': bodies[res_id],
  607. 'email_from': emails_from[res_id],
  608. 'reply_to': replies_to[res_id],
  609. }
  610. results[res_id].update(default_recipients.get(res_id, dict()))
  611. # generate template-based values
  612. if self.template_id:
  613. template_values = self.generate_email_for_composer(
  614. self.template_id.id, res_ids,
  615. ['email_to', 'partner_to', 'email_cc', 'attachment_ids', 'mail_server_id'])
  616. else:
  617. template_values = {}
  618. for res_id in res_ids:
  619. if template_values.get(res_id):
  620. # recipients are managed by the template
  621. results[res_id].pop('partner_ids', None)
  622. results[res_id].pop('email_to', None)
  623. results[res_id].pop('email_cc', None)
  624. # remove attachments from template values as they should not be rendered
  625. template_values[res_id].pop('attachment_ids', None)
  626. else:
  627. template_values[res_id] = dict()
  628. # update template values by composer values
  629. template_values[res_id].update(results[res_id])
  630. return multi_mode and template_values or template_values[res_ids[0]]
  631. @api.model
  632. def generate_email_for_composer(self, template_id, res_ids, fields):
  633. """ Call email_template.generate_email(), get fields relevant for
  634. mail.compose.message, transform email_cc and email_to into partner_ids """
  635. multi_mode = True
  636. if isinstance(res_ids, int):
  637. multi_mode = False
  638. res_ids = [res_ids]
  639. returned_fields = fields + ['partner_ids', 'attachments']
  640. values = dict.fromkeys(res_ids, False)
  641. template_values = self.env['mail.template'].with_context(tpl_partners_only=True).browse(template_id).generate_email(res_ids, fields)
  642. for res_id in res_ids:
  643. res_id_values = dict((field, template_values[res_id][field]) for field in returned_fields if template_values[res_id].get(field))
  644. res_id_values['body'] = res_id_values.pop('body_html', '')
  645. values[res_id] = res_id_values
  646. return multi_mode and values or values[res_ids[0]]