53cd239cb583505901ec476a23fa15d13ac0803c
[stgit] / stgit / commands / mail.py
1 __copyright__ = """
2 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License version 2 as
6 published by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License
14 along with this program; if not, write to the Free Software
15 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 """
17
18 import sys, os, re, time, datetime, socket, smtplib, getpass
19 import email, email.Utils, email.Header
20 from optparse import OptionParser, make_option
21
22 from stgit.commands.common import *
23 from stgit.utils import *
24 from stgit.out import *
25 from stgit import stack, git, version, templates
26 from stgit.config import config
27
28
29 help = 'send a patch or series of patches by e-mail'
30 usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
31
32 Send a patch or a range of patches by e-mail using the SMTP server
33 specified by the 'stgit.smtpserver' configuration option, or the
34 '--smtp-server' command line option. The From address and the e-mail
35 format are generated from the template file passed as argument to
36 '--template' (defaulting to '.git/patchmail.tmpl' or
37 '~/.stgit/templates/patchmail.tmpl' or
38 '/usr/share/stgit/templates/patchmail.tmpl'). A patch can be sent as
39 attachment using the --attach option in which case the 'mailattch.tmpl'
40 template will be used instead of 'patchmail.tmpl'.
41
42 The To/Cc/Bcc addresses can either be added to the template file or
43 passed via the corresponding command line options. They can be e-mail
44 addresses or aliases which are automatically expanded to the values
45 stored in the [mail "alias"] section of GIT configuration files.
46
47 A preamble e-mail can be sent using the '--cover' and/or
48 '--edit-cover' options. The first allows the user to specify a file to
49 be used as a template. The latter option will invoke the editor on the
50 specified file (defaulting to '.git/covermail.tmpl' or
51 '~/.stgit/templates/covermail.tmpl' or
52 '/usr/share/stgit/templates/covermail.tmpl').
53
54 All the subsequent e-mails appear as replies to the first e-mail sent
55 (either the preamble or the first patch). E-mails can be seen as
56 replies to a different e-mail by using the '--refid' option.
57
58 SMTP authentication is also possible with '--smtp-user' and
59 '--smtp-password' options, also available as configuration settings:
60 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
61 '--smtp-tls' option and 'smtptls' setting.
62
63 The following variables are accepted by both the preamble and the
64 patch e-mail templates:
65
66 %(diffstat)s - diff statistics
67 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
68 %(patchnr)s - patch number
69 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
70 %(totalnr)s - total number of patches to be sent
71 %(version)s - ' version' string passed on the command line (or empty)
72
73 In addition to the common variables, the preamble e-mail template
74 accepts the following:
75
76 %(shortlog)s - first line of each patch description, listed by author
77
78 In addition to the common variables, the patch e-mail template accepts
79 the following:
80
81 %(authdate)s - patch creation date
82 %(authemail)s - author's email
83 %(authname)s - author's name
84 %(commemail)s - committer's e-mail
85 %(commname)s - committer's name
86 %(diff)s - unified diff of the patch
87 %(fromauth)s - 'From: author\\n\\n' if different from sender
88 %(longdescr)s - the rest of the patch description, after the first line
89 %(patch)s - patch name
90 %(prefix)s - 'prefix ' string passed on the command line
91 %(shortdescr)s - the first line of the patch description"""
92
93 directory = DirectoryHasRepository()
94 options = [make_option('-a', '--all',
95 help = 'e-mail all the applied patches',
96 action = 'store_true'),
97 make_option('--to',
98 help = 'add TO to the To: list',
99 action = 'append'),
100 make_option('--cc',
101 help = 'add CC to the Cc: list',
102 action = 'append'),
103 make_option('--bcc',
104 help = 'add BCC to the Bcc: list',
105 action = 'append'),
106 make_option('--auto',
107 help = 'automatically cc the patch signers',
108 action = 'store_true'),
109 make_option('--noreply',
110 help = 'do not send subsequent messages as replies',
111 action = 'store_true'),
112 make_option('--unrelated',
113 help = 'send patches without sequence numbering',
114 action = 'store_true'),
115 make_option('--attach',
116 help = 'send a patch as attachment',
117 action = 'store_true'),
118 make_option('-v', '--version', metavar = 'VERSION',
119 help = 'add VERSION to the [PATCH ...] prefix'),
120 make_option('--prefix', metavar = 'PREFIX',
121 help = 'add PREFIX to the [... PATCH ...] prefix'),
122 make_option('-t', '--template', metavar = 'FILE',
123 help = 'use FILE as the message template'),
124 make_option('-c', '--cover', metavar = 'FILE',
125 help = 'send FILE as the cover message'),
126 make_option('-e', '--edit-cover',
127 help = 'edit the cover message before sending',
128 action = 'store_true'),
129 make_option('-E', '--edit-patches',
130 help = 'edit each patch before sending',
131 action = 'store_true'),
132 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
133 help = 'sleep for SECONDS between e-mails sending'),
134 make_option('--refid',
135 help = 'use REFID as the reference id'),
136 make_option('--smtp-server', metavar = 'HOST[:PORT]',
137 help = 'SMTP server to use for sending mail'),
138 make_option('-u', '--smtp-user', metavar = 'USER',
139 help = 'username for SMTP authentication'),
140 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
141 help = 'username for SMTP authentication'),
142 make_option('-T', '--smtp-tls',
143 help = 'use SMTP with TLS encryption',
144 action = 'store_true'),
145 make_option('-b', '--branch',
146 help = 'use BRANCH instead of the default one'),
147 make_option('-O', '--diff-opts',
148 help = 'options to pass to git-diff'),
149 make_option('-m', '--mbox',
150 help = 'generate an mbox file instead of sending',
151 action = 'store_true')]
152
153
154 def __get_sender():
155 """Return the 'authname <authemail>' string as read from the
156 configuration file
157 """
158 sender=config.get('stgit.sender')
159 if not sender:
160 try:
161 sender = str(git.user())
162 except git.GitException:
163 sender = str(git.author())
164
165 if not sender:
166 raise CmdException, 'unknown sender details'
167
168 return address_or_alias(sender)
169
170 def __parse_addresses(msg):
171 """Return a two elements tuple: (from, [to])
172 """
173 def __addr_list(msg, header):
174 return [name_addr[1] for name_addr in
175 email.Utils.getaddresses(msg.get_all(header, []))]
176
177 from_addr_list = __addr_list(msg, 'From')
178 if len(from_addr_list) == 0:
179 raise CmdException, 'No "From" address'
180
181 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
182 + __addr_list(msg, 'Bcc')
183 if len(to_addr_list) == 0:
184 raise CmdException, 'No "To/Cc/Bcc" addresses'
185
186 return (from_addr_list[0], to_addr_list)
187
188 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
189 smtpuser, smtppassword, use_tls):
190 """Send the message using the given SMTP server
191 """
192 try:
193 s = smtplib.SMTP(smtpserver)
194 except Exception, err:
195 raise CmdException, str(err)
196
197 s.set_debuglevel(0)
198 try:
199 if smtpuser and smtppassword:
200 s.ehlo()
201 if use_tls:
202 if not hasattr(socket, 'ssl'):
203 raise CmdException, "cannot use TLS - no SSL support in Python"
204 s.starttls()
205 s.ehlo()
206 s.login(smtpuser, smtppassword)
207
208 result = s.sendmail(from_addr, to_addr_list, msg)
209 if len(result):
210 print "mail server refused delivery for the following recipients: %s" % result
211 # give recipients a chance of receiving patches in the correct order
212 time.sleep(sleep)
213 except Exception, err:
214 raise CmdException, str(err)
215
216 s.quit()
217
218 def __build_address_headers(msg, options, extra_cc = []):
219 """Build the address headers and check existing headers in the
220 template.
221 """
222 def __replace_header(header, addr):
223 if addr:
224 crt_addr = msg[header]
225 del msg[header]
226
227 if crt_addr:
228 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
229 else:
230 msg[header] = address_or_alias(addr)
231
232 to_addr = ''
233 cc_addr = ''
234 bcc_addr = ''
235
236 autobcc = config.get('stgit.autobcc') or ''
237
238 if options.to:
239 to_addr = ', '.join(options.to)
240 if options.cc:
241 cc_addr = ', '.join(options.cc + extra_cc)
242 cc_addr = ', '.join(options.cc + extra_cc)
243 elif extra_cc:
244 cc_addr = ', '.join(extra_cc)
245 if options.bcc:
246 bcc_addr = ', '.join(options.bcc + [autobcc])
247 elif autobcc:
248 bcc_addr = autobcc
249
250 __replace_header('To', to_addr)
251 __replace_header('Cc', cc_addr)
252 __replace_header('Bcc', bcc_addr)
253
254 def __get_signers_list(msg):
255 """Return the address list generated from signed-off-by and
256 acked-by lines in the message.
257 """
258 addr_list = []
259
260 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
261 for line in msg.split('\n'):
262 m = r.match(line)
263 if m:
264 addr_list.append(m.expand('\g<2>'))
265
266 return addr_list
267
268 def __build_extra_headers(msg, msg_id, ref_id = None):
269 """Build extra email headers and encoding
270 """
271 del msg['Date']
272 msg['Date'] = email.Utils.formatdate(localtime = True)
273 msg['Message-ID'] = msg_id
274 if ref_id:
275 msg['In-Reply-To'] = ref_id
276 msg['References'] = ref_id
277 msg['User-Agent'] = 'StGIT/%s' % version.version
278
279 def __encode_message(msg):
280 # 7 or 8 bit encoding
281 charset = email.Charset.Charset('utf-8')
282 charset.body_encoding = None
283
284 # encode headers
285 for header, value in msg.items():
286 words = []
287 for word in value.split(' '):
288 try:
289 uword = unicode(word, 'utf-8')
290 except UnicodeDecodeError:
291 # maybe we should try a different encoding or report
292 # the error. At the moment, we just ignore it
293 pass
294 words.append(email.Header.Header(uword).encode())
295 new_val = ' '.join(words)
296 msg.replace_header(header, new_val)
297
298 # encode the body and set the MIME and encoding headers
299 if msg.is_multipart():
300 for p in msg.get_payload():
301 p.set_charset(charset)
302 else:
303 msg.set_charset(charset)
304
305 def __edit_message(msg):
306 fname = '.stgitmail.txt'
307
308 # create the initial file
309 f = file(fname, 'w')
310 f.write(msg)
311 f.close()
312
313 call_editor(fname)
314
315 # read the message back
316 f = file(fname)
317 msg = f.read()
318 f.close()
319
320 return msg
321
322 def __build_cover(tmpl, patches, msg_id, options):
323 """Build the cover message (series description) to be sent via SMTP
324 """
325 sender = __get_sender()
326
327 if options.version:
328 version_str = ' %s' % options.version
329 else:
330 version_str = ''
331
332 if options.prefix:
333 prefix_str = options.prefix + ' '
334 else:
335 confprefix = config.get('stgit.mail.prefix')
336 if confprefix:
337 prefix_str = confprefix + ' '
338 else:
339 prefix_str = ''
340
341 total_nr_str = str(len(patches))
342 patch_nr_str = '0'.zfill(len(total_nr_str))
343 if len(patches) > 1:
344 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
345 else:
346 number_str = ''
347
348 tmpl_dict = {'sender': sender,
349 # for backward template compatibility
350 'maintainer': sender,
351 # for backward template compatibility
352 'endofheaders': '',
353 # for backward template compatibility
354 'date': '',
355 'version': version_str,
356 'prefix': prefix_str,
357 'patchnr': patch_nr_str,
358 'totalnr': total_nr_str,
359 'number': number_str,
360 'shortlog': stack.shortlog(crt_series.get_patch(p)
361 for p in patches),
362 'diffstat': git.diffstat(
363 rev1 = git_id(crt_series, '%s//bottom' % patches[0]),
364 rev2 = git_id(crt_series, '%s//top' % patches[-1]))}
365
366 try:
367 msg_string = tmpl % tmpl_dict
368 except KeyError, err:
369 raise CmdException, 'Unknown patch template variable: %s' \
370 % err
371 except TypeError:
372 raise CmdException, 'Only "%(name)s" variables are ' \
373 'supported in the patch template'
374
375 if options.edit_cover:
376 msg_string = __edit_message(msg_string)
377
378 # The Python email message
379 try:
380 msg = email.message_from_string(msg_string)
381 except Exception, ex:
382 raise CmdException, 'template parsing error: %s' % str(ex)
383
384 __build_address_headers(msg, options)
385 __build_extra_headers(msg, msg_id, options.refid)
386 __encode_message(msg)
387
388 return msg
389
390 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
391 """Build the message to be sent via SMTP
392 """
393 p = crt_series.get_patch(patch)
394
395 descr = p.get_description().strip()
396 descr_lines = descr.split('\n')
397
398 short_descr = descr_lines[0].rstrip()
399 long_descr = '\n'.join(descr_lines[1:]).lstrip()
400
401 authname = p.get_authname();
402 authemail = p.get_authemail();
403 commname = p.get_commname();
404 commemail = p.get_commemail();
405
406 sender = __get_sender()
407
408 fromauth = '%s <%s>' % (authname, authemail)
409 if fromauth != sender:
410 fromauth = 'From: %s\n\n' % fromauth
411 else:
412 fromauth = ''
413
414 if options.version:
415 version_str = ' %s' % options.version
416 else:
417 version_str = ''
418
419 if options.prefix:
420 prefix_str = options.prefix + ' '
421 else:
422 confprefix = config.get('stgit.mail.prefix')
423 if confprefix:
424 prefix_str = confprefix + ' '
425 else:
426 prefix_str = ''
427
428 if options.diff_opts:
429 diff_flags = options.diff_opts.split()
430 else:
431 diff_flags = []
432
433 total_nr_str = str(total_nr)
434 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
435 if not options.unrelated and total_nr > 1:
436 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
437 else:
438 number_str = ''
439
440 tmpl_dict = {'patch': patch,
441 'sender': sender,
442 # for backward template compatibility
443 'maintainer': sender,
444 'shortdescr': short_descr,
445 'longdescr': long_descr,
446 # for backward template compatibility
447 'endofheaders': '',
448 'diff': git.diff(
449 rev1 = git_id(crt_series, '%s//bottom' % patch),
450 rev2 = git_id(crt_series, '%s//top' % patch),
451 diff_flags = diff_flags),
452 'diffstat': git.diffstat(
453 rev1 = git_id(crt_series, '%s//bottom'%patch),
454 rev2 = git_id(crt_series, '%s//top' % patch)),
455 # for backward template compatibility
456 'date': '',
457 'version': version_str,
458 'prefix': prefix_str,
459 'patchnr': patch_nr_str,
460 'totalnr': total_nr_str,
461 'number': number_str,
462 'fromauth': fromauth,
463 'authname': authname,
464 'authemail': authemail,
465 'authdate': p.get_authdate(),
466 'commname': commname,
467 'commemail': commemail}
468 # change None to ''
469 for key in tmpl_dict:
470 if not tmpl_dict[key]:
471 tmpl_dict[key] = ''
472
473 try:
474 msg_string = tmpl % tmpl_dict
475 except KeyError, err:
476 raise CmdException, 'Unknown patch template variable: %s' \
477 % err
478 except TypeError:
479 raise CmdException, 'Only "%(name)s" variables are ' \
480 'supported in the patch template'
481
482 if options.edit_patches:
483 msg_string = __edit_message(msg_string)
484
485 # The Python email message
486 try:
487 msg = email.message_from_string(msg_string)
488 except Exception, ex:
489 raise CmdException, 'template parsing error: %s' % str(ex)
490
491 if options.auto:
492 extra_cc = __get_signers_list(descr)
493 else:
494 extra_cc = []
495
496 __build_address_headers(msg, options, extra_cc)
497 __build_extra_headers(msg, msg_id, ref_id)
498 __encode_message(msg)
499
500 return msg
501
502 def func(parser, options, args):
503 """Send the patches by e-mail using the patchmail.tmpl file as
504 a template
505 """
506 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
507
508 applied = crt_series.get_applied()
509
510 if options.all:
511 patches = applied
512 elif len(args) >= 1:
513 unapplied = crt_series.get_unapplied()
514 patches = parse_patches(args, applied + unapplied, len(applied))
515 else:
516 raise CmdException, 'Incorrect options. Unknown patches to send'
517
518 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
519 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
520 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
521
522 if (smtppassword and not smtpuser):
523 raise CmdException, 'SMTP password supplied, username needed'
524 if (smtpusetls and not smtpuser):
525 raise CmdException, 'SMTP over TLS requested, username needed'
526 if (smtpuser and not smtppassword):
527 smtppassword = getpass.getpass("Please enter SMTP password: ")
528
529 total_nr = len(patches)
530 if total_nr == 0:
531 raise CmdException, 'No patches to send'
532
533 if options.refid:
534 if options.noreply or options.unrelated:
535 raise CmdException, \
536 '--refid option not allowed with --noreply or --unrelated'
537 ref_id = options.refid
538 else:
539 ref_id = None
540
541 sleep = options.sleep or config.getint('stgit.smtpdelay')
542
543 # send the cover message (if any)
544 if options.cover or options.edit_cover:
545 if options.unrelated:
546 raise CmdException, 'cover sending not allowed with --unrelated'
547
548 # find the template file
549 if options.cover:
550 tmpl = file(options.cover).read()
551 else:
552 tmpl = templates.get_template('covermail.tmpl')
553 if not tmpl:
554 raise CmdException, 'No cover message template file found'
555
556 msg_id = email.Utils.make_msgid('stgit')
557 msg = __build_cover(tmpl, patches, msg_id, options)
558 from_addr, to_addr_list = __parse_addresses(msg)
559
560 msg_string = msg.as_string(options.mbox)
561
562 # subsequent e-mails are seen as replies to the first one
563 if not options.noreply:
564 ref_id = msg_id
565
566 if options.mbox:
567 out.stdout_raw(msg_string + '\n')
568 else:
569 out.start('Sending the cover message')
570 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
571 sleep, smtpuser, smtppassword, smtpusetls)
572 out.done()
573
574 # send the patches
575 if options.template:
576 tmpl = file(options.template).read()
577 else:
578 if options.attach:
579 tmpl = templates.get_template('mailattch.tmpl')
580 else:
581 tmpl = templates.get_template('patchmail.tmpl')
582 if not tmpl:
583 raise CmdException, 'No e-mail template file found'
584
585 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
586 msg_id = email.Utils.make_msgid('stgit')
587 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
588 options)
589 from_addr, to_addr_list = __parse_addresses(msg)
590
591 msg_string = msg.as_string(options.mbox)
592
593 # subsequent e-mails are seen as replies to the first one
594 if not options.noreply and not options.unrelated and not ref_id:
595 ref_id = msg_id
596
597 if options.mbox:
598 out.stdout_raw(msg_string + '\n')
599 else:
600 out.start('Sending patch "%s"' % p)
601 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
602 sleep, smtpuser, smtppassword, smtpusetls)
603 out.done()