|
4 | 4 | from email.MIMEText import MIMEText |
5 | 5 | from email.MIMEMessage import MIMEMessage |
6 | 6 | from email.MIMEMultipart import MIMEMultipart |
| 7 | +from email.header import Header |
7 | 8 | from email import message_from_string |
8 | 9 | import smtplib |
9 | 10 | from django.conf import settings |
@@ -190,7 +191,25 @@ def condition_message(to, frm, subject, msg, cc, extra): |
190 | 191 | cc = ", ".join([isinstance(addr, tuple) and formataddr(addr) or addr for addr in cc if addr]) |
191 | 192 | if frm: |
192 | 193 | msg['From'] = frm |
193 | | - msg['To'] = to |
| 194 | + |
| 195 | + # The following is a hack to avoid an issue with how the email module (as of version 4.0.3) |
| 196 | + # breaks lines when encoding header fields with anything other than the us-ascii codec. |
| 197 | + # This allows the Header implementation to encode each display name as a separate chunk. |
| 198 | + # The resulting encode produces a string that is us-ascii and has a good density of |
| 199 | + # "higher-level syntactic breaks" |
| 200 | + to_hdr = Header(header_name='To') |
| 201 | + for name, addr in getaddresses([to]): |
| 202 | + if addr != '' and not addr.startswith('unknown-email-'): |
| 203 | + if name: |
| 204 | + to_hdr.append('"%s"' % name) |
| 205 | + to_hdr.append("<%s>," % addr) |
| 206 | + to_str = to_hdr.encode() |
| 207 | + if to_str and to_str[-1] == ',': |
| 208 | + to_str=to_str[:-1] |
| 209 | + # It's important to use this string, and not assign the Header object. |
| 210 | + # Code downstream from this assumes that the msg['To'] will return a string, not an instance |
| 211 | + msg['To'] = to_str |
| 212 | + |
194 | 213 | if cc: |
195 | 214 | msg['Cc'] = cc |
196 | 215 | msg['Subject'] = subject |
|
0 commit comments