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.

585 lines
23 KiB

  1. ##############################################################################
  2. #
  3. # Author: Avoin.Systems
  4. # Copyright 2018 Avoin.Systems
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Affero General Public License as
  8. # published by the Free Software Foundation, either version 3 of the
  9. # License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Affero General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Affero General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. ##############################################################################
  20. import base64
  21. import binascii
  22. import logging
  23. import random
  24. import re
  25. import string
  26. from email.message import Message
  27. from email.utils import formataddr, parseaddr
  28. from Crypto.Cipher import AES
  29. from odoo import api, fields, models, tools
  30. from odoo.tools import frozendict
  31. from odoo.addons.base.models.ir_mail_server import encode_rfc2822_address_header
  32. _logger = logging.getLogger(__name__)
  33. MESSAGE_PREFIX = "msg-"
  34. def random_string(length):
  35. return "".join(
  36. random.choice(string.ascii_lowercase + string.digits) for _ in range(length)
  37. )
  38. def get_key(env):
  39. return env["ir.config_parameter"].get_param("database.secret", "noneedtobestrong")[
  40. :16
  41. ]
  42. def get_cipher(env):
  43. return AES.new(
  44. get_key(env).encode("utf-8"), mode=AES.MODE_CBC, iv=b"veryverysecret81"
  45. )
  46. def encode_msg_id(msg_id, env):
  47. id_padded = "%016d" % msg_id
  48. encrypted = get_cipher(env).encrypt(id_padded.encode("utf-8"))
  49. return base64.b32encode(encrypted).decode("utf-8")
  50. # Remove in Odoo 14
  51. def encode_msg_id_legacy(msg_id, env):
  52. id_padded = "%016d" % msg_id
  53. encrypted = get_cipher(env).encrypt(id_padded.encode("utf-8"))
  54. return base64.urlsafe_b64encode(encrypted).decode("utf-8")
  55. def decode_msg_id(encoded_encrypted_id, env):
  56. try:
  57. # Some email clients don't respect the original Reply-To address case
  58. # and might make them lowercase. Make the encoded ID uppercase.
  59. encrypted = base64.b32decode(encoded_encrypted_id.encode("utf-8").upper())
  60. except binascii.Error:
  61. # Fall back to base64, which was used by the previous versions.
  62. # This can be removed in Odoo 14.
  63. try:
  64. encrypted = base64.urlsafe_b64decode(encoded_encrypted_id.encode("utf-8"))
  65. except binascii.Error:
  66. _logger.error(
  67. "Unable to decode the message ID. The input value "
  68. "is invalid and cannot be decoded. "
  69. "Encoded value: {}".format(encoded_encrypted_id)
  70. )
  71. raise
  72. try:
  73. id_str = get_cipher(env).decrypt(encrypted).decode("utf-8")
  74. except UnicodeDecodeError:
  75. _logger.error(
  76. "Unable to decrypt the message ID. The input value "
  77. "probably wasn't encrypted with the same key. Encoded "
  78. "value: {}".format(encoded_encrypted_id)
  79. )
  80. raise
  81. return int(id_str)
  82. class MailServer(models.Model):
  83. _inherit = "ir.mail_server"
  84. reply_to_method = fields.Selection(
  85. [("default", "Odoo Default"), ("alias", "Alias"), ("msg_id", "Message ID")],
  86. "Reply-To Method",
  87. default="default",
  88. help="Odoo Default: Don't add any unique identifiers into the\n"
  89. "Reply-To address.\n"
  90. "\n"
  91. "Alias: Find or generate an email alias for the Reply-To field of\n "
  92. "every outgoing message so the responses will be automatically \n"
  93. "routed to the correct thread even if the email client (Yes, \n"
  94. "I'm looking at you, Microsoft Outlook) decides to drop the \n"
  95. "References, In-Reply-To and Message-ID fields.\n\n"
  96. "The alias will then be used to generate a RFC 5233 sub-address\n"
  97. "using the Force From Address field as a base, eg.\n"
  98. "odoo@mycompany.fi would become odoo+adf9bacd98732@mycompany.fi\n"
  99. "\n"
  100. "Note that this method has a flaw: if the headers have dropped\n"
  101. "and Odoo can't connect the reply to any message in the thread,\n"
  102. "it will automatically connect it to the first message in the \n"
  103. "thread which often is an internal note and the reply will also\n"
  104. "be marked as an internal note even when it should be a comment."
  105. "\n\n"
  106. "Message ID: Include a prefix and the message ID in encrypted\n"
  107. "and base32 encoded format in the Reply-To\n"
  108. "address to that Odoo will be able to directly connect the\n"
  109. "reply to the original message. Note that in this mode the\n"
  110. "Reply-To address has a priority over References and\n"
  111. "In-Reply-To headers.",
  112. )
  113. force_email_reply_to = fields.Char("Force Reply-To Address",)
  114. force_email_reply_to_name = fields.Char("Force Reply-To Name",)
  115. force_email_reply_to_domain = fields.Char("Force Reply-To Domain",)
  116. force_email_from = fields.Char("Force From Address",)
  117. force_email_sender = fields.Char("Force Sender Address",)
  118. prioritize_reply_to_over_msgid = fields.Boolean(
  119. "Prioritize Reply-To Over Email Headers",
  120. default=True,
  121. help="If this field is selected, the unique Reply-To address "
  122. "generated by the Message ID method will be prioritized "
  123. "over the email headers (default Odoo behavior) in incoming "
  124. "emails. This is recommended when the Reply-To method is set to "
  125. "Message ID.",
  126. )
  127. headers_example = fields.Text(
  128. "Example Headers", compute="_compute_headers_example", store=False,
  129. )
  130. # TODO Implement field input validators
  131. def _get_reply_to_address(self, alias, original_from_name):
  132. self.ensure_one()
  133. force_email_from = encode_rfc2822_address_header(self.force_email_from)
  134. # Split the From address
  135. from_address = force_email_from.split("@")
  136. reply_to_addr = "{alias}@{domain}".format(
  137. alias=alias if alias else from_address[0],
  138. domain=self.force_email_reply_to_domain or from_address[1],
  139. )
  140. if self.force_email_reply_to_name:
  141. reply_to = formataddr((self.force_email_reply_to_name, reply_to_addr))
  142. elif original_from_name:
  143. reply_to = formataddr((original_from_name, reply_to_addr))
  144. else:
  145. reply_to = reply_to_addr
  146. return encode_rfc2822_address_header(reply_to)
  147. @api.depends(
  148. "force_email_sender",
  149. "force_email_reply_to",
  150. "force_email_reply_to_domain",
  151. "force_email_from",
  152. "force_email_reply_to_name",
  153. "reply_to_method",
  154. )
  155. def _compute_headers_example(self):
  156. for server in self:
  157. example = []
  158. if server.force_email_sender:
  159. example.append("Sender: {}".format(server.force_email_sender))
  160. if server.force_email_reply_to:
  161. example.append("Reply-To: {}".format(server.force_email_reply_to))
  162. elif server.force_email_from and server.reply_to_method != "default":
  163. reply_to_pair = server.force_email_from.split("@")
  164. if server.reply_to_method == "alias":
  165. token = "{}+1d278g1082bca"
  166. elif server.reply_to_method == "msg_id":
  167. token = "{}+" + MESSAGE_PREFIX + "p2IxKkfEKugl16juheTT0g=="
  168. else:
  169. token = "INVALID"
  170. _logger.error(
  171. "Invalid reply_to_method found: " + server.reply_to_method
  172. )
  173. # noinspection PyProtectedMember
  174. reply_to = server._get_reply_to_address(
  175. token.format(reply_to_pair[0]), "Original From Person"
  176. )
  177. example.append("Reply-To: {}".format(reply_to))
  178. else:
  179. example.append("Reply-To: Odoo default")
  180. if server.force_email_from:
  181. example.append(
  182. "From: {}".format(
  183. formataddr(("Original From Person", server.force_email_from))
  184. )
  185. )
  186. else:
  187. example.append("From: Odoo default")
  188. server.headers_example = "\n".join(example)
  189. @api.model
  190. def send_email(
  191. self,
  192. message,
  193. mail_server_id=None,
  194. smtp_server=None,
  195. smtp_port=None,
  196. smtp_user=None,
  197. smtp_password=None,
  198. smtp_encryption=None,
  199. smtp_debug=False,
  200. smtp_session=None,
  201. ):
  202. # Get SMTP Server Details from Mail Server
  203. mail_server = None
  204. if mail_server_id:
  205. mail_server = self.sudo().browse(mail_server_id)
  206. elif not smtp_server:
  207. mail_server = self.sudo().search([], order="sequence", limit=1)
  208. # Note that Odoo already has the ability to use a fixed From address
  209. # by settings "email_from" in the Odoo settings. This is however a
  210. # secondary option and here email_from always overrides that.
  211. if mail_server.force_email_from:
  212. original_from_name = parseaddr(message["From"])[0]
  213. force_email_from = encode_rfc2822_address_header(
  214. mail_server.force_email_from
  215. )
  216. del message["From"]
  217. message["From"] = formataddr((original_from_name, force_email_from))
  218. if mail_server.reply_to_method == "alias":
  219. # Find or create an email alias
  220. alias = self.find_or_create_alias(force_email_from.split("@"))
  221. # noinspection PyProtectedMember
  222. reply_to = mail_server._get_reply_to_address(alias, original_from_name,)
  223. del message["Reply-To"]
  224. message["Reply-To"] = reply_to
  225. elif mail_server.reply_to_method == "msg_id":
  226. odoo_msg_id = message.get("Message-Id")
  227. if odoo_msg_id:
  228. # The message_id isn't unique. Prefer the one that has a
  229. # model set and only pick the first record. Odoo does
  230. # almost the same thing in mail.thread.message_route().
  231. odoo_msg = (
  232. self.sudo()
  233. .env["mail.message"]
  234. .search(
  235. [("message_id", "=", odoo_msg_id)], order="model", limit=1
  236. )
  237. )
  238. encrypted_id = encode_msg_id(odoo_msg.id, self.env)
  239. # noinspection PyProtectedMember
  240. reply_to = mail_server._get_reply_to_address(
  241. "{}+{}{}".format(
  242. force_email_from.split("@")[0], MESSAGE_PREFIX, encrypted_id
  243. ),
  244. original_from_name,
  245. )
  246. _logger.info(
  247. 'Generated a new reply-to address "{}" for '
  248. 'Message-Id "{}".'.format(reply_to, odoo_msg_id)
  249. )
  250. del message["Reply-To"]
  251. message["Reply-To"] = reply_to
  252. else:
  253. _logger.warning(
  254. "Couldn't get Message-Id from the message {}. The "
  255. "reply might not find its way to the correct thread.".format(
  256. message.as_string()
  257. )
  258. )
  259. if mail_server.force_email_reply_to:
  260. del message["Reply-To"]
  261. message["Reply-To"] = encode_rfc2822_address_header(
  262. mail_server.force_email_reply_to
  263. )
  264. if mail_server.force_email_sender:
  265. del message["Sender"]
  266. message["Sender"] = encode_rfc2822_address_header(
  267. mail_server.force_email_sender
  268. )
  269. return super(MailServer, self).send_email(
  270. message,
  271. mail_server_id,
  272. smtp_server,
  273. smtp_port,
  274. smtp_user,
  275. smtp_password,
  276. smtp_encryption,
  277. smtp_debug,
  278. smtp_session,
  279. )
  280. def find_or_create_alias(self, from_address):
  281. record_id, record_model_name = self.resolve_record()
  282. if not record_id or not record_model_name:
  283. # Can't create an alias if we don't know the related record
  284. return False
  285. if record_model_name not in self.env:
  286. _logger.error(
  287. "Unable to find or create an alias for outgoing "
  288. "email: invalid_model name {}.".format(record_model_name)
  289. )
  290. return False
  291. # Find an alias
  292. alias_model_id = (
  293. self.env["ir.model"].search([("model", "=", record_model_name)]).id
  294. )
  295. # noinspection PyPep8Naming
  296. Alias = self.env["mail.alias"]
  297. existing_aliases = Alias.search(
  298. [
  299. ("alias_model_id", "=", alias_model_id),
  300. (
  301. "alias_name",
  302. "like",
  303. "{from_address}+".format(from_address=from_address[0]),
  304. ),
  305. ("alias_force_thread_id", "=", record_id),
  306. ("alias_contact", "=", "everyone"), # TODO: check from record
  307. ]
  308. )
  309. if existing_aliases:
  310. return existing_aliases[0].alias_name
  311. # Create a new alias
  312. alias = Alias.create(
  313. {
  314. "alias_model_id": alias_model_id,
  315. "alias_name": "{from_address}+{random_string}".format(
  316. from_address=from_address[0], random_string=random_string(8)
  317. ),
  318. "alias_force_thread_id": record_id,
  319. "alias_contact": "everyone",
  320. }
  321. )
  322. return alias.alias_name
  323. def resolve_record(self):
  324. ctx = self.env.context
  325. # Don't ever use active_id or active_model from the context here.
  326. # It might not be the one that you expect. Go ahead and try, open
  327. # a sales order, go to the related purchase order and send the PO.
  328. record_id = ctx.get("default_res_id")
  329. record_model_name = ctx.get("default_model")
  330. # If incoming_routes isn't enough, we can use ctx['incoming_to'] to
  331. # find a alias directly without active_id and active_model_name.
  332. routes = ctx.get("incoming_routes", [])
  333. if (not record_id or not record_model_name) and routes and len(routes) > 0:
  334. route = routes[0]
  335. record_model_name = route[0]
  336. record_id = route[1]
  337. return record_id, record_model_name
  338. @api.model
  339. def encrypt_message_id(self, message_id):
  340. """
  341. A helper encryption method for debugging mail delivery issues.
  342. :param message_id: The id of the `mail.message`
  343. :return: The id of the `mail.message` encrypted and base64 encoded
  344. """
  345. return encode_msg_id(message_id, self.env)
  346. @api.model
  347. def decrypt_message_id(self, encrypted_id):
  348. """
  349. A helper decryption method for debugging mail delivery issues.
  350. :param encrypted_id: The encrypted and base64 encoded id of
  351. the `mail.message` to be decrypted
  352. :return: The id of the `mail.message`
  353. """
  354. return decode_msg_id(encrypted_id, self.env)
  355. class MailThread(models.AbstractModel):
  356. _inherit = "mail.thread"
  357. """
  358. The process for incoming emails goes something like this:
  359. 1. message_process (processing the incoming message)
  360. 2. message_parse (parsing the email message)
  361. 3. message_route (decides how to route the email)
  362. 4. message_route_process (executes the route)
  363. 5. message_post (posts the message to a thread)
  364. """
  365. @api.model
  366. def message_parse(self, message, save_original=False):
  367. email_to = tools.decode_message_header(message, "To")
  368. email_to_localpart = (tools.email_split(email_to) or [""])[0].split("@", 1)[0]
  369. config_params = self.env["ir.config_parameter"].sudo()
  370. # Check if the To part contains the prefix and a base32/64 encoded string
  371. # Remove the "24," part when migrating to Odoo 14.
  372. prefix_in_to = email_to_localpart and re.search(
  373. r".*" + MESSAGE_PREFIX + "(?P<odoo_id>.{24,32}$)", email_to_localpart
  374. )
  375. prioritize_replyto_over_headers = config_params.get_param(
  376. "email_headers.prioritize_replyto_over_headers", "True"
  377. )
  378. prioritize_replyto_over_headers = (
  379. True if prioritize_replyto_over_headers != "False" else False
  380. )
  381. # If the msg prefix part is found in the To part, find the parent
  382. # message and inject the Message-Id to the In-Reply-To part and
  383. # remove References because it by default takes priority over
  384. # In-Reply-To. We want the unique Reply-To address have the priority.
  385. if prefix_in_to and prioritize_replyto_over_headers:
  386. message_id_encrypted = prefix_in_to.group("odoo_id")
  387. try:
  388. message_id = decode_msg_id(message_id_encrypted, self.env)
  389. parent_id = self.env["mail.message"].browse(message_id)
  390. if parent_id:
  391. # See unit test test_reply_to_method_msg_id_priority
  392. del message["References"]
  393. del message["In-Reply-To"]
  394. message["In-Reply-To"] = parent_id.message_id
  395. else:
  396. _logger.warning(
  397. "Received an invalid mail.message database id in incoming "
  398. "email sent to {}. The email type (comment, note) might "
  399. "be wrong.".format(email_to)
  400. )
  401. except UnicodeDecodeError:
  402. _logger.warning(
  403. "Unique Reply-To address of an incoming email couldn't be "
  404. "decrypted. Falling back to default Odoo behavior."
  405. )
  406. res = super(MailThread, self).message_parse(message, save_original)
  407. strip_message_id = config_params.get_param(
  408. "email_headers.strip_mail_message_ids", "True"
  409. )
  410. strip_message_id = True if strip_message_id != "False" else False
  411. if not strip_message_id == "True":
  412. return res
  413. # When Odoo compares message_id to the one stored in the database when determining
  414. # whether or not the incoming message is a reply to another one, the message_id search
  415. # parameter is stripped before the search. But Odoo does not do anything of the sort when
  416. # a message is created, meaning if some email software (for example Outlook,
  417. # for no particular reason) includes anything strippable at the start of the Message-Id,
  418. # any replies to that message in the future will not find their way correctly, as the
  419. # search yields nothing.
  420. #
  421. # Example of what happened before. The first one is the original Message-Id, and thus also
  422. # the ID that gets stored on the mail.message as the `message_id`
  423. # '\r\n <AM6PR05MB4933DE6BCAD68A037185EBCFFBAF0@AM6PR05MB4933.eurprd05.prod.outlook.com>'
  424. # But when trying to find this message, Odoo takes the above message_id and strips it,
  425. # which results in:
  426. # '<AM6PR05MB4933DE6BCAD68A037185EBCFFBAF0@AM6PR05MB4933.eurprd05.prod.outlook.com>'
  427. # And then the search is done for an exact match, which will fail.
  428. #
  429. # Odoo doesn't, so we must strip the message_ids before they are stored in the database
  430. mail_message_id = res.get("message_id", "")
  431. if mail_message_id:
  432. mail_message_id = mail_message_id.strip()
  433. res["message_id"] = mail_message_id
  434. return res
  435. @api.model
  436. def message_route_process(self, message, message_dict, routes):
  437. ctx = self.env.context.copy()
  438. ctx["incoming_routes"] = routes
  439. ctx["incoming_to"] = message_dict.get("to")
  440. self.env.context = frozendict(ctx)
  441. return super(MailThread, self).message_route_process(
  442. message, message_dict, routes
  443. )
  444. @api.model
  445. def message_route(
  446. self, message, message_dict, model=None, thread_id=None, custom_values=None
  447. ):
  448. # NOTE! If you're going to backport this module to Odoo 11 or Odoo 10,
  449. # you will have to create the mail_bounce_catchall email template
  450. # because it was introduced only in Odoo 12.
  451. if not isinstance(message, Message):
  452. raise TypeError("message must be an " "email.message.Message at this point")
  453. try:
  454. route = super(MailThread, self).message_route(
  455. message, message_dict, model, thread_id, custom_values
  456. )
  457. except ValueError:
  458. # If the headers that connect the incoming message to a thread in
  459. # Odoo have disappeared at some point and the message was sent to
  460. # the catchall address (with a sub-addressing suffix), we will
  461. # skip the default catchall check and perform it here for
  462. # mail.catchall.alias.custom. We do this because the alias check
  463. # if done AFTER the catchall check by default and it may cause
  464. # Odoo to send a bounce message to the sender who sent the email to
  465. # the correct thread-specific address.
  466. catchall_alias = (
  467. self.env["ir.config_parameter"]
  468. .sudo()
  469. .get_param("mail.catchall.alias.custom")
  470. )
  471. email_to = tools.decode_message_header(message, "To")
  472. email_to_localpart = (
  473. (tools.email_split(email_to) or [""])[0].split("@", 1)[0].lower()
  474. )
  475. message_id = message.get("Message-Id")
  476. email_from = tools.decode_message_header(message, "From")
  477. # check it does not directly contact catchall
  478. if catchall_alias and catchall_alias in email_to_localpart:
  479. _logger.info(
  480. "Routing mail from %s to %s with Message-Id %s: "
  481. "direct write to catchall, bounce",
  482. email_from,
  483. email_to,
  484. message_id,
  485. )
  486. body = self.env.ref("mail.mail_bounce_catchall").render(
  487. {"message": message}, engine="ir.qweb"
  488. )
  489. self._routing_create_bounce_email(
  490. email_from, body, message, reply_to=self.env.user.company_id.email
  491. )
  492. return []
  493. else:
  494. raise
  495. return route