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