Release 0.12.1
[stgit] / stgit / commands / mail.py
CommitLineData
b4bddc06
CM
1__copyright__ = """
2Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
3
4This program is free software; you can redistribute it and/or modify
5it under the terms of the GNU General Public License version 2 as
6published by the Free Software Foundation.
7
8This program is distributed in the hope that it will be useful,
9but WITHOUT ANY WARRANTY; without even the implied warranty of
10MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11GNU General Public License for more details.
12
13You should have received a copy of the GNU General Public License
14along with this program; if not, write to the Free Software
15Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16"""
17
61eed152
CM
18import sys, os, re, time, datetime, smtplib
19import email, email.Utils, email.Header
b4bddc06 20from optparse import OptionParser, make_option
b4bddc06
CM
21
22from stgit.commands.common import *
23from stgit.utils import *
1f3bb017 24from stgit import stack, git, version, templates
b4bddc06
CM
25from stgit.config import config
26
27
28help = 'send a patch or series of patches by e-mail'
6b1e0111 29usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
26aab5b0 30
6b1e0111
CM
31Send a patch or a range of patches by e-mail using the 'smtpserver'
32configuration option. The From address and the e-mail format are
33generated from the template file passed as argument to '--template'
34(defaulting to '.git/patchmail.tmpl' or
79df2f0d
CM
35'~/.stgit/templates/patchmail.tmpl' or
36'/usr/share/stgit/templates/patchmail.tmpl').
37
38The To/Cc/Bcc addresses can either be added to the template file or
39passed via the corresponding command line options. They can be e-mail
40addresses or aliases which are automatically expanded to the values
41stored in the [mail "alias"] section of GIT configuration files.
2bb96902 42
0ba13ee9
KH
43A preamble e-mail can be sent using the '--cover' and/or
44'--edit-cover' options. The first allows the user to specify a file to
45be used as a template. The latter option will invoke the editor on the
46specified file (defaulting to '.git/covermail.tmpl' or
94d18868
YD
47'~/.stgit/templates/covermail.tmpl' or
48'/usr/share/stgit/templates/covermail.tmpl').
e3e05587
CM
49
50All the subsequent e-mails appear as replies to the first e-mail sent
51(either the preamble or the first patch). E-mails can be seen as
52replies to a different e-mail by using the '--refid' option.
26aab5b0
CM
53
54SMTP authentication is also possible with '--smtp-user' and
55'--smtp-password' options, also available as configuration settings:
56'smtpuser' and 'smtppassword'.
57
e5bdb1fe 58The patch e-mail template accepts the following variables:
26aab5b0
CM
59
60 %(patch)s - patch name
901288c2 61 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
26aab5b0
CM
62 %(shortdescr)s - the first line of the patch description
63 %(longdescr)s - the rest of the patch description, after the first line
26aab5b0
CM
64 %(diff)s - unified diff of the patch
65 %(diffstat)s - diff statistics
d0d139a3 66 %(version)s - ' version' string passed on the command line (or empty)
d323b5da 67 %(prefix)s - 'prefix ' string passed on the command line
26aab5b0
CM
68 %(patchnr)s - patch number
69 %(totalnr)s - total number of patches to be sent
b8d258e5 70 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
901288c2 71 %(fromauth)s - 'From: author\\n\\n' if different from sender
26aab5b0
CM
72 %(authname)s - author's name
73 %(authemail)s - author's email
74 %(authdate)s - patch creation date
75 %(commname)s - committer's name
76 %(commemail)s - committer's e-mail
77
901288c2
CM
78For the preamble e-mail template, only the %(sender)s, %(version)s,
79%(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
b4bddc06 80
9a316368
CM
81options = [make_option('-a', '--all',
82 help = 'e-mail all the applied patches',
83 action = 'store_true'),
2bb96902 84 make_option('--to',
e83b3149
PO
85 help = 'add TO to the To: list',
86 action = 'append'),
2bb96902 87 make_option('--cc',
e83b3149
PO
88 help = 'add CC to the Cc: list',
89 action = 'append'),
2bb96902 90 make_option('--bcc',
e83b3149
PO
91 help = 'add BCC to the Bcc: list',
92 action = 'append'),
f8d1cf65
CM
93 make_option('--auto',
94 help = 'automatically cc the patch signers',
95 action = 'store_true'),
d1ed3a12
CM
96 make_option('--noreply',
97 help = 'do not send subsequent messages as replies',
98 action = 'store_true'),
d0d139a3
CM
99 make_option('-v', '--version', metavar = 'VERSION',
100 help = 'add VERSION to the [PATCH ...] prefix'),
d323b5da
RR
101 make_option('--prefix', metavar = 'PREFIX',
102 help = 'add PREFIX to the [... PATCH ...] prefix'),
9a316368
CM
103 make_option('-t', '--template', metavar = 'FILE',
104 help = 'use FILE as the message template'),
e3e05587
CM
105 make_option('-c', '--cover', metavar = 'FILE',
106 help = 'send FILE as the cover message'),
0ba13ee9 107 make_option('-e', '--edit-cover',
e3e05587
CM
108 help = 'edit the cover message before sending',
109 action = 'store_true'),
0ba13ee9
KH
110 make_option('-E', '--edit-patches',
111 help = 'edit each patch before sending',
112 action = 'store_true'),
b4bddc06
CM
113 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
114 help = 'sleep for SECONDS between e-mails sending'),
115 make_option('--refid',
d0d139a3 116 help = 'use REFID as the reference id'),
eb026d93
B
117 make_option('-u', '--smtp-user', metavar = 'USER',
118 help = 'username for SMTP authentication'),
119 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
2f7c8b0b
CM
120 help = 'username for SMTP authentication'),
121 make_option('-b', '--branch',
29f00589
CM
122 help = 'use BRANCH instead of the default one'),
123 make_option('-m', '--mbox',
124 help = 'generate an mbox file instead of sending',
125 action = 'store_true')]
b4bddc06
CM
126
127
901288c2 128def __get_sender():
dae0f0be
CM
129 """Return the 'authname <authemail>' string as read from the
130 configuration file
131 """
c73e63b7
YD
132 sender=config.get('stgit.sender')
133 if not sender:
9e3f506f
KH
134 try:
135 sender = str(git.user())
136 except git.GitException:
137 sender = str(git.author())
138
139 if not sender:
901288c2 140 raise CmdException, 'unknown sender details'
dae0f0be 141
79df2f0d 142 return address_or_alias(sender)
9e3f506f 143
d650d6ed 144def __parse_addresses(msg):
b4bddc06
CM
145 """Return a two elements tuple: (from, [to])
146 """
d650d6ed
CM
147 def __addr_list(msg, header):
148 return [name_addr[1] for name_addr in
149 email.Utils.getaddresses(msg.get_all(header, []))]
b4bddc06 150
d650d6ed 151 from_addr_list = __addr_list(msg, 'From')
24aadb3f 152 if len(from_addr_list) == 0:
b4bddc06 153 raise CmdException, 'No "From" address'
d650d6ed
CM
154
155 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
156 + __addr_list(msg, 'Bcc')
b4bddc06
CM
157 if len(to_addr_list) == 0:
158 raise CmdException, 'No "To/Cc/Bcc" addresses'
159
160 return (from_addr_list[0], to_addr_list)
161
eb026d93
B
162def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
163 smtpuser, smtppassword):
b4bddc06
CM
164 """Send the message using the given SMTP server
165 """
166 try:
167 s = smtplib.SMTP(smtpserver)
168 except Exception, err:
169 raise CmdException, str(err)
170
171 s.set_debuglevel(0)
172 try:
eb026d93
B
173 if smtpuser and smtppassword:
174 s.ehlo()
175 s.login(smtpuser, smtppassword)
176
b4bddc06
CM
177 s.sendmail(from_addr, to_addr_list, msg)
178 # give recipients a chance of receiving patches in the correct order
179 time.sleep(sleep)
180 except Exception, err:
181 raise CmdException, str(err)
182
183 s.quit()
184
61eed152 185def __build_address_headers(msg, options, extra_cc = []):
f8d1cf65
CM
186 """Build the address headers and check existing headers in the
187 template.
188 """
61eed152
CM
189 def __replace_header(header, addr):
190 if addr:
191 crt_addr = msg[header]
192 del msg[header]
f8d1cf65 193
61eed152 194 if crt_addr:
79df2f0d 195 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
61eed152 196 else:
79df2f0d 197 msg[header] = address_or_alias(addr)
f8d1cf65 198
f8d1cf65
CM
199 to_addr = ''
200 cc_addr = ''
201 bcc_addr = ''
202
c73e63b7 203 autobcc = config.get('stgit.autobcc') or ''
d884c4d8 204
e83b3149 205 if options.to:
61eed152 206 to_addr = ', '.join(options.to)
e83b3149 207 if options.cc:
61eed152 208 cc_addr = ', '.join(options.cc + extra_cc)
f8d1cf65 209 elif extra_cc:
61eed152 210 cc_addr = ', '.join(extra_cc)
e83b3149 211 if options.bcc:
61eed152 212 bcc_addr = ', '.join(options.bcc + [autobcc])
d884c4d8
CM
213 elif autobcc:
214 bcc_addr = autobcc
f8d1cf65 215
61eed152
CM
216 __replace_header('To', to_addr)
217 __replace_header('Cc', cc_addr)
218 __replace_header('Bcc', bcc_addr)
f8d1cf65
CM
219
220def __get_signers_list(msg):
221 """Return the address list generated from signed-off-by and
222 acked-by lines in the message.
223 """
224 addr_list = []
225
226 r = re.compile('^(signed-off-by|acked-by):\s+(.+)$', re.I)
227 for line in msg.split('\n'):
228 m = r.match(line)
229 if m:
230 addr_list.append(m.expand('\g<2>'))
231
232 return addr_list
e83b3149 233
61eed152
CM
234def __build_extra_headers(msg, msg_id, ref_id = None):
235 """Build extra email headers and encoding
19a56fa1 236 """
61eed152
CM
237 del msg['Date']
238 msg['Date'] = email.Utils.formatdate(localtime = True)
239 msg['Message-ID'] = msg_id
240 if ref_id:
241 msg['In-Reply-To'] = ref_id
242 msg['References'] = ref_id
243 msg['User-Agent'] = 'StGIT/%s' % version.version
244
245def __encode_message(msg):
246 # 7 or 8 bit encoding
247 charset = email.Charset.Charset('utf-8')
248 charset.body_encoding = None
249
250 # encode headers
251 for header, value in msg.items():
252 words = []
253 for word in value.split(' '):
254 try:
255 uword = unicode(word, 'utf-8')
256 except UnicodeDecodeError:
257 # maybe we should try a different encoding or report
258 # the error. At the moment, we just ignore it
259 pass
260 words.append(email.Header.Header(uword).encode())
261 new_val = ' '.join(words)
262 msg.replace_header(header, new_val)
263
264 # encode the body and set the MIME and encoding headers
265 msg.set_charset(charset)
19a56fa1 266
58c61f10 267def __edit_message(msg):
0ba13ee9
KH
268 fname = '.stgitmail.txt'
269
270 # create the initial file
271 f = file(fname, 'w')
272 f.write(msg)
273 f.close()
274
275 # the editor
c73e63b7
YD
276 editor = config.get('stgit.editor')
277 if editor:
278 pass
0ba13ee9
KH
279 elif 'EDITOR' in os.environ:
280 editor = os.environ['EDITOR']
281 else:
282 editor = 'vi'
283 editor += ' %s' % fname
284
285 print 'Invoking the editor: "%s"...' % editor,
286 sys.stdout.flush()
0aa8df2e
CM
287 err = os.system(editor)
288 if err:
289 raise CmdException, 'editor failed, exit code: %d' % err
290 print 'done'
0ba13ee9
KH
291
292 # read the message back
293 f = file(fname)
294 msg = f.read()
295 f.close()
296
297 return msg
298
e3e05587
CM
299def __build_cover(tmpl, total_nr, msg_id, options):
300 """Build the cover message (series description) to be sent via SMTP
b4bddc06 301 """
901288c2 302 sender = __get_sender()
dae0f0be 303
d0d139a3
CM
304 if options.version:
305 version_str = ' %s' % options.version
ed5de0cc
CM
306 else:
307 version_str = ''
d0d139a3 308
d323b5da
RR
309 if options.prefix:
310 prefix_str = options.prefix + ' '
311 else:
312 prefix_str = ''
313
b4bddc06 314 total_nr_str = str(total_nr)
b8d258e5
CM
315 patch_nr_str = '0'.zfill(len(total_nr_str))
316 if total_nr > 1:
317 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
318 else:
319 number_str = ''
b4bddc06 320
901288c2
CM
321 tmpl_dict = {'sender': sender,
322 # for backward template compatibility
323 'maintainer': sender,
61eed152
CM
324 # for backward template compatibility
325 'endofheaders': '',
326 # for backward template compatibility
327 'date': '',
d0d139a3 328 'version': version_str,
d323b5da 329 'prefix': prefix_str,
b8d258e5
CM
330 'patchnr': patch_nr_str,
331 'totalnr': total_nr_str,
332 'number': number_str}
b4bddc06
CM
333
334 try:
61eed152 335 msg_string = tmpl % tmpl_dict
b4bddc06
CM
336 except KeyError, err:
337 raise CmdException, 'Unknown patch template variable: %s' \
338 % err
339 except TypeError:
340 raise CmdException, 'Only "%(name)s" variables are ' \
341 'supported in the patch template'
342
58c61f10
CM
343 if options.edit_cover:
344 msg_string = __edit_message(msg_string)
345
61eed152
CM
346 # The Python email message
347 try:
348 msg = email.message_from_string(msg_string)
349 except Exception, ex:
350 raise CmdException, 'template parsing error: %s' % str(ex)
351
352 __build_address_headers(msg, options)
353 __build_extra_headers(msg, msg_id, options.refid)
354 __encode_message(msg)
355
d650d6ed 356 return msg
b4bddc06 357
2bb96902 358def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
b4bddc06
CM
359 """Build the message to be sent via SMTP
360 """
361 p = crt_series.get_patch(patch)
362
363 descr = p.get_description().strip()
364 descr_lines = descr.split('\n')
365
366 short_descr = descr_lines[0].rstrip()
61eed152 367 long_descr = '\n'.join(descr_lines[1:]).lstrip()
b4bddc06 368
1d1485c3
CM
369 authname = p.get_authname();
370 authemail = p.get_authemail();
371 commname = p.get_commname();
372 commemail = p.get_commemail();
373
901288c2 374 sender = __get_sender()
1d1485c3
CM
375
376 fromauth = '%s <%s>' % (authname, authemail)
901288c2 377 if fromauth != sender:
1d1485c3
CM
378 fromauth = 'From: %s\n\n' % fromauth
379 else:
380 fromauth = ''
dae0f0be 381
d0d139a3
CM
382 if options.version:
383 version_str = ' %s' % options.version
ed5de0cc
CM
384 else:
385 version_str = ''
d0d139a3 386
d323b5da
RR
387 if options.prefix:
388 prefix_str = options.prefix + ' '
389 else:
390 prefix_str = ''
391
b4bddc06
CM
392 total_nr_str = str(total_nr)
393 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
b8d258e5
CM
394 if total_nr > 1:
395 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
396 else:
397 number_str = ''
b4bddc06
CM
398
399 tmpl_dict = {'patch': patch,
901288c2
CM
400 'sender': sender,
401 # for backward template compatibility
402 'maintainer': sender,
b4bddc06
CM
403 'shortdescr': short_descr,
404 'longdescr': long_descr,
61eed152
CM
405 # for backward template compatibility
406 'endofheaders': '',