From 55b68de643b5c2d5f0a8ea7587ab3b2966021ccc Mon Sep 17 00:00:00 2001 From: Chason Chaffin Date: Tue, 2 Jul 2019 21:15:32 +0900 Subject: [PATCH] Fixed #30608 -- Fixed non-unicode EmailMessage crash when domain name for localhost is non-ASCII. Assisted by felixxm. --- AUTHORS | 1 + django/core/mail/utils.py | 4 +++- tests/mail/tests.py | 10 +++++++++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/AUTHORS b/AUTHORS index 9bae13abb0..640ef00920 100644 --- a/AUTHORS +++ b/AUTHORS @@ -166,6 +166,7 @@ answer newbie questions, and generally made Django that much better: ChaosKCW Charlie Leifer charly.wilhelm@gmail.com + Chason Chaffin Cheng Zhang Chris Adams Chris Beaven diff --git a/django/core/mail/utils.py b/django/core/mail/utils.py index d18dfe4667..1e48faa366 100644 --- a/django/core/mail/utils.py +++ b/django/core/mail/utils.py @@ -4,6 +4,8 @@ Email message and email sending related helper functions. import socket +from django.utils.encoding import punycode + # Cache the hostname, but do it lazily: socket.getfqdn() can take a couple of # seconds, which slows down the restart of the server. @@ -13,7 +15,7 @@ class CachedDnsName: def get_fqdn(self): if not hasattr(self, '_fqdn'): - self._fqdn = socket.getfqdn() + self._fqdn = punycode(socket.getfqdn()) return self._fqdn diff --git a/tests/mail/tests.py b/tests/mail/tests.py index 15593dc3f7..6de819965a 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -14,10 +14,11 @@ from email.utils import parseaddr from io import StringIO from smtplib import SMTP, SMTPAuthenticationError, SMTPException from ssl import SSLError +from unittest import mock from django.core import mail from django.core.mail import ( - EmailMessage, EmailMultiAlternatives, mail_admins, mail_managers, + DNS_NAME, EmailMessage, EmailMultiAlternatives, mail_admins, mail_managers, send_mail, send_mass_mail, ) from django.core.mail.backends import console, dummy, filebased, locmem, smtp @@ -365,6 +366,13 @@ class MailTests(HeadersCheckMixin, SimpleTestCase): self.assertEqual(msg.body, '') self.assertEqual(msg.message().get_payload(), '') + @mock.patch('socket.getfqdn', return_value='漢字') + def test_non_ascii_dns_non_unicode_email(self, mocked_getfqdn): + delattr(DNS_NAME, '_fqdn') + email = EmailMessage('subject', 'content', 'from@example.com', ['to@example.com']) + email.encoding = 'iso-8859-1' + self.assertIn('@xn--p8s937b>', email.message()['Message-ID']) + def test_encoding(self): """ Regression for #12791 - Encode body correctly with other encodings