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
18 import sys, os, re, time, datetime, socket, smtplib, getpass
19 import email, email.Utils, email.Header
20 from optparse import OptionParser, make_option
22 from stgit.commands.common import *
23 from stgit.utils import *
24 from stgit.out import *
25 from stgit import argparse, stack, git, version, templates
26 from stgit.config import config
27 from stgit.run import Run
30 help = 'send a patch or series of patches by e-mail'
31 usage = r"""%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
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 '--refid' 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 %(patchnr)s - patch number
72 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
73 %(totalnr)s - total number of patches to be sent
74 %(version)s - ' version' string passed on the command line (or empty)
76 In addition to the common variables, the preamble e-mail template
77 accepts the following:
79 %(shortlog)s - first line of each patch description, listed by author
81 In addition to the common variables, the patch e-mail template accepts
84 %(authdate)s - patch creation date
85 %(authemail)s - author's email
86 %(authname)s - author's name
87 %(commemail)s - committer's e-mail
88 %(commname)s - committer's name
89 %(diff)s - unified diff of the patch
90 %(fromauth)s - 'From: author\n\n' if different from sender
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"""
96 directory = DirectoryHasRepository()
97 options = [make_option('-a', '--all',
98 help = 'e-mail all the applied patches',
99 action = 'store_true'),
101 help = 'add TO to the To: list',
104 help = 'add CC to the Cc: list',
107 help = 'add BCC to the Bcc: list',
109 make_option('--auto',
110 help = 'automatically cc the patch signers',
111 action = 'store_true'),
112 make_option('--noreply',
113 help = 'do not send subsequent messages as replies',
114 action = 'store_true'),
115 make_option('--unrelated',
116 help = 'send patches without sequence numbering',
117 action = 'store_true'),
118 make_option('--attach',
119 help = 'send a patch as attachment',
120 action = 'store_true'),
121 make_option('-v', '--version', metavar = 'VERSION',
122 help = 'add VERSION to the [PATCH ...] prefix'),
123 make_option('--prefix', metavar = 'PREFIX',
124 help = 'add PREFIX to the [... PATCH ...] prefix'),
125 make_option('-t', '--template', metavar = 'FILE',
126 help = 'use FILE as the message template'),
127 make_option('-c', '--cover', metavar = 'FILE',
128 help = 'send FILE as the cover message'),
129 make_option('-e', '--edit-cover',
130 help = 'edit the cover message before sending',
131 action = 'store_true'),
132 make_option('-E', '--edit-patches',
133 help = 'edit each patch before sending',
134 action = 'store_true'),
135 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
136 help = 'sleep for SECONDS between e-mails sending'),
137 make_option('--refid',
138 help = 'use REFID as the reference id'),
139 make_option('--smtp-server',
140 metavar = 'HOST[:PORT] or "/path/to/sendmail -t -i"',
141 help = 'SMTP server or command to use for sending mail'),
142 make_option('-u', '--smtp-user', metavar = 'USER',
143 help = 'username for SMTP authentication'),
144 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
145 help = 'username for SMTP authentication'),
146 make_option('-T', '--smtp-tls',
147 help = 'use SMTP with TLS encryption',
148 action = 'store_true'),
149 make_option('-b', '--branch',
150 help = 'use BRANCH instead of the default one'),
151 make_option('-m', '--mbox',
152 help = 'generate an mbox file instead of sending',
153 action = 'store_true')
154 ] + argparse.diff_opts_option()
157 """Return the 'authname <authemail>' string as read from the
160 sender=config.get('stgit.sender')
163 sender = str(git.user())
164 except git.GitException:
165 sender = str(git.author())
168 raise CmdException, 'unknown sender details'
170 return address_or_alias(sender)
172 def __parse_addresses(msg):
173 """Return a two elements tuple: (from, [to])
175 def __addr_list(msg, header):
176 return [name_addr[1] for name_addr in
177 email.Utils.getaddresses(msg.get_all(header, []))]
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], 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 def __send_message_smtp(smtpserver, from_addr, to_addr_list, msg,
197 smtpuser, smtppassword, use_tls):
198 """Send the message using the given SMTP server
201 s = smtplib.SMTP(smtpserver)
202 except Exception, err:
203 raise CmdException, str(err)
207 if smtpuser and smtppassword:
210 if not hasattr(socket, 'ssl'):
211 raise CmdException, "cannot use TLS - no SSL support in Python"
214 s.login(smtpuser, smtppassword)
216 result = s.sendmail(from_addr, to_addr_list, msg)
218 print "mail server refused delivery for the following recipients: %s" % result
219 except Exception, err:
220 raise CmdException, str(err)
224 def __send_message(smtpserver, from_addr, to_addr_list, msg,
225 sleep, smtpuser, smtppassword, use_tls):
226 """Message sending dispatcher.
228 if smtpserver.startswith('/'):
229 # Use the sendmail tool
230 __send_message_sendmail(smtpserver, msg)
232 # Use the SMTP server (we have host and port information)
233 __send_message_smtp(smtpserver, from_addr, to_addr_list, msg,
234 smtpuser, smtppassword, use_tls)
235 # give recipients a chance of receiving patches in the correct order
238 def __build_address_headers(msg, options, extra_cc = []):
239 """Build the address headers and check existing headers in the
242 def __replace_header(header, addr):
244 crt_addr = msg[header]
248 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
250 msg[header] = address_or_alias(addr)
256 autobcc = config.get('stgit.autobcc') or ''
259 to_addr = ', '.join(options.to)
261 cc_addr = ', '.join(options.cc + extra_cc)
262 cc_addr = ', '.join(options.cc + extra_cc)
264 cc_addr = ', '.join(extra_cc)
266 bcc_addr = ', '.join(options.bcc + [autobcc])
270 __replace_header('To', to_addr)
271 __replace_header('Cc', cc_addr)
272 __replace_header('Bcc', bcc_addr)
274 def __get_signers_list(msg):
275 """Return the address list generated from signed-off-by and
276 acked-by lines in the message.
280 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
281 for line in msg.split('\n'):
284 addr_list.append(m.expand('\g<2>'))
288 def __build_extra_headers(msg, msg_id, ref_id = None):
289 """Build extra email headers and encoding
292 msg['Date'] = email.Utils.formatdate(localtime = True)
293 msg['Message-ID'] = msg_id
295 # make sure the ref id has the angle brackets
296 ref_id = '<%s>' % ref_id.strip(' \t\n<>')
297 msg['In-Reply-To'] = ref_id
298 msg['References'] = ref_id
299 msg['User-Agent'] = 'StGIT/%s' % version.version
301 def __encode_message(msg):
302 # 7 or 8 bit encoding
303 charset = email.Charset.Charset('utf-8')
304 charset.body_encoding = None
307 for header, value in msg.items():
309 for word in value.split(' '):
311 uword = unicode(word, 'utf-8')
312 except UnicodeDecodeError:
313 # maybe we should try a different encoding or report
314 # the error. At the moment, we just ignore it
316 words.append(email.Header.Header(uword).encode())
317 new_val = ' '.join(words)
318 msg.replace_header(header, new_val)
320 # encode the body and set the MIME and encoding headers
321 if msg.is_multipart():
322 for p in msg.get_payload():
323 p.set_charset(charset)
325 msg.set_charset(charset)
327 def __edit_message(msg):
328 fname = '.stgitmail.txt'
330 # create the initial file
337 # read the message back
344 def __build_cover(tmpl, patches, msg_id, options):
345 """Build the cover message (series description) to be sent via SMTP
347 sender = __get_sender()
350 version_str = ' %s' % options.version
355 prefix_str = options.prefix + ' '
357 confprefix = config.get('stgit.mail.prefix')
359 prefix_str = confprefix + ' '
363 total_nr_str = str(len(patches))
364 patch_nr_str = '0'.zfill(len(total_nr_str))
366 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
370 tmpl_dict = {'sender': sender,
371 # for backward template compatibility
372 'maintainer': sender,
373 # for backward template compatibility
375 # for backward template compatibility
377 'version': version_str,
378 'prefix': prefix_str,
379 'patchnr': patch_nr_str,
380 'totalnr': total_nr_str,
381 'number': number_str,
382 'shortlog': stack.shortlog(crt_series.get_patch(p)
384 'diffstat': git.diffstat(git.diff(
385 rev1 = git_id(crt_series, '%s^' % patches[0]),
386 rev2 = git_id(crt_series, '%s' % patches[-1])))}
389 msg_string = tmpl % tmpl_dict
390 except KeyError, err:
391 raise CmdException, 'Unknown patch template variable: %s' \
394 raise CmdException, 'Only "%(name)s" variables are ' \
395 'supported in the patch template'
397 if options.edit_cover:
398 msg_string = __edit_message(msg_string)
400 # The Python email message
402 msg = email.message_from_string(msg_string)
403 except Exception, ex:
404 raise CmdException, 'template parsing error: %s' % str(ex)
406 __build_address_headers(msg, options)
407 __build_extra_headers(msg, msg_id, options.refid)
408 __encode_message(msg)
412 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
413 """Build the message to be sent via SMTP
415 p = crt_series.get_patch(patch)
417 if p.get_description():
418 descr = p.get_description().strip()
420 # provide a place holder and force the edit message option on
421 descr = '<empty message>'
422 options.edit_patches = True
424 descr_lines = descr.split('\n')
425 short_descr = descr_lines[0].strip()
426 long_descr = '\n'.join(l.rstrip() for l in descr_lines[1:]).lstrip('\n')
428 authname = p.get_authname();
429 authemail = p.get_authemail();
430 commname = p.get_commname();
431 commemail = p.get_commemail();
433 sender = __get_sender()
435 fromauth = '%s <%s>' % (authname, authemail)
436 if fromauth != sender:
437 fromauth = 'From: %s\n\n' % fromauth
442 version_str = ' %s' % options.version
447 prefix_str = options.prefix + ' '
449 confprefix = config.get('stgit.mail.prefix')
451 prefix_str = confprefix + ' '
455 total_nr_str = str(total_nr)
456 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
457 if not options.unrelated and total_nr > 1:
458 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
462 diff = git.diff(rev1 = git_id(crt_series, '%s^' % patch),
463 rev2 = git_id(crt_series, '%s' % patch),
464 diff_flags = options.diff_flags)
465 tmpl_dict = {'patch': patch,
467 # for backward template compatibility
468 'maintainer': sender,
469 'shortdescr': short_descr,
470 'longdescr': long_descr,
471 # for backward template compatibility
474 'diffstat': git.diffstat(diff),
475 # for backward template compatibility
477 'version': version_str,
478 'prefix': prefix_str,
479 'patchnr': patch_nr_str,
480 'totalnr': total_nr_str,
481 'number': number_str,
482 'fromauth': fromauth,
483 'authname': authname,
484 'authemail': authemail,
485 'authdate': p.get_authdate(),
486 'commname': commname,
487 'commemail': commemail}
489 for key in tmpl_dict:
490 if not tmpl_dict[key]:
494 msg_string = tmpl % tmpl_dict
495 except KeyError, err:
496 raise CmdException, 'Unknown patch template variable: %s' \
499 raise CmdException, 'Only "%(name)s" variables are ' \
500 'supported in the patch template'
502 if options.edit_patches:
503 msg_string = __edit_message(msg_string)
505 # The Python email message
507 msg = email.message_from_string(msg_string)
508 except Exception, ex:
509 raise CmdException, 'template parsing error: %s' % str(ex)
512 extra_cc = __get_signers_list(descr)
516 __build_address_headers(msg, options, extra_cc)
517 __build_extra_headers(msg, msg_id, ref_id)
518 __encode_message(msg)
522 def func(parser, options, args):
523 """Send the patches by e-mail using the patchmail.tmpl file as
526 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
528 applied = crt_series.get_applied()
533 unapplied = crt_series.get_unapplied()
534 patches = parse_patches(args, applied + unapplied, len(applied))
536 raise CmdException, 'Incorrect options. Unknown patches to send'
538 out.start('Checking the validity of the patches')
540 if crt_series.empty_patch(p):
541 raise CmdException, 'Cannot send empty patch "%s"' % p
544 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
545 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
546 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
548 if (smtppassword and not smtpuser):
549 raise CmdException, 'SMTP password supplied, username needed'
550 if (smtpusetls and not smtpuser):
551 raise CmdException, 'SMTP over TLS requested, username needed'
552 if (smtpuser and not smtppassword):
553 smtppassword = getpass.getpass("Please enter SMTP password: ")
555 total_nr = len(patches)
557 raise CmdException, 'No patches to send'
560 if options.noreply or options.unrelated:
561 raise CmdException, \
562 '--refid option not allowed with --noreply or --unrelated'
563 ref_id = options.refid
567 sleep = options.sleep or config.getint('stgit.smtpdelay')
569 # send the cover message (if any)
570 if options.cover or options.edit_cover:
571 if options.unrelated:
572 raise CmdException, 'cover sending not allowed with --unrelated'
574 # find the template file
576 tmpl = file(options.cover).read()
578 tmpl = templates.get_template('covermail.tmpl')
580 raise CmdException, 'No cover message template file found'
582 msg_id = email.Utils.make_msgid('stgit')
583 msg = __build_cover(tmpl, patches, msg_id, options)
584 from_addr, to_addr_list = __parse_addresses(msg)
586 msg_string = msg.as_string(options.mbox)
588 # subsequent e-mails are seen as replies to the first one
589 if not options.noreply:
593 out.stdout_raw(msg_string + '\n')
595 out.start('Sending the cover message')
596 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
597 sleep, smtpuser, smtppassword, smtpusetls)
602 tmpl = file(options.template).read()
605 tmpl = templates.get_template('mailattch.tmpl')
607 tmpl = templates.get_template('patchmail.tmpl')
609 raise CmdException, 'No e-mail template file found'
611 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
612 msg_id = email.Utils.make_msgid('stgit')
613 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
615 from_addr, to_addr_list = __parse_addresses(msg)
617 msg_string = msg.as_string(options.mbox)
619 # subsequent e-mails are seen as replies to the first one
620 if not options.noreply and not options.unrelated and not ref_id:
624 out.stdout_raw(msg_string + '\n')
626 out.start('Sending patch "%s"' % p)
627 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
628 sleep, smtpuser, smtppassword, smtpusetls)