Merge branch 'main' into avm99963-monorail

Merged commit 34d8229ae2b51fb1a15bd208e6fe6185c94f6266

GitOrigin-RevId: 7ee0917f93a577e475f8e09526dd144d245593f4
diff --git a/framework/emailfmt.py b/framework/emailfmt.py
index 2933fea..e14075c 100644
--- a/framework/emailfmt.py
+++ b/framework/emailfmt.py
@@ -1,7 +1,6 @@
-# Copyright 2016 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style
-# license that can be found in the LICENSE file or at
-# https://developers.google.com/open-source/licenses/bsd
+# Copyright 2016 The Chromium Authors
+# Use of this source code is governed by a BSD-style license that can be
+# found in the LICENSE file.
 
 """Functions that format or parse email messages in Monorail.
 
@@ -13,13 +12,18 @@
 from __future__ import division
 from __future__ import absolute_import
 
+import hashlib
 import hmac
 import logging
 import re
-import rfc822
 
 import six
 
+if six.PY2:
+  import rfc822
+else:
+  import email.utils
+
 from google.appengine.api import app_identity
 
 import settings
@@ -116,7 +120,10 @@
 
 def _ExtractAddrs(header_value):
   """Given a message header value, return email address found there."""
-  friendly_addr_pairs = list(rfc822.AddressList(header_value))
+  if six.PY2:
+    friendly_addr_pairs = list(rfc822.AddressList(header_value))
+  else:
+    friendly_addr_pairs = email.utils.getaddresses([header_value])
   return [addr for _friendly, addr in friendly_addr_pairs]
 
 
@@ -230,11 +237,15 @@
   if isinstance(normalized_subject, six.text_type):
     normalized_subject = normalized_subject.encode('utf-8')
   mail_hmac_key = secrets_svc.GetEmailKey()
+  to_addr_hash = hmac.new(
+      mail_hmac_key, six.ensure_binary(to_addr),
+      digestmod=hashlib.md5).hexdigest()
+  subject_hash = hmac.new(
+      mail_hmac_key,
+      six.ensure_binary(normalized_subject),
+      digestmod=hashlib.md5).hexdigest()
   return '<0=%s=%s=%s@%s>' % (
-      hmac.new(mail_hmac_key, to_addr).hexdigest(),
-      hmac.new(mail_hmac_key, normalized_subject).hexdigest(),
-      from_addr.split('@')[0],
-      MailDomain())
+      to_addr_hash, subject_hash, from_addr.split('@')[0], MailDomain())
 
 
 def GetReferences(to_addr, subject, seq_num, project_from_addr):