stg mail: factor out __update_header
[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
6cf5ec9b 18import sys, os, re, time, datetime, socket, smtplib, getpass
61eed152 19import email, email.Utils, email.Header
575bbdae 20from stgit.argparse import opt
b4bddc06
CM
21from stgit.commands.common import *
22from stgit.utils import *
5e888f30 23from stgit.out import *
20a52e06 24from stgit import argparse, stack, git, version, templates
b4bddc06 25from stgit.config import config
a0fe60a2 26from stgit.run import Run
ef954fe6 27from stgit.lib import git as gitlib
b4bddc06 28
575bbdae 29help = 'Send a patch or series of patches by e-mail'
33ff9cdd 30kind = 'patch'
54239abf 31usage = [' [options] [--] [<patch1>] [<patch2>] [<patch3>..<patch4>]']
575bbdae 32description = r"""
cec913c4
KH
33Send a patch or a range of patches by e-mail using the SMTP server
34specified by the 'stgit.smtpserver' configuration option, or the
a0fe60a2
CM
35'--smtp-server' command line option. This option can also be an
36absolute path to 'sendmail' followed by command line arguments.
37
38The From address and the e-mail format are generated from the template
39file passed as argument to '--template' (defaulting to
40'.git/patchmail.tmpl' or '~/.stgit/templates/patchmail.tmpl' or
e5c32acf 41'/usr/share/stgit/templates/patchmail.tmpl'). A patch can be sent as
a0fe60a2
CM
42attachment using the --attach option in which case the
43'mailattch.tmpl' template will be used instead of 'patchmail.tmpl'.
79df2f0d
CM
44
45The To/Cc/Bcc addresses can either be added to the template file or
46passed via the corresponding command line options. They can be e-mail
47addresses or aliases which are automatically expanded to the values
48stored in the [mail "alias"] section of GIT configuration files.
2bb96902 49
0ba13ee9
KH
50A 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
52be used as a template. The latter option will invoke the editor on the
53specified file (defaulting to '.git/covermail.tmpl' or
94d18868
YD
54'~/.stgit/templates/covermail.tmpl' or
55'/usr/share/stgit/templates/covermail.tmpl').
e3e05587
CM
56
57All 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
59replies to a different e-mail by using the '--refid' option.
26aab5b0
CM
60
61SMTP authentication is also possible with '--smtp-user' and
62'--smtp-password' options, also available as configuration settings:
fc44c2ca
PR
63'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
64'--smtp-tls' option and 'smtptls' setting.
26aab5b0 65
27827959
KH
66The following variables are accepted by both the preamble and the
67patch e-mail templates:
26aab5b0 68
26aab5b0 69 %(diffstat)s - diff statistics
27827959 70 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
26aab5b0 71 %(patchnr)s - patch number
27827959 72 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
26aab5b0 73 %(totalnr)s - total number of patches to be sent
27827959
KH
74 %(version)s - ' version' string passed on the command line (or empty)
75
76In addition to the common variables, the preamble e-mail template
77accepts the following:
78
79 %(shortlog)s - first line of each patch description, listed by author
80
81In addition to the common variables, the patch e-mail template accepts
82the following:
83
26aab5b0 84 %(authdate)s - patch creation date
27827959
KH
85 %(authemail)s - author's email
86 %(authname)s - author's name
26aab5b0 87 %(commemail)s - committer's e-mail
27827959
KH
88 %(commname)s - committer's name
89 %(diff)s - unified diff of the patch
77eeb7f4 90 %(fromauth)s - 'From: author\n\n' if different from sender
27827959
KH
91 %(longdescr)s - the rest of the patch description, after the first line
92 %(patch)s - patch name
93 %(prefix)s - 'prefix ' string passed on the command line
94 %(shortdescr)s - the first line of the patch description"""
b4bddc06 95
6c8a90e1
KH
96args = [argparse.patch_range(argparse.applied_patches,
97 argparse.unapplied_patches,
98 argparse.hidden_patches)]
575bbdae
KH
99options = [
100 opt('-a', '--all', action = 'store_true',
101 short = 'E-mail all the applied patches'),
102 opt('--to', action = 'append',
103 short = 'Add TO to the To: list'),
104 opt('--cc', action = 'append',
105 short = 'Add CC to the Cc: list'),
106 opt('--bcc', action = 'append',
107 short = 'Add BCC to the Bcc: list'),
108 opt('--auto', action = 'store_true',
109 short = 'Automatically cc the patch signers'),
110 opt('--noreply', action = 'store_true',
111 short = 'Do not send subsequent messages as replies'),
112 opt('--unrelated', action = 'store_true',
113 short = 'Send patches without sequence numbering'),
114 opt('--attach', action = 'store_true',
115 short = 'Send a patch as attachment'),
116 opt('-v', '--version', metavar = 'VERSION',
117 short = 'Add VERSION to the [PATCH ...] prefix'),
118 opt('--prefix', metavar = 'PREFIX',
119 short = 'Add PREFIX to the [... PATCH ...] prefix'),
120 opt('-t', '--template', metavar = 'FILE',
121 short = 'Use FILE as the message template'),
122 opt('-c', '--cover', metavar = 'FILE',
123 short = 'Send FILE as the cover message'),
124 opt('-e', '--edit-cover', action = 'store_true',
125 short = 'Edit the cover message before sending'),
126 opt('-E', '--edit-patches', action = 'store_true',
127 short = 'Edit each patch before sending'),
128 opt('-s', '--sleep', type = 'int', metavar = 'SECONDS',
129 short = 'Sleep for SECONDS between e-mails sending'),
130 opt('--refid',
131 short = 'Use REFID as the reference id'),
132 opt('--smtp-server', metavar = 'HOST[:PORT] or "/path/to/sendmail -t -i"',
133 short = 'SMTP server or command to use for sending mail'),
134 opt('-u', '--smtp-user', metavar = 'USER',
135 short = 'Username for SMTP authentication'),
136 opt('-p', '--smtp-password', metavar = 'PASSWORD',
137 short = 'Password for SMTP authentication'),
138 opt('-T', '--smtp-tls', action = 'store_true',
139 short = 'Use SMTP with TLS encryption'),
6c8a90e1 140 opt('-b', '--branch', args = [argparse.stg_branches],
575bbdae
KH
141 short = 'Use BRANCH instead of the default branch'),
142 opt('-m', '--mbox', action = 'store_true',
143 short = 'Generate an mbox file instead of sending')
144 ] + argparse.diff_opts_option()
145
117ed129 146directory = DirectoryHasRepository(log = False)
b4bddc06 147
901288c2 148def __get_sender():
dae0f0be
CM
149 """Return the 'authname <authemail>' string as read from the
150 configuration file
151 """
c73e63b7
YD
152 sender=config.get('stgit.sender')
153 if not sender:
9e3f506f
KH
154 try:
155 sender = str(git.user())
156 except git.GitException:
ea09f8ce
GH
157 try:
158 sender = str(git.author())
159 except git.GitException:
160 pass
9e3f506f 161 if not sender:
ea09f8ce
GH
162 raise CmdException, ('Unknown sender name and e-mail; you should'
163 ' for example set git config user.name and'
164 ' user.email')
cd74a041
CM
165 sender = email.Utils.parseaddr(sender)
166
167 return email.Utils.formataddr(address_or_alias(sender))
dae0f0be 168
cd74a041
CM
169def __addr_list(msg, header):
170 return [addr for name, addr in
171 email.Utils.getaddresses(msg.get_all(header, []))]
9e3f506f 172
d650d6ed 173def __parse_addresses(msg):
b4bddc06
CM
174 """Return a two elements tuple: (from, [to])
175 """
d650d6ed 176 from_addr_list = __addr_list(msg, 'From')
24aadb3f 177 if len(from_addr_list) == 0:
b4bddc06 178 raise CmdException, 'No "From" address'
d650d6ed
CM
179
180 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
181 + __addr_list(msg, 'Bcc')
b4bddc06
CM
182 if len(to_addr_list) == 0:
183 raise CmdException, 'No "To/Cc/Bcc" addresses'
184
cd74a041 185 return (from_addr_list[0], set(to_addr_list))
b4bddc06 186
a0fe60a2
CM
187def __send_message_sendmail(sendmail, msg):
188 """Send the message using the sendmail command.
189 """
190 cmd = sendmail.split()
191 Run(*cmd).raw_input(msg).discard_output()
192
89d7ec43 193def __send_message_smtp(smtpserver, from_addr, to_addr_list, msg, options):
b4bddc06
CM
194 """Send the message using the given SMTP server
195 """
89d7ec43
AC
196 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
197 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
198 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
199
200 if (smtppassword and not smtpuser):
201 raise CmdException('SMTP password supplied, username needed')
202 if (smtpusetls and not smtpuser):
203 raise CmdException('SMTP over TLS requested, username needed')
204 if (smtpuser and not smtppassword):
205 smtppassword = getpass.getpass("Please enter SMTP password: ")
206
b4bddc06
CM
207 try:
208 s = smtplib.SMTP(smtpserver)
209 except Exception, err:
210 raise CmdException, str(err)
211
212 s.set_debuglevel(0)
213 try:
eb026d93
B
214 if smtpuser and smtppassword:
215 s.ehlo()
89d7ec43 216 if smtpusetls:
fc44c2ca
PR
217 if not hasattr(socket, 'ssl'):
218 raise CmdException, "cannot use TLS - no SSL support in Python"
219 s.starttls()
220 s.ehlo()
eb026d93
B
221 s.login(smtpuser, smtppassword)
222
0bc1343c
YD
223 result = s.sendmail(from_addr, to_addr_list, msg)
224 if len(result):
225 print "mail server refused delivery for the following recipients: %s" % result
b4bddc06
CM
226 except Exception, err:
227 raise CmdException, str(err)
228
229 s.quit()
230
9cb369d4 231def __send_message(type, tmpl, options, *args):
a0fe60a2
CM
232 """Message sending dispatcher.
233 """
9cb369d4
AC
234 (build, outstr) = {'cover': (__build_cover, 'the cover message'),
235 'patch': (__build_message, 'patch "%s"' % args[0])}[type]
236 if type == 'patch':
237 (patch_nr, total_nr) = (args[1], args[2])
238
239 msg_id = email.Utils.make_msgid('stgit')
240 msg = build(tmpl, msg_id, options, *args)
241
242 from_addr, to_addrs = __parse_addresses(msg)
243 msg_str = msg.as_string(options.mbox)
244 if options.mbox:
245 out.stdout_raw(msg_str + '\n')
246 return msg_id
247
248 out.start('Sending ' + outstr)
89d7ec43 249
9cb369d4 250 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
a0fe60a2
CM
251 if smtpserver.startswith('/'):
252 # Use the sendmail tool
9cb369d4 253 __send_message_sendmail(smtpserver, msg_str)
a0fe60a2
CM
254 else:
255 # Use the SMTP server (we have host and port information)
9cb369d4
AC
256 __send_message_smtp(smtpserver, from_addr, to_addrs, msg_str, options)
257
258 # give recipients a chance of receiving related patches in correct order
259 if type == 'cover' or (type == 'patch' and patch_nr < total_nr):
260 sleep = options.sleep or config.getint('stgit.smtpdelay')
261 time.sleep(sleep)
262 out.done()
263 return msg_id
a0fe60a2 264
c28b8841 265def __update_header(msg, header, addr = '', ignore = ()):
cd74a041
CM
266 def __addr_pairs(msg, header, extra):
267 pairs = email.Utils.getaddresses(msg.get_all(header, []) + extra)
268 # remove pairs without an address and resolve the aliases
269 return [address_or_alias(p) for p in pairs if p[1]]
270
c28b8841
AC
271 addr_pairs = __addr_pairs(msg, header, [addr])
272 del msg[header]
273 # remove the duplicates and filter the addresses
274 addr_dict = dict((addr, email.Utils.formataddr((name, addr)))
275 for name, addr in addr_pairs if addr not in ignore)
276 if addr_dict:
277 msg[header] = ', '.join(addr_dict.itervalues())
278 return set(addr_dict.iterkeys())
f8d1cf65 279
c28b8841
AC
280def __build_address_headers(msg, options, extra_cc = []):
281 """Build the address headers and check existing headers in the
282 template.
283 """
f8d1cf65
CM
284 to_addr = ''
285 cc_addr = ''
cd74a041 286 extra_cc_addr = ''
f8d1cf65
CM
287 bcc_addr = ''
288
c73e63b7 289 autobcc = config.get('stgit.autobcc') or ''
d884c4d8 290
e83b3149 291 if options.to:
61eed152 292 to_addr = ', '.join(options.to)
e83b3149 293 if options.cc:
cd74a041
CM
294 cc_addr = ', '.join(options.cc)
295 if extra_cc:
296 extra_cc_addr = ', '.join(extra_cc)
e83b3149 297 if options.bcc:
61eed152 298 bcc_addr = ', '.join(options.bcc + [autobcc])
d884c4d8
CM
299 elif autobcc:
300 bcc_addr = autobcc
f8d1cf65 301
cd74a041 302 # if an address is on a header, ignore it from the rest
c28b8841
AC
303 to_set = __update_header(msg, 'To', to_addr)
304 cc_set = __update_header(msg, 'Cc', cc_addr, to_set)
305 bcc_set = __update_header(msg, 'Bcc', bcc_addr, to_set.union(cc_set))
cd74a041
CM
306
307 # --auto generated addresses, don't include the sender
c28b8841
AC
308 from_set = __update_header(msg, 'From')
309 __update_header(msg, 'Cc', extra_cc_addr,
310 to_set.union(bcc_set).union(from_set))
f8d1cf65
CM
311
312def __get_signers_list(msg):
313 """Return the address list generated from signed-off-by and
314 acked-by lines in the message.
315 """
316 addr_list = []
de41ecc8
DW
317 tags = '%s|%s|%s|%s|%s|%s|%s' % (
318 'signed-off-by',
319 'acked-by',
320 'cc',
321 'reviewed-by',
322 'reported-by',
323 'tested-by',
324 'reported-and-tested-by')
325 regex = '^(%s):\s+(.+)$' % tags
326
327 r = re.compile(regex, re.I)
f8d1cf65
CM
328 for line in msg.split('\n'):
329 m = r.match(line)
330 if m:
331 addr_list.append(m.expand('\g<2>'))
332
333 return addr_list
e83b3149 334
61eed152
CM
335def __build_extra_headers(msg, msg_id, ref_id = None):
336 """Build extra email headers and encoding
19a56fa1 337 """
61eed152
CM
338 del msg['Date']
339 msg['Date'] = email.Utils.formatdate(localtime = True)
340 msg['Message-ID'] = msg_id
341 if ref_id:
00375337
CM
342 # make sure the ref id has the angle brackets
343 ref_id = '<%s>' % ref_id.strip(' \t\n<>')
61eed152
CM
344 msg['In-Reply-To'] = ref_id
345 msg['References'] = ref_id
d5214f56 346 msg['User-Agent'] = 'StGit/%s' % version.version
61eed152 347
c28b8841
AC
348 # update other address headers
349 __update_header(msg, 'Reply-To')
350 __update_header(msg, 'Mail-Reply-To')
351 __update_header(msg, 'Mail-Followup-To')
352
353
61eed152
CM
354def __encode_message(msg):
355 # 7 or 8 bit encoding
356 charset = email.Charset.Charset('utf-8')
357 charset.body_encoding = None
358
359 # encode headers
360 for header, value in msg.items():
361 words = []
362 for word in value.split(' '):
363 try:
364 uword = unicode(word, 'utf-8')
365 except UnicodeDecodeError:
366 # maybe we should try a different encoding or report
367 # the error. At the moment, we just ignore it
368 pass
369 words.append(email.Header.Header(uword).encode())
370 new_val = ' '.join(words)
371 msg.replace_header(header, new_val)
372
373 # encode the body and set the MIME and encoding headers
e5c32acf
CM
374 if msg.is_multipart():
375 for p in msg.get_payload():
376 p.set_charset(charset)
377 else:
378 msg.set_charset(charset)
19a56fa1 379
58c61f10 380def __edit_message(msg):
0ba13ee9
KH
381 fname = '.stgitmail.txt'
382
383 # create the initial file
384 f = file(fname, 'w')
385 f.write(msg)
386 f.close()
387
83bb4e4c 388 call_editor(fname)
0ba13ee9
KH
389
390 # read the message back
391 f = file(fname)
392 msg = f.read()
393 f.close()
394
395 return msg
396
c18d3a36 397def __build_cover(tmpl, msg_id, options, patches):
e3e05587 398 """Build the cover message (series description) to be sent via SMTP
b4bddc06 399 """
901288c2 400 sender = __get_sender()
dae0f0be 401
d0d139a3
CM
402 if options.version:
403 version_str = ' %s' % options.version
ed5de0cc
CM
404 else:
405 version_str = ''
d0d139a3 406
d323b5da
RR
407 if options.prefix:
408 prefix_str = options.prefix + ' '
409 else:
a7e0d4ee
YD
410 confprefix = config.get('stgit.mail.prefix')
411 if confprefix:
412 prefix_str = confprefix + ' '
413 else:
414 prefix_str = ''
d323b5da 415
99c4a4c5 416 total_nr_str = str(len(patches))
b8d258e5 417 patch_nr_str = '0'.zfill(len(total_nr_str))
99c4a4c5 418 if len(patches) > 1:
b8d258e5
CM
419 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
420 else:
421 number_str = ''
b4bddc06 422
901288c2
CM
423 tmpl_dict = {'sender': sender,
424 # for backward template compatibility
425 'maintainer': sender,
61eed152
CM
426 # for backward template compatibility
427 'endofheaders': '',
428 # for backward template compatibility
429 'date': '',
d0d139a3 430 'version': version_str,
d323b5da 431 'prefix': prefix_str,
b8d258e5
CM
432 'patchnr': patch_nr_str,
433 'totalnr': total_nr_str,
99c4a4c5 434 'number': number_str,
27827959 435 'shortlog': stack.shortlog(crt_series.get_patch(p)
c9379a15 436 for p in reversed(patches)),
ef954fe6 437 'diffstat': gitlib.diffstat(git.diff(
e4560d7e 438 rev1 = git_id(crt_series, '%s^' % patches[0]),
baf8241d
CM
439 rev2 = git_id(crt_series, '%s' % patches[-1]),
440 diff_flags = options.diff_flags))}
b4bddc06
CM
441
442 try:
61eed152 443 msg_string = tmpl % tmpl_dict
b4bddc06
CM
444 except KeyError, err:
445 raise CmdException, 'Unknown patch template variable: %s' \
446 % err
447 except TypeError:
448 raise CmdException, 'Only "%(name)s" variables are ' \
449 'supported in the patch template'
450
58c61f10
CM
451 if options.edit_cover:
452 msg_string = __edit_message(msg_string)
453
61eed152
CM
454 # The Python email message
455 try:
456 msg = email.message_from_string(msg_string)
457 except Exception, ex:
458 raise CmdException, 'template parsing error: %s' % str(ex)
459
460 __build_address_headers(msg, options)
461 __build_extra_headers(msg, msg_id, options.refid)
462 __encode_message(msg)
463
d650d6ed 464 return msg
b4bddc06 465
c18d3a36 466def __build_message(tmpl, msg_id, options, patch, patch_nr, total_nr, ref_id):
b4bddc06
CM
467 """Build the message to be sent via SMTP
468 """
469 p = crt_series.get_patch(patch)
470
c897c87c
AS
471 if p.get_description():
472 descr = p.get_description().strip()
473 else:
474 # provide a place holder and force the edit message option on
475 descr = '<empty message>'
476 options.edit_patches = True
b4bddc06 477
c897c87c 478 descr_lines = descr.split('\n')
42857cbe
ST
479 short_descr = descr_lines[0].strip()
480 long_descr = '\n'.join(l.rstrip() for l in descr_lines[1:]).lstrip('\n')
b4bddc06 481
1d1485c3
CM
482 authname = p.get_authname();
483 authemail = p.get_authemail();
484 commname = p.get_commname();
485 commemail = p.get_commemail();
486
901288c2 487 sender = __get_sender()
1d1485c3
CM
488
489 fromauth = '%s <%s>' % (authname, authemail)
901288c2 490 if fromauth != sender:
1d1485c3
CM
491 fromauth = 'From: %s\n\n' % fromauth
492 else:
493 fromauth = ''
dae0f0be 494
d0d139a3
CM
495 if options.version:
496 version_str = ' %s' % options.version
ed5de0cc
CM
497 else:
498 version_str = ''
d0d139a3 499
d323b5da
RR
500 if options.prefix:
501 prefix_str = options.prefix + ' '
502 else:
a7e0d4ee
YD
503 confprefix = config.get('stgit.mail.prefix')
504 if confprefix:
505 prefix_str = confprefix + ' '
506 else:
507 prefix_str = ''
0d219030 508
b4bddc06
CM
509 total_nr_str = str(total_nr)
510 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
c2a8af1d 511 if not options.unrelated and total_nr > 1:
b8d258e5
CM
512 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
513 else:
514 number_str = ''
b4bddc06 515
e4560d7e
CM
516 diff = git.diff(rev1 = git_id(crt_series, '%s^' % patch),
517 rev2 = git_id(crt_series, '%s' % patch),
a45cea15 518 diff_flags = options.diff_flags)
b4bddc06 519 tmpl_dict = {'patch': patch,
901288c2
CM
520 'sender': sender,
521 # for backward template compatibility
522 'maintainer': sender,
b4bddc06
CM
523 'shortdescr': short_descr,
524 'longdescr': long_descr,
61eed152
CM
525 # for backward template compatibility
526 'endofheaders': '',
a45cea15 527 'diff': diff,
ef954fe6 528 'diffstat': gitlib.diffstat(diff),
61eed152
CM
529 # for backward template compatibility
530 'date': '',
d0d139a3 531 'version': version_str,
d323b5da 532 'prefix': prefix_str,
b4bddc06
CM
533 'patchnr': patch_nr_str,
534 'totalnr': total_nr_str,
b8d258e5 535 'number': number_str,
1d1485c3
CM
536 'fromauth': fromauth,
537 'authname': authname,
538 'authemail': authemail,
b4bddc06 539 'authdate': p.get_authdate(),
1d1485c3
CM
540 'commname': commname,
541 'commemail': commemail}
61eed152 542 # change None to ''
b4bddc06
CM
543 for key in tmpl_dict:
544 if not tmpl_dict[key]:
545 tmpl_dict[key] = ''
546
547 try:
61eed152 548 msg_string = tmpl % tmpl_dict
b4bddc06
CM
549 except KeyError, err:
550 raise CmdException, 'Unknown patch template variable: %s' \
551 % err
552 except TypeError:
553 raise CmdException, 'Only "%(name)s" variables are ' \
554 'supported in the patch template'
555
58c61f10
CM
556 if options.edit_patches:
557 msg_string = __edit_message(msg_string)
558
61eed152
CM
559 # The Python email message
560 try:
561 msg = email.message_from_string(msg_string)
562 except Exception, ex:
563 raise CmdException, 'template parsing error: %s' % str(ex)
564
565 if options.auto:
566 extra_cc = __get_signers_list(descr)
567 else:
568 extra_cc = []
569
570 __build_address_headers(msg, options, extra_cc)
571 __build_extra_headers(msg, msg_id, ref_id)
572 __encode_message(msg)
573
d650d6ed 574 return msg
b4bddc06 575
b4bddc06
CM
576def func(parser, options, args):
577 """Send the patches by e-mail using the patchmail.tmpl file as
578 a template
579 """
b4bddc06 580 applied = crt_series.get_applied()
b4bddc06 581
6b1e0111
CM
582 if options.all:
583 patches = applied
584 elif len(args) >= 1:
b4f656f0
CM
585 unapplied = crt_series.get_unapplied()
586 patches = parse_patches(args, applied + unapplied, len(applied))
b4bddc06 587 else:
9a316368 588 raise CmdException, 'Incorrect options. Unknown patches to send'
b4bddc06 589
ea09f8ce
GH
590 # early test for sender identity
591 __get_sender()
592
3c04f430
CM
593 out.start('Checking the validity of the patches')
594 for p in patches:
595 if crt_series.empty_patch(p):
596 raise CmdException, 'Cannot send empty patch "%s"' % p
597 out.done()
598
b4bddc06 599 total_nr = len(patches)
9a316368
CM
600 if total_nr == 0:
601 raise CmdException, 'No patches to send'
b4bddc06 602
c2a8af1d
CM
603 if options.refid:
604 if options.noreply or options.unrelated:
605 raise CmdException, \
606 '--refid option not allowed with --noreply or --unrelated'
d1ed3a12 607 ref_id = options.refid
c2a8af1d
CM
608 else:
609 ref_id = None
b4bddc06 610
b4bddc06 611
e3e05587 612 # send the cover message (if any)
0ba13ee9 613 if options.cover or options.edit_cover:
c2a8af1d
CM
614 if options.unrelated:
615 raise CmdException, 'cover sending not allowed with --unrelated'
616
e3e05587
CM
617 # find the template file
618 if options.cover:
16fee874 619 tmpl = file(options.cover).read()
e3e05587 620 else:
1f3bb017
CM
621 tmpl = templates.get_template('covermail.tmpl')
622 if not tmpl:
623 raise CmdException, 'No cover message template file found'
b4bddc06 624
9cb369d4 625 msg_id = __send_message('cover', tmpl, options, patches)
d650d6ed 626
b4bddc06 627 # subsequent e-mails are seen as replies to the first one
d1ed3a12
CM
628 if not options.noreply:
629 ref_id = msg_id
b4bddc06 630
b4bddc06
CM
631 # send the patches
632 if options.template:
1f3bb017 633 tmpl = file(options.template).read()
b4bddc06 634 else:
e5c32acf
CM
635 if options.attach:
636 tmpl = templates.get_template('mailattch.tmpl')
637 else:
638 tmpl = templates.get_template('patchmail.tmpl')
1f3bb017
CM
639 if not tmpl:
640 raise CmdException, 'No e-mail template file found'
b4bddc06 641
9cb369d4
AC
642 for (p, n) in zip(patches, range(1, total_nr + 1)):
643 msg_id = __send_message('patch', tmpl, options, p, n, total_nr, ref_id)
d650d6ed 644
b4bddc06 645 # subsequent e-mails are seen as replies to the first one
c2a8af1d 646 if not options.noreply and not options.unrelated and not ref_id:
b4bddc06 647 ref_id = msg_id