##// END OF EJS Templates
mail: ensure that Python2.4 to 2.7 use the same header format...
Nicolas Dumazet -
r11542:594b9884 stable
parent child Browse files
Show More
@@ -1,206 +1,226
1 # mail.py - mail sending bits for mercurial
1 # mail.py - mail sending bits for mercurial
2 #
2 #
3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
3 # Copyright 2006 Matt Mackall <mpm@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
6 # GNU General Public License version 2 or any later version.
7
7
8 from i18n import _
8 from i18n import _
9 import util, encoding
9 import util, encoding
10 import os, smtplib, socket, quopri
10 import os, smtplib, socket, quopri
11 import email.Header, email.MIMEText, email.Utils
11 import email.Header, email.MIMEText, email.Utils
12
12
13 _oldheaderinit = email.Header.Header.__init__
14 def _unifiedheaderinit(self, *args, **kw):
15 """
16 Python2.7 introduces a backwards incompatible change
17 (Python issue1974, r70772) in email.Generator.Generator code:
18 pre-2.7 code passed "continuation_ws='\t'" to the Header
19 constructor, and 2.7 removed this parameter.
20
21 Default argument is continuation_ws=' ', which means that the
22 behaviour is different in <2.7 and 2.7
23
24 We consider the 2.7 behaviour to be preferable, but need
25 to have an unified behaviour for versions 2.4 to 2.7
26 """
27 # override continuation_ws
28 kw['continuation_ws'] = ' '
29 _oldheaderinit(self, *args, **kw)
30
31 email.Header.Header.__dict__['__init__'] = _unifiedheaderinit
32
13 def _smtp(ui):
33 def _smtp(ui):
14 '''build an smtp connection and return a function to send mail'''
34 '''build an smtp connection and return a function to send mail'''
15 local_hostname = ui.config('smtp', 'local_hostname')
35 local_hostname = ui.config('smtp', 'local_hostname')
16 s = smtplib.SMTP(local_hostname=local_hostname)
36 s = smtplib.SMTP(local_hostname=local_hostname)
17 mailhost = ui.config('smtp', 'host')
37 mailhost = ui.config('smtp', 'host')
18 if not mailhost:
38 if not mailhost:
19 raise util.Abort(_('no [smtp]host in hgrc - cannot send mail'))
39 raise util.Abort(_('no [smtp]host in hgrc - cannot send mail'))
20 mailport = int(ui.config('smtp', 'port', 25))
40 mailport = int(ui.config('smtp', 'port', 25))
21 ui.note(_('sending mail: smtp host %s, port %s\n') %
41 ui.note(_('sending mail: smtp host %s, port %s\n') %
22 (mailhost, mailport))
42 (mailhost, mailport))
23 s.connect(host=mailhost, port=mailport)
43 s.connect(host=mailhost, port=mailport)
24 if ui.configbool('smtp', 'tls'):
44 if ui.configbool('smtp', 'tls'):
25 if not hasattr(socket, 'ssl'):
45 if not hasattr(socket, 'ssl'):
26 raise util.Abort(_("can't use TLS: Python SSL support "
46 raise util.Abort(_("can't use TLS: Python SSL support "
27 "not installed"))
47 "not installed"))
28 ui.note(_('(using tls)\n'))
48 ui.note(_('(using tls)\n'))
29 s.ehlo()
49 s.ehlo()
30 s.starttls()
50 s.starttls()
31 s.ehlo()
51 s.ehlo()
32 username = ui.config('smtp', 'username')
52 username = ui.config('smtp', 'username')
33 password = ui.config('smtp', 'password')
53 password = ui.config('smtp', 'password')
34 if username and not password:
54 if username and not password:
35 password = ui.getpass()
55 password = ui.getpass()
36 if username and password:
56 if username and password:
37 ui.note(_('(authenticating to mail server as %s)\n') %
57 ui.note(_('(authenticating to mail server as %s)\n') %
38 (username))
58 (username))
39 try:
59 try:
40 s.login(username, password)
60 s.login(username, password)
41 except smtplib.SMTPException, inst:
61 except smtplib.SMTPException, inst:
42 raise util.Abort(inst)
62 raise util.Abort(inst)
43
63
44 def send(sender, recipients, msg):
64 def send(sender, recipients, msg):
45 try:
65 try:
46 return s.sendmail(sender, recipients, msg)
66 return s.sendmail(sender, recipients, msg)
47 except smtplib.SMTPRecipientsRefused, inst:
67 except smtplib.SMTPRecipientsRefused, inst:
48 recipients = [r[1] for r in inst.recipients.values()]
68 recipients = [r[1] for r in inst.recipients.values()]
49 raise util.Abort('\n' + '\n'.join(recipients))
69 raise util.Abort('\n' + '\n'.join(recipients))
50 except smtplib.SMTPException, inst:
70 except smtplib.SMTPException, inst:
51 raise util.Abort(inst)
71 raise util.Abort(inst)
52
72
53 return send
73 return send
54
74
55 def _sendmail(ui, sender, recipients, msg):
75 def _sendmail(ui, sender, recipients, msg):
56 '''send mail using sendmail.'''
76 '''send mail using sendmail.'''
57 program = ui.config('email', 'method')
77 program = ui.config('email', 'method')
58 cmdline = '%s -f %s %s' % (program, util.email(sender),
78 cmdline = '%s -f %s %s' % (program, util.email(sender),
59 ' '.join(map(util.email, recipients)))
79 ' '.join(map(util.email, recipients)))
60 ui.note(_('sending mail: %s\n') % cmdline)
80 ui.note(_('sending mail: %s\n') % cmdline)
61 fp = util.popen(cmdline, 'w')
81 fp = util.popen(cmdline, 'w')
62 fp.write(msg)
82 fp.write(msg)
63 ret = fp.close()
83 ret = fp.close()
64 if ret:
84 if ret:
65 raise util.Abort('%s %s' % (
85 raise util.Abort('%s %s' % (
66 os.path.basename(program.split(None, 1)[0]),
86 os.path.basename(program.split(None, 1)[0]),
67 util.explain_exit(ret)[0]))
87 util.explain_exit(ret)[0]))
68
88
69 def connect(ui):
89 def connect(ui):
70 '''make a mail connection. return a function to send mail.
90 '''make a mail connection. return a function to send mail.
71 call as sendmail(sender, list-of-recipients, msg).'''
91 call as sendmail(sender, list-of-recipients, msg).'''
72 if ui.config('email', 'method', 'smtp') == 'smtp':
92 if ui.config('email', 'method', 'smtp') == 'smtp':
73 return _smtp(ui)
93 return _smtp(ui)
74 return lambda s, r, m: _sendmail(ui, s, r, m)
94 return lambda s, r, m: _sendmail(ui, s, r, m)
75
95
76 def sendmail(ui, sender, recipients, msg):
96 def sendmail(ui, sender, recipients, msg):
77 send = connect(ui)
97 send = connect(ui)
78 return send(sender, recipients, msg)
98 return send(sender, recipients, msg)
79
99
80 def validateconfig(ui):
100 def validateconfig(ui):
81 '''determine if we have enough config data to try sending email.'''
101 '''determine if we have enough config data to try sending email.'''
82 method = ui.config('email', 'method', 'smtp')
102 method = ui.config('email', 'method', 'smtp')
83 if method == 'smtp':
103 if method == 'smtp':
84 if not ui.config('smtp', 'host'):
104 if not ui.config('smtp', 'host'):
85 raise util.Abort(_('smtp specified as email transport, '
105 raise util.Abort(_('smtp specified as email transport, '
86 'but no smtp host configured'))
106 'but no smtp host configured'))
87 else:
107 else:
88 if not util.find_exe(method):
108 if not util.find_exe(method):
89 raise util.Abort(_('%r specified as email transport, '
109 raise util.Abort(_('%r specified as email transport, '
90 'but not in PATH') % method)
110 'but not in PATH') % method)
91
111
92 def mimetextpatch(s, subtype='plain', display=False):
112 def mimetextpatch(s, subtype='plain', display=False):
93 '''If patch in utf-8 transfer-encode it.'''
113 '''If patch in utf-8 transfer-encode it.'''
94
114
95 enc = None
115 enc = None
96 for line in s.splitlines():
116 for line in s.splitlines():
97 if len(line) > 950:
117 if len(line) > 950:
98 s = quopri.encodestring(s)
118 s = quopri.encodestring(s)
99 enc = "quoted-printable"
119 enc = "quoted-printable"
100 break
120 break
101
121
102 cs = 'us-ascii'
122 cs = 'us-ascii'
103 if not display:
123 if not display:
104 try:
124 try:
105 s.decode('us-ascii')
125 s.decode('us-ascii')
106 except UnicodeDecodeError:
126 except UnicodeDecodeError:
107 try:
127 try:
108 s.decode('utf-8')
128 s.decode('utf-8')
109 cs = 'utf-8'
129 cs = 'utf-8'
110 except UnicodeDecodeError:
130 except UnicodeDecodeError:
111 # We'll go with us-ascii as a fallback.
131 # We'll go with us-ascii as a fallback.
112 pass
132 pass
113
133
114 msg = email.MIMEText.MIMEText(s, subtype, cs)
134 msg = email.MIMEText.MIMEText(s, subtype, cs)
115 if enc:
135 if enc:
116 del msg['Content-Transfer-Encoding']
136 del msg['Content-Transfer-Encoding']
117 msg['Content-Transfer-Encoding'] = enc
137 msg['Content-Transfer-Encoding'] = enc
118 return msg
138 return msg
119
139
120 def _charsets(ui):
140 def _charsets(ui):
121 '''Obtains charsets to send mail parts not containing patches.'''
141 '''Obtains charsets to send mail parts not containing patches.'''
122 charsets = [cs.lower() for cs in ui.configlist('email', 'charsets')]
142 charsets = [cs.lower() for cs in ui.configlist('email', 'charsets')]
123 fallbacks = [encoding.fallbackencoding.lower(),
143 fallbacks = [encoding.fallbackencoding.lower(),
124 encoding.encoding.lower(), 'utf-8']
144 encoding.encoding.lower(), 'utf-8']
125 for cs in fallbacks: # find unique charsets while keeping order
145 for cs in fallbacks: # find unique charsets while keeping order
126 if cs not in charsets:
146 if cs not in charsets:
127 charsets.append(cs)
147 charsets.append(cs)
128 return [cs for cs in charsets if not cs.endswith('ascii')]
148 return [cs for cs in charsets if not cs.endswith('ascii')]
129
149
130 def _encode(ui, s, charsets):
150 def _encode(ui, s, charsets):
131 '''Returns (converted) string, charset tuple.
151 '''Returns (converted) string, charset tuple.
132 Finds out best charset by cycling through sendcharsets in descending
152 Finds out best charset by cycling through sendcharsets in descending
133 order. Tries both encoding and fallbackencoding for input. Only as
153 order. Tries both encoding and fallbackencoding for input. Only as
134 last resort send as is in fake ascii.
154 last resort send as is in fake ascii.
135 Caveat: Do not use for mail parts containing patches!'''
155 Caveat: Do not use for mail parts containing patches!'''
136 try:
156 try:
137 s.decode('ascii')
157 s.decode('ascii')
138 except UnicodeDecodeError:
158 except UnicodeDecodeError:
139 sendcharsets = charsets or _charsets(ui)
159 sendcharsets = charsets or _charsets(ui)
140 for ics in (encoding.encoding, encoding.fallbackencoding):
160 for ics in (encoding.encoding, encoding.fallbackencoding):
141 try:
161 try:
142 u = s.decode(ics)
162 u = s.decode(ics)
143 except UnicodeDecodeError:
163 except UnicodeDecodeError:
144 continue
164 continue
145 for ocs in sendcharsets:
165 for ocs in sendcharsets:
146 try:
166 try:
147 return u.encode(ocs), ocs
167 return u.encode(ocs), ocs
148 except UnicodeEncodeError:
168 except UnicodeEncodeError:
149 pass
169 pass
150 except LookupError:
170 except LookupError:
151 ui.warn(_('ignoring invalid sendcharset: %s\n') % ocs)
171 ui.warn(_('ignoring invalid sendcharset: %s\n') % ocs)
152 # if ascii, or all conversion attempts fail, send (broken) ascii
172 # if ascii, or all conversion attempts fail, send (broken) ascii
153 return s, 'us-ascii'
173 return s, 'us-ascii'
154
174
155 def headencode(ui, s, charsets=None, display=False):
175 def headencode(ui, s, charsets=None, display=False):
156 '''Returns RFC-2047 compliant header from given string.'''
176 '''Returns RFC-2047 compliant header from given string.'''
157 if not display:
177 if not display:
158 # split into words?
178 # split into words?
159 s, cs = _encode(ui, s, charsets)
179 s, cs = _encode(ui, s, charsets)
160 return str(email.Header.Header(s, cs))
180 return str(email.Header.Header(s, cs))
161 return s
181 return s
162
182
163 def _addressencode(ui, name, addr, charsets=None):
183 def _addressencode(ui, name, addr, charsets=None):
164 name = headencode(ui, name, charsets)
184 name = headencode(ui, name, charsets)
165 try:
185 try:
166 acc, dom = addr.split('@')
186 acc, dom = addr.split('@')
167 acc = acc.encode('ascii')
187 acc = acc.encode('ascii')
168 dom = dom.decode(encoding.encoding).encode('idna')
188 dom = dom.decode(encoding.encoding).encode('idna')
169 addr = '%s@%s' % (acc, dom)
189 addr = '%s@%s' % (acc, dom)
170 except UnicodeDecodeError:
190 except UnicodeDecodeError:
171 raise util.Abort(_('invalid email address: %s') % addr)
191 raise util.Abort(_('invalid email address: %s') % addr)
172 except ValueError:
192 except ValueError:
173 try:
193 try:
174 # too strict?
194 # too strict?
175 addr = addr.encode('ascii')
195 addr = addr.encode('ascii')
176 except UnicodeDecodeError:
196 except UnicodeDecodeError:
177 raise util.Abort(_('invalid local address: %s') % addr)
197 raise util.Abort(_('invalid local address: %s') % addr)
178 return email.Utils.formataddr((name, addr))
198 return email.Utils.formataddr((name, addr))
179
199
180 def addressencode(ui, address, charsets=None, display=False):
200 def addressencode(ui, address, charsets=None, display=False):
181 '''Turns address into RFC-2047 compliant header.'''
201 '''Turns address into RFC-2047 compliant header.'''
182 if display or not address:
202 if display or not address:
183 return address or ''
203 return address or ''
184 name, addr = email.Utils.parseaddr(address)
204 name, addr = email.Utils.parseaddr(address)
185 return _addressencode(ui, name, addr, charsets)
205 return _addressencode(ui, name, addr, charsets)
186
206
187 def addrlistencode(ui, addrs, charsets=None, display=False):
207 def addrlistencode(ui, addrs, charsets=None, display=False):
188 '''Turns a list of addresses into a list of RFC-2047 compliant headers.
208 '''Turns a list of addresses into a list of RFC-2047 compliant headers.
189 A single element of input list may contain multiple addresses, but output
209 A single element of input list may contain multiple addresses, but output
190 always has one address per item'''
210 always has one address per item'''
191 if display:
211 if display:
192 return [a.strip() for a in addrs if a.strip()]
212 return [a.strip() for a in addrs if a.strip()]
193
213
194 result = []
214 result = []
195 for name, addr in email.Utils.getaddresses(addrs):
215 for name, addr in email.Utils.getaddresses(addrs):
196 if name or addr:
216 if name or addr:
197 result.append(_addressencode(ui, name, addr, charsets))
217 result.append(_addressencode(ui, name, addr, charsets))
198 return result
218 return result
199
219
200 def mimeencode(ui, s, charsets=None, display=False):
220 def mimeencode(ui, s, charsets=None, display=False):
201 '''creates mime text object, encodes it if needed, and sets
221 '''creates mime text object, encodes it if needed, and sets
202 charset and transfer-encoding accordingly.'''
222 charset and transfer-encoding accordingly.'''
203 cs = 'us-ascii'
223 cs = 'us-ascii'
204 if not display:
224 if not display:
205 s, cs = _encode(ui, s, charsets)
225 s, cs = _encode(ui, s, charsets)
206 return email.MIMEText.MIMEText(s, 'plain', cs)
226 return email.MIMEText.MIMEText(s, 'plain', cs)
General Comments 0
You need to be logged in to leave comments. Login now