mail: Add 'snumber' template parameter equivalent to stripped 'number'
[stgit/kha.git] / stgit / commands / mail.py
blob7f972a41f3924995e35fada932a3e52a6ee9eef1
1 __copyright__ = """
2 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
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.
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.
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 """
18 import sys, os, re, time, datetime, socket, smtplib, getpass
19 import email, email.Utils, email.Header
20 from stgit.argparse import opt
21 from stgit.commands.common import *
22 from stgit.utils import *
23 from stgit.out import *
24 from stgit import argparse, stack, git, version, templates
25 from stgit.config import config
26 from stgit.run import Run
27 from stgit.lib import git as gitlib
29 help = 'Send a patch or series of patches by e-mail'
30 kind = 'patch'
31 usage = [' [options] [--] [<patch1>] [<patch2>] [<patch3>..<patch4>]']
32 description = r"""
33 Send a patch or a range of patches by e-mail using the SMTP server
34 specified by the 'stgit.smtpserver' configuration option, or the
35 '--smtp-server' command line option. This option can also be an
36 absolute path to 'sendmail' followed by command line arguments.
38 The From address and the e-mail format are generated from the template
39 file passed as argument to '--template' (defaulting to
40 '.git/patchmail.tmpl' or '~/.stgit/templates/patchmail.tmpl' or
41 '/usr/share/stgit/templates/patchmail.tmpl'). A patch can be sent as
42 attachment using the --attach option in which case the
43 'mailattch.tmpl' template will be used instead of 'patchmail.tmpl'.
45 The To/Cc/Bcc addresses can either be added to the template file or
46 passed via the corresponding command line options. They can be e-mail
47 addresses or aliases which are automatically expanded to the values
48 stored in the [mail "alias"] section of GIT configuration files.
50 A preamble e-mail can be sent using the '--cover' and/or
51 '--edit-cover' options. The first allows the user to specify a file to
52 be used as a template. The latter option will invoke the editor on the
53 specified file (defaulting to '.git/covermail.tmpl' or
54 '~/.stgit/templates/covermail.tmpl' or
55 '/usr/share/stgit/templates/covermail.tmpl').
57 All the subsequent e-mails appear as replies to the first e-mail sent
58 (either the preamble or the first patch). E-mails can be seen as
59 replies to a different e-mail by using the '--in-reply-to' option.
61 SMTP authentication is also possible with '--smtp-user' and
62 '--smtp-password' options, also available as configuration settings:
63 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
64 '--smtp-tls' option and 'smtptls' setting.
66 The following variables are accepted by both the preamble and the
67 patch e-mail templates:
69 %(diffstat)s - diff statistics
70 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
71 %(snumber)s - stripped version of '%(number)s'
72 %(patchnr)s - patch number
73 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
74 %(totalnr)s - total number of patches to be sent
75 %(version)s - ' version' string passed on the command line (or empty)
77 In addition to the common variables, the preamble e-mail template
78 accepts the following:
80 %(shortlog)s - first line of each patch description, listed by author
82 In addition to the common variables, the patch e-mail template accepts
83 the following:
85 %(authdate)s - patch creation date
86 %(authemail)s - author's email
87 %(authname)s - author's name
88 %(commemail)s - committer's e-mail
89 %(commname)s - committer's name
90 %(diff)s - unified diff of the patch
91 %(fromauth)s - 'From: author\n\n' if different from sender
92 %(longdescr)s - the rest of the patch description, after the first line
93 %(patch)s - patch name
94 %(prefix)s - 'prefix ' string passed on the command line
95 %(shortdescr)s - the first line of the patch description"""
97 args = [argparse.patch_range(argparse.applied_patches,
98 argparse.unapplied_patches,
99 argparse.hidden_patches)]
100 options = [
101 opt('-a', '--all', action = 'store_true',
102 short = 'E-mail all the applied patches'),
103 opt('--to', action = 'append',
104 short = 'Add TO to the To: list'),
105 opt('--cc', action = 'append',
106 short = 'Add CC to the Cc: list'),
107 opt('--bcc', action = 'append',
108 short = 'Add BCC to the Bcc: list'),
109 opt('--auto', action = 'store_true',
110 short = 'Automatically cc the patch signers'),
111 opt('--no-thread', action = 'store_true',
112 short = 'Do not send subsequent messages as replies'),
113 opt('--unrelated', action = 'store_true',
114 short = 'Send patches without sequence numbering'),
115 opt('--attach', action = 'store_true',
116 short = 'Send a patch as attachment'),
117 opt('-v', '--version', metavar = 'VERSION',
118 short = 'Add VERSION to the [PATCH ...] prefix'),
119 opt('--prefix', metavar = 'PREFIX',
120 short = 'Add PREFIX to the [... PATCH ...] prefix'),
121 opt('-t', '--template', metavar = 'FILE',
122 short = 'Use FILE as the message template'),
123 opt('-c', '--cover', metavar = 'FILE',
124 short = 'Send FILE as the cover message'),
125 opt('-e', '--edit-cover', action = 'store_true',
126 short = 'Edit the cover message before sending'),
127 opt('-E', '--edit-patches', action = 'store_true',
128 short = 'Edit each patch before sending'),
129 opt('-s', '--sleep', type = 'int', metavar = 'SECONDS',
130 short = 'Sleep for SECONDS between e-mails sending'),
131 opt('--in-reply-to', metavar = 'REFID',
132 short = 'Use REFID as the reference id'),
133 opt('--smtp-server', metavar = 'HOST[:PORT] or "/path/to/sendmail -t -i"',
134 short = 'SMTP server or command to use for sending mail'),
135 opt('-u', '--smtp-user', metavar = 'USER',
136 short = 'Username for SMTP authentication'),
137 opt('-p', '--smtp-password', metavar = 'PASSWORD',
138 short = 'Password for SMTP authentication'),
139 opt('-T', '--smtp-tls', action = 'store_true',
140 short = 'Use SMTP with TLS encryption'),
141 opt('-b', '--branch', args = [argparse.stg_branches],
142 short = 'Use BRANCH instead of the default branch'),
143 opt('-m', '--mbox', action = 'store_true',
144 short = 'Generate an mbox file instead of sending'),
145 opt('--git', action = 'store_true',
146 short = 'Use git send-email (EXPERIMENTAL)')
147 ] + argparse.diff_opts_option()
149 directory = DirectoryHasRepository(log = False)
151 def __get_sender():
152 """Return the 'authname <authemail>' string as read from the
153 configuration file
155 sender=config.get('stgit.sender')
156 if not sender:
157 try:
158 sender = str(git.user())
159 except git.GitException:
160 try:
161 sender = str(git.author())
162 except git.GitException:
163 pass
164 if not sender:
165 raise CmdException, ('Unknown sender name and e-mail; you should'
166 ' for example set git config user.name and'
167 ' user.email')
168 sender = email.Utils.parseaddr(sender)
170 return email.Utils.formataddr(address_or_alias(sender))
172 def __addr_list(msg, header):
173 return [addr for name, addr in
174 email.Utils.getaddresses(msg.get_all(header, []))]
176 def __parse_addresses(msg):
177 """Return a two elements tuple: (from, [to])
179 from_addr_list = __addr_list(msg, 'From')
180 if len(from_addr_list) == 0:
181 raise CmdException, 'No "From" address'
183 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
184 + __addr_list(msg, 'Bcc')
185 if len(to_addr_list) == 0:
186 raise CmdException, 'No "To/Cc/Bcc" addresses'
188 return (from_addr_list[0], set(to_addr_list))
190 def __send_message_sendmail(sendmail, msg):
191 """Send the message using the sendmail command.
193 cmd = sendmail.split()
194 Run(*cmd).raw_input(msg).discard_output()
196 __smtp_credentials = None
198 def __set_smtp_credentials(options):
199 """Set the (smtpuser, smtppassword, smtpusetls) credentials if the method
200 of sending is SMTP.
202 global __smtp_credentials
204 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
205 if options.mbox or options.git or smtpserver.startswith('/'):
206 return
208 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
209 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
210 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
212 if (smtppassword and not smtpuser):
213 raise CmdException('SMTP password supplied, username needed')
214 if (smtpusetls and not smtpuser):
215 raise CmdException('SMTP over TLS requested, username needed')
216 if (smtpuser and not smtppassword):
217 smtppassword = getpass.getpass("Please enter SMTP password: ")
219 __smtp_credentials = (smtpuser, smtppassword, smtpusetls)
221 def __send_message_smtp(smtpserver, from_addr, to_addr_list, msg, options):
222 """Send the message using the given SMTP server
224 smtpuser, smtppassword, smtpusetls = __smtp_credentials
226 try:
227 s = smtplib.SMTP(smtpserver)
228 except Exception, err:
229 raise CmdException, str(err)
231 s.set_debuglevel(0)
232 try:
233 if smtpuser and smtppassword:
234 s.ehlo()
235 if smtpusetls:
236 if not hasattr(socket, 'ssl'):
237 raise CmdException, "cannot use TLS - no SSL support in Python"
238 s.starttls()
239 s.ehlo()
240 s.login(smtpuser, smtppassword)
242 result = s.sendmail(from_addr, to_addr_list, msg)
243 if len(result):
244 print "mail server refused delivery for the following recipients: %s" % result
245 except Exception, err:
246 raise CmdException, str(err)
248 s.quit()
250 def __send_message_git(msg, options):
251 """Send the message using git send-email
253 from subprocess import call
254 from tempfile import mkstemp
256 cmd = ["git", "send-email", "--from=%s" % msg['From']]
257 cmd.append("--quiet")
258 cmd.append("--suppress-cc=self")
259 if not options.auto:
260 cmd.append("--suppress-cc=body")
261 if options.in_reply_to:
262 cmd.extend(["--in-reply-to", options.in_reply_to])
263 if options.no_thread:
264 cmd.append("--no-thread")
266 # We only support To/Cc/Bcc in git send-email for now.
267 for x in ['to', 'cc', 'bcc']:
268 if getattr(options, x):
269 cmd.extend('--%s=%s' % (x, a) for a in getattr(options, x))
271 (fd, path) = mkstemp()
272 os.write(fd, msg.as_string(options.mbox))
273 os.close(fd)
275 try:
276 try:
277 cmd.append(path)
278 call(cmd)
279 except Exception, err:
280 raise CmdException, str(err)
281 finally:
282 os.unlink(path)
284 def __send_message(type, tmpl, options, *args):
285 """Message sending dispatcher.
287 (build, outstr) = {'cover': (__build_cover, 'the cover message'),
288 'patch': (__build_message, 'patch "%s"' % args[0])}[type]
289 if type == 'patch':
290 (patch_nr, total_nr) = (args[1], args[2])
292 msg_id = email.Utils.make_msgid('stgit')
293 msg = build(tmpl, msg_id, options, *args)
295 msg_str = msg.as_string(options.mbox)
296 if options.mbox:
297 out.stdout_raw(msg_str + '\n')
298 return msg_id
300 if not options.git:
301 from_addr, to_addrs = __parse_addresses(msg)
302 out.start('Sending ' + outstr)
304 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
305 if options.git:
306 __send_message_git(msg, options)
307 elif smtpserver.startswith('/'):
308 # Use the sendmail tool
309 __send_message_sendmail(smtpserver, msg_str)
310 else:
311 # Use the SMTP server (we have host and port information)
312 __send_message_smtp(smtpserver, from_addr, to_addrs, msg_str, options)
314 # give recipients a chance of receiving related patches in correct order
315 if type == 'cover' or (type == 'patch' and patch_nr < total_nr):
316 sleep = options.sleep or config.getint('stgit.smtpdelay')
317 time.sleep(sleep)
318 if not options.git:
319 out.done()
320 return msg_id
322 def __update_header(msg, header, addr = '', ignore = ()):
323 def __addr_pairs(msg, header, extra):
324 pairs = email.Utils.getaddresses(msg.get_all(header, []) + extra)
325 # remove pairs without an address and resolve the aliases
326 return [address_or_alias(p) for p in pairs if p[1]]
328 addr_pairs = __addr_pairs(msg, header, [addr])
329 del msg[header]
330 # remove the duplicates and filter the addresses
331 addr_dict = dict((addr, email.Utils.formataddr((name, addr)))
332 for name, addr in addr_pairs if addr not in ignore)
333 if addr_dict:
334 msg[header] = ', '.join(addr_dict.itervalues())
335 return set(addr_dict.iterkeys())
337 def __build_address_headers(msg, options, extra_cc = []):
338 """Build the address headers and check existing headers in the
339 template.
341 to_addr = ''
342 cc_addr = ''
343 extra_cc_addr = ''
344 bcc_addr = ''
346 autobcc = config.get('stgit.autobcc') or ''
348 if options.to:
349 to_addr = ', '.join(options.to)
350 if options.cc:
351 cc_addr = ', '.join(options.cc)
352 if extra_cc:
353 extra_cc_addr = ', '.join(extra_cc)
354 if options.bcc:
355 bcc_addr = ', '.join(options.bcc + [autobcc])
356 elif autobcc:
357 bcc_addr = autobcc
359 # if an address is on a header, ignore it from the rest
360 to_set = __update_header(msg, 'To', to_addr)
361 cc_set = __update_header(msg, 'Cc', cc_addr, to_set)
362 bcc_set = __update_header(msg, 'Bcc', bcc_addr, to_set.union(cc_set))
364 # --auto generated addresses, don't include the sender
365 from_set = __update_header(msg, 'From')
366 __update_header(msg, 'Cc', extra_cc_addr,
367 to_set.union(bcc_set).union(from_set))
369 def __get_signers_list(msg):
370 """Return the address list generated from signed-off-by and
371 acked-by lines in the message.
373 addr_list = []
374 tags = '%s|%s|%s|%s|%s|%s|%s' % (
375 'signed-off-by',
376 'acked-by',
377 'cc',
378 'reviewed-by',
379 'reported-by',
380 'tested-by',
381 'reported-and-tested-by')
382 regex = '^(%s):\s+(.+)$' % tags
384 r = re.compile(regex, re.I)
385 for line in msg.split('\n'):
386 m = r.match(line)
387 if m:
388 addr_list.append(m.expand('\g<2>'))
390 return addr_list
392 def __build_extra_headers(msg, msg_id, ref_id = None):
393 """Build extra email headers and encoding
395 del msg['Date']
396 msg['Date'] = email.Utils.formatdate(localtime = True)
397 msg['Message-ID'] = msg_id
398 if ref_id:
399 # make sure the ref id has the angle brackets
400 ref_id = '<%s>' % ref_id.strip(' \t\n<>')
401 msg['In-Reply-To'] = ref_id
402 msg['References'] = ref_id
403 msg['User-Agent'] = 'StGit/%s' % version.version
405 # update other address headers
406 __update_header(msg, 'Reply-To')
407 __update_header(msg, 'Mail-Reply-To')
408 __update_header(msg, 'Mail-Followup-To')
411 def __encode_message(msg):
412 # 7 or 8 bit encoding
413 charset = email.Charset.Charset('utf-8')
414 charset.body_encoding = None
416 # encode headers
417 for header, value in msg.items():
418 words = []
419 for word in value.split(' '):
420 try:
421 uword = unicode(word, 'utf-8')
422 except UnicodeDecodeError:
423 # maybe we should try a different encoding or report
424 # the error. At the moment, we just ignore it
425 pass
426 words.append(email.Header.Header(uword).encode())
427 new_val = ' '.join(words)
428 msg.replace_header(header, new_val)
430 # replace the Subject string with a Header() object otherwise the long
431 # line folding is done using "\n\t" rather than "\n ", causing issues with
432 # some e-mail clients
433 subject = msg.get('subject', '')
434 msg.replace_header('subject',
435 email.Header.Header(subject, header_name = 'subject'))
437 # encode the body and set the MIME and encoding headers
438 if msg.is_multipart():
439 for p in msg.get_payload():
440 p.set_charset(charset)
441 else:
442 msg.set_charset(charset)
444 def __edit_message(msg):
445 fname = '.stgitmail.txt'
447 # create the initial file
448 f = file(fname, 'w')
449 f.write(msg)
450 f.close()
452 call_editor(fname)
454 # read the message back
455 f = file(fname)
456 msg = f.read()
457 f.close()
459 return msg
461 def __build_cover(tmpl, msg_id, options, patches):
462 """Build the cover message (series description) to be sent via SMTP
464 sender = __get_sender()
466 if options.version:
467 version_str = ' %s' % options.version
468 else:
469 version_str = ''
471 if options.prefix:
472 prefix_str = options.prefix + ' '
473 else:
474 confprefix = config.get('stgit.mail.prefix')
475 if confprefix:
476 prefix_str = confprefix + ' '
477 else:
478 prefix_str = ''
480 total_nr_str = str(len(patches))
481 patch_nr_str = '0'.zfill(len(total_nr_str))
482 if len(patches) > 1:
483 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
484 else:
485 number_str = ''
487 tmpl_dict = {'sender': sender,
488 # for backward template compatibility
489 'maintainer': sender,
490 # for backward template compatibility
491 'endofheaders': '',
492 # for backward template compatibility
493 'date': '',
494 'version': version_str,
495 'prefix': prefix_str,
496 'patchnr': patch_nr_str,
497 'totalnr': total_nr_str,
498 'number': number_str,
499 'snumber': number_str.strip(),
500 'shortlog': stack.shortlog(crt_series.get_patch(p)
501 for p in reversed(patches)),
502 'diffstat': gitlib.diffstat(git.diff(
503 rev1 = git_id(crt_series, '%s^' % patches[0]),
504 rev2 = git_id(crt_series, '%s' % patches[-1]),
505 diff_flags = options.diff_flags))}
507 try:
508 msg_string = tmpl % tmpl_dict
509 except KeyError, err:
510 raise CmdException, 'Unknown patch template variable: %s' \
511 % err
512 except TypeError:
513 raise CmdException, 'Only "%(name)s" variables are ' \
514 'supported in the patch template'
516 if options.edit_cover:
517 msg_string = __edit_message(msg_string)
519 # The Python email message
520 try:
521 msg = email.message_from_string(msg_string)
522 except Exception, ex:
523 raise CmdException, 'template parsing error: %s' % str(ex)
525 if not options.git:
526 __build_address_headers(msg, options)
527 __build_extra_headers(msg, msg_id, options.in_reply_to)
528 __encode_message(msg)
530 return msg
532 def __build_message(tmpl, msg_id, options, patch, patch_nr, total_nr, ref_id):
533 """Build the message to be sent via SMTP
535 p = crt_series.get_patch(patch)
537 if p.get_description():
538 descr = p.get_description().strip()
539 else:
540 # provide a place holder and force the edit message option on
541 descr = '<empty message>'
542 options.edit_patches = True
544 descr_lines = descr.split('\n')
545 short_descr = descr_lines[0].strip()
546 long_descr = '\n'.join(l.rstrip() for l in descr_lines[1:]).lstrip('\n')
548 authname = p.get_authname();
549 authemail = p.get_authemail();
550 commname = p.get_commname();
551 commemail = p.get_commemail();
553 sender = __get_sender()
555 fromauth = '%s <%s>' % (authname, authemail)
556 if fromauth != sender:
557 fromauth = 'From: %s\n\n' % fromauth
558 else:
559 fromauth = ''
561 if options.version:
562 version_str = ' %s' % options.version
563 else:
564 version_str = ''
566 if options.prefix:
567 prefix_str = options.prefix + ' '
568 else:
569 confprefix = config.get('stgit.mail.prefix')
570 if confprefix:
571 prefix_str = confprefix + ' '
572 else:
573 prefix_str = ''
575 total_nr_str = str(total_nr)
576 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
577 if not options.unrelated and total_nr > 1:
578 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
579 else:
580 number_str = ''
582 diff = git.diff(rev1 = git_id(crt_series, '%s^' % patch),
583 rev2 = git_id(crt_series, '%s' % patch),
584 diff_flags = options.diff_flags)
585 tmpl_dict = {'patch': patch,
586 'sender': sender,
587 # for backward template compatibility
588 'maintainer': sender,
589 'shortdescr': short_descr,
590 'longdescr': long_descr,
591 # for backward template compatibility
592 'endofheaders': '',
593 'diff': diff,
594 'diffstat': gitlib.diffstat(diff),
595 # for backward template compatibility
596 'date': '',
597 'version': version_str,
598 'prefix': prefix_str,
599 'patchnr': patch_nr_str,
600 'totalnr': total_nr_str,
601 'number': number_str,
602 'snumber': number_str.strip(),
603 'fromauth': fromauth,
604 'authname': authname,
605 'authemail': authemail,
606 'authdate': p.get_authdate(),
607 'commname': commname,
608 'commemail': commemail}
609 # change None to ''
610 for key in tmpl_dict:
611 if not tmpl_dict[key]:
612 tmpl_dict[key] = ''
614 try:
615 msg_string = tmpl % tmpl_dict
616 except KeyError, err:
617 raise CmdException, 'Unknown patch template variable: %s' \
618 % err
619 except TypeError:
620 raise CmdException, 'Only "%(name)s" variables are ' \
621 'supported in the patch template'
623 if options.edit_patches:
624 msg_string = __edit_message(msg_string)
626 # The Python email message
627 try:
628 msg = email.message_from_string(msg_string)
629 except Exception, ex:
630 raise CmdException, 'template parsing error: %s' % str(ex)
632 if options.auto:
633 extra_cc = __get_signers_list(descr)
634 else:
635 extra_cc = []
637 if not options.git:
638 __build_address_headers(msg, options, extra_cc)
639 __build_extra_headers(msg, msg_id, ref_id)
640 __encode_message(msg)
642 return msg
644 def func(parser, options, args):
645 """Send the patches by e-mail using the patchmail.tmpl file as
646 a template
648 applied = crt_series.get_applied()
650 if options.all:
651 patches = applied
652 elif len(args) >= 1:
653 unapplied = crt_series.get_unapplied()
654 patches = parse_patches(args, applied + unapplied, len(applied))
655 else:
656 raise CmdException, 'Incorrect options. Unknown patches to send'
658 # early test for sender identity
659 __get_sender()
661 out.start('Checking the validity of the patches')
662 for p in patches:
663 if crt_series.empty_patch(p):
664 raise CmdException, 'Cannot send empty patch "%s"' % p
665 out.done()
667 total_nr = len(patches)
668 if total_nr == 0:
669 raise CmdException, 'No patches to send'
671 if options.in_reply_to:
672 if options.no_thread or options.unrelated:
673 raise CmdException, \
674 '--in-reply-to option not allowed with --no-thread or --unrelated'
675 ref_id = options.in_reply_to
676 else:
677 ref_id = None
679 # get username/password if sending by SMTP
680 __set_smtp_credentials(options)
682 # send the cover message (if any)
683 if options.cover or options.edit_cover:
684 if options.unrelated:
685 raise CmdException, 'cover sending not allowed with --unrelated'
687 # find the template file
688 if options.cover:
689 tmpl = file(options.cover).read()
690 else:
691 tmpl = templates.get_template('covermail.tmpl')
692 if not tmpl:
693 raise CmdException, 'No cover message template file found'
695 msg_id = __send_message('cover', tmpl, options, patches)
697 # subsequent e-mails are seen as replies to the first one
698 if not options.no_thread:
699 ref_id = msg_id
701 # send the patches
702 if options.template:
703 tmpl = file(options.template).read()
704 else:
705 if options.attach:
706 tmpl = templates.get_template('mailattch.tmpl')
707 else:
708 tmpl = templates.get_template('patchmail.tmpl')
709 if not tmpl:
710 raise CmdException, 'No e-mail template file found'
712 for (p, n) in zip(patches, range(1, total_nr + 1)):
713 msg_id = __send_message('patch', tmpl, options, p, n, total_nr, ref_id)
715 # subsequent e-mails are seen as replies to the first one
716 if not options.no_thread and not options.unrelated and not ref_id:
717 ref_id = msg_id