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