##// END OF EJS Templates
email: Catch exceptions during send....
David Soria Parra -
r9246:2de7d965 default
parent child Browse files
Show More
@@ -1,187 +1,190 b''
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, incorporated herein by reference.
6 # GNU General Public License version 2, incorporated herein by reference.
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 def _smtp(ui):
13 def _smtp(ui):
14 '''build an smtp connection and return a function to send mail'''
14 '''build an smtp connection and return a function to send mail'''
15 local_hostname = ui.config('smtp', 'local_hostname')
15 local_hostname = ui.config('smtp', 'local_hostname')
16 s = smtplib.SMTP(local_hostname=local_hostname)
16 s = smtplib.SMTP(local_hostname=local_hostname)
17 mailhost = ui.config('smtp', 'host')
17 mailhost = ui.config('smtp', 'host')
18 if not mailhost:
18 if not mailhost:
19 raise util.Abort(_('no [smtp]host in hgrc - cannot send mail'))
19 raise util.Abort(_('no [smtp]host in hgrc - cannot send mail'))
20 mailport = int(ui.config('smtp', 'port', 25))
20 mailport = int(ui.config('smtp', 'port', 25))
21 ui.note(_('sending mail: smtp host %s, port %s\n') %
21 ui.note(_('sending mail: smtp host %s, port %s\n') %
22 (mailhost, mailport))
22 (mailhost, mailport))
23 s.connect(host=mailhost, port=mailport)
23 s.connect(host=mailhost, port=mailport)
24 if ui.configbool('smtp', 'tls'):
24 if ui.configbool('smtp', 'tls'):
25 if not hasattr(socket, 'ssl'):
25 if not hasattr(socket, 'ssl'):
26 raise util.Abort(_("can't use TLS: Python SSL support "
26 raise util.Abort(_("can't use TLS: Python SSL support "
27 "not installed"))
27 "not installed"))
28 ui.note(_('(using tls)\n'))
28 ui.note(_('(using tls)\n'))
29 s.ehlo()
29 s.ehlo()
30 s.starttls()
30 s.starttls()
31 s.ehlo()
31 s.ehlo()
32 username = ui.config('smtp', 'username')
32 username = ui.config('smtp', 'username')
33 password = ui.config('smtp', 'password')
33 password = ui.config('smtp', 'password')
34 if username and not password:
34 if username and not password:
35 password = ui.getpass()
35 password = ui.getpass()
36 if username and password:
36 if username and password:
37 ui.note(_('(authenticating to mail server as %s)\n') %
37 ui.note(_('(authenticating to mail server as %s)\n') %
38 (username))
38 (username))
39 s.login(username, password)
39 try:
40 s.login(username, password)
41 except smtplib.SMTPException, inst:
42 raise util.Abort(inst)
40
43
41 def send(sender, recipients, msg):
44 def send(sender, recipients, msg):
42 try:
45 try:
43 return s.sendmail(sender, recipients, msg)
46 return s.sendmail(sender, recipients, msg)
44 except smtplib.SMTPRecipientsRefused, inst:
47 except smtplib.SMTPRecipientsRefused, inst:
45 recipients = [r[1] for r in inst.recipients.values()]
48 recipients = [r[1] for r in inst.recipients.values()]
46 raise util.Abort('\n' + '\n'.join(recipients))
49 raise util.Abort('\n' + '\n'.join(recipients))
47 except smtplib.SMTPException, inst:
50 except smtplib.SMTPException, inst:
48 raise util.Abort(inst)
51 raise util.Abort(inst)
49
52
50 return send
53 return send
51
54
52 def _sendmail(ui, sender, recipients, msg):
55 def _sendmail(ui, sender, recipients, msg):
53 '''send mail using sendmail.'''
56 '''send mail using sendmail.'''
54 program = ui.config('email', 'method')
57 program = ui.config('email', 'method')
55 cmdline = '%s -f %s %s' % (program, util.email(sender),
58 cmdline = '%s -f %s %s' % (program, util.email(sender),
56 ' '.join(map(util.email, recipients)))
59 ' '.join(map(util.email, recipients)))
57 ui.note(_('sending mail: %s\n') % cmdline)
60 ui.note(_('sending mail: %s\n') % cmdline)
58 fp = util.popen(cmdline, 'w')
61 fp = util.popen(cmdline, 'w')
59 fp.write(msg)
62 fp.write(msg)
60 ret = fp.close()
63 ret = fp.close()
61 if ret:
64 if ret:
62 raise util.Abort('%s %s' % (
65 raise util.Abort('%s %s' % (
63 os.path.basename(program.split(None, 1)[0]),
66 os.path.basename(program.split(None, 1)[0]),
64 util.explain_exit(ret)[0]))
67 util.explain_exit(ret)[0]))
65
68
66 def connect(ui):
69 def connect(ui):
67 '''make a mail connection. return a function to send mail.
70 '''make a mail connection. return a function to send mail.
68 call as sendmail(sender, list-of-recipients, msg).'''
71 call as sendmail(sender, list-of-recipients, msg).'''
69 if ui.config('email', 'method', 'smtp') == 'smtp':
72 if ui.config('email', 'method', 'smtp') == 'smtp':
70 return _smtp(ui)
73 return _smtp(ui)
71 return lambda s, r, m: _sendmail(ui, s, r, m)
74 return lambda s, r, m: _sendmail(ui, s, r, m)
72
75
73 def sendmail(ui, sender, recipients, msg):
76 def sendmail(ui, sender, recipients, msg):
74 send = connect(ui)
77 send = connect(ui)
75 return send(sender, recipients, msg)
78 return send(sender, recipients, msg)
76
79
77 def validateconfig(ui):
80 def validateconfig(ui):
78 '''determine if we have enough config data to try sending email.'''
81 '''determine if we have enough config data to try sending email.'''
79 method = ui.config('email', 'method', 'smtp')
82 method = ui.config('email', 'method', 'smtp')
80 if method == 'smtp':
83 if method == 'smtp':
81 if not ui.config('smtp', 'host'):
84 if not ui.config('smtp', 'host'):
82 raise util.Abort(_('smtp specified as email transport, '
85 raise util.Abort(_('smtp specified as email transport, '
83 'but no smtp host configured'))
86 'but no smtp host configured'))
84 else:
87 else:
85 if not util.find_exe(method):
88 if not util.find_exe(method):
86 raise util.Abort(_('%r specified as email transport, '
89 raise util.Abort(_('%r specified as email transport, '
87 'but not in PATH') % method)
90 'but not in PATH') % method)
88
91
89 def mimetextpatch(s, subtype='plain', display=False):
92 def mimetextpatch(s, subtype='plain', display=False):
90 '''If patch in utf-8 transfer-encode it.'''
93 '''If patch in utf-8 transfer-encode it.'''
91
94
92 enc = None
95 enc = None
93 for line in s.splitlines():
96 for line in s.splitlines():
94 if len(line) > 950:
97 if len(line) > 950:
95 s = quopri.encodestring(s)
98 s = quopri.encodestring(s)
96 enc = "quoted-printable"
99 enc = "quoted-printable"
97 break
100 break
98
101
99 cs = 'us-ascii'
102 cs = 'us-ascii'
100 if not display:
103 if not display:
101 try:
104 try:
102 s.decode('us-ascii')
105 s.decode('us-ascii')
103 except UnicodeDecodeError:
106 except UnicodeDecodeError:
104 try:
107 try:
105 s.decode('utf-8')
108 s.decode('utf-8')
106 cs = 'utf-8'
109 cs = 'utf-8'
107 except UnicodeDecodeError:
110 except UnicodeDecodeError:
108 # We'll go with us-ascii as a fallback.
111 # We'll go with us-ascii as a fallback.
109 pass
112 pass
110
113
111 msg = email.MIMEText.MIMEText(s, subtype, cs)
114 msg = email.MIMEText.MIMEText(s, subtype, cs)
112 if enc:
115 if enc:
113 del msg['Content-Transfer-Encoding']
116 del msg['Content-Transfer-Encoding']
114 msg['Content-Transfer-Encoding'] = enc
117 msg['Content-Transfer-Encoding'] = enc
115 return msg
118 return msg
116
119
117 def _charsets(ui):
120 def _charsets(ui):
118 '''Obtains charsets to send mail parts not containing patches.'''
121 '''Obtains charsets to send mail parts not containing patches.'''
119 charsets = [cs.lower() for cs in ui.configlist('email', 'charsets')]
122 charsets = [cs.lower() for cs in ui.configlist('email', 'charsets')]
120 fallbacks = [encoding.fallbackencoding.lower(),
123 fallbacks = [encoding.fallbackencoding.lower(),
121 encoding.encoding.lower(), 'utf-8']
124 encoding.encoding.lower(), 'utf-8']
122 for cs in fallbacks: # find unique charsets while keeping order
125 for cs in fallbacks: # find unique charsets while keeping order
123 if cs not in charsets:
126 if cs not in charsets:
124 charsets.append(cs)
127 charsets.append(cs)
125 return [cs for cs in charsets if not cs.endswith('ascii')]
128 return [cs for cs in charsets if not cs.endswith('ascii')]
126
129
127 def _encode(ui, s, charsets):
130 def _encode(ui, s, charsets):
128 '''Returns (converted) string, charset tuple.
131 '''Returns (converted) string, charset tuple.
129 Finds out best charset by cycling through sendcharsets in descending
132 Finds out best charset by cycling through sendcharsets in descending
130 order. Tries both encoding and fallbackencoding for input. Only as
133 order. Tries both encoding and fallbackencoding for input. Only as
131 last resort send as is in fake ascii.
134 last resort send as is in fake ascii.
132 Caveat: Do not use for mail parts containing patches!'''
135 Caveat: Do not use for mail parts containing patches!'''
133 try:
136 try:
134 s.decode('ascii')
137 s.decode('ascii')
135 except UnicodeDecodeError:
138 except UnicodeDecodeError:
136 sendcharsets = charsets or _charsets(ui)
139 sendcharsets = charsets or _charsets(ui)
137 for ics in (encoding.encoding, encoding.fallbackencoding):
140 for ics in (encoding.encoding, encoding.fallbackencoding):
138 try:
141 try:
139 u = s.decode(ics)
142 u = s.decode(ics)
140 except UnicodeDecodeError:
143 except UnicodeDecodeError:
141 continue
144 continue
142 for ocs in sendcharsets:
145 for ocs in sendcharsets:
143 try:
146 try:
144 return u.encode(ocs), ocs
147 return u.encode(ocs), ocs
145 except UnicodeEncodeError:
148 except UnicodeEncodeError:
146 pass
149 pass
147 except LookupError:
150 except LookupError:
148 ui.warn(_('ignoring invalid sendcharset: %s\n') % ocs)
151 ui.warn(_('ignoring invalid sendcharset: %s\n') % ocs)
149 # if ascii, or all conversion attempts fail, send (broken) ascii
152 # if ascii, or all conversion attempts fail, send (broken) ascii
150 return s, 'us-ascii'
153 return s, 'us-ascii'
151
154
152 def headencode(ui, s, charsets=None, display=False):
155 def headencode(ui, s, charsets=None, display=False):
153 '''Returns RFC-2047 compliant header from given string.'''
156 '''Returns RFC-2047 compliant header from given string.'''
154 if not display:
157 if not display:
155 # split into words?
158 # split into words?
156 s, cs = _encode(ui, s, charsets)
159 s, cs = _encode(ui, s, charsets)
157 return str(email.Header.Header(s, cs))
160 return str(email.Header.Header(s, cs))
158 return s
161 return s
159
162
160 def addressencode(ui, address, charsets=None, display=False):
163 def addressencode(ui, address, charsets=None, display=False):
161 '''Turns address into RFC-2047 compliant header.'''
164 '''Turns address into RFC-2047 compliant header.'''
162 if display or not address:
165 if display or not address:
163 return address or ''
166 return address or ''
164 name, addr = email.Utils.parseaddr(address)
167 name, addr = email.Utils.parseaddr(address)
165 name = headencode(ui, name, charsets)
168 name = headencode(ui, name, charsets)
166 try:
169 try:
167 acc, dom = addr.split('@')
170 acc, dom = addr.split('@')
168 acc = acc.encode('ascii')
171 acc = acc.encode('ascii')
169 dom = dom.encode('idna')
172 dom = dom.encode('idna')
170 addr = '%s@%s' % (acc, dom)
173 addr = '%s@%s' % (acc, dom)
171 except UnicodeDecodeError:
174 except UnicodeDecodeError:
172 raise util.Abort(_('invalid email address: %s') % addr)
175 raise util.Abort(_('invalid email address: %s') % addr)
173 except ValueError:
176 except ValueError:
174 try:
177 try:
175 # too strict?
178 # too strict?
176 addr = addr.encode('ascii')
179 addr = addr.encode('ascii')
177 except UnicodeDecodeError:
180 except UnicodeDecodeError:
178 raise util.Abort(_('invalid local address: %s') % addr)
181 raise util.Abort(_('invalid local address: %s') % addr)
179 return email.Utils.formataddr((name, addr))
182 return email.Utils.formataddr((name, addr))
180
183
181 def mimeencode(ui, s, charsets=None, display=False):
184 def mimeencode(ui, s, charsets=None, display=False):
182 '''creates mime text object, encodes it if needed, and sets
185 '''creates mime text object, encodes it if needed, and sets
183 charset and transfer-encoding accordingly.'''
186 charset and transfer-encoding accordingly.'''
184 cs = 'us-ascii'
187 cs = 'us-ascii'
185 if not display:
188 if not display:
186 s, cs = _encode(ui, s, charsets)
189 s, cs = _encode(ui, s, charsets)
187 return email.MIMEText.MIMEText(s, 'plain', cs)
190 return email.MIMEText.MIMEText(s, 'plain', cs)
General Comments 0
You need to be logged in to leave comments. Login now