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 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
28 help = 'Send a patch or series of patches by e-mail'
30 usage = [' [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]']
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 '--refid' 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 %(patchnr)s - patch number
71 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
72 %(totalnr)s - total number of patches to be sent
73 %(version)s - ' version' string passed on the command line (or empty)
75 In addition to the common variables, the preamble e-mail template
76 accepts the following:
78 %(shortlog)s - first line of each patch description, listed by author
80 In addition to the common variables, the patch e-mail template accepts
83 %(authdate)s - patch creation date
84 %(authemail)s - author's email
85 %(authname)s - author's name
86 %(commemail)s - committer's e-mail
87 %(commname)s - committer's name
88 %(diff)s - unified diff of the patch
89 %(fromauth)s - 'From: author\n\n' if different from sender
90 %(longdescr)s - the rest of the patch description, after the first line
91 %(patch)s - patch name
92 %(prefix)s - 'prefix ' string passed on the command line
93 %(shortdescr)s - the first line of the patch description"""
96 opt('-a', '--all', action = 'store_true',
97 short = 'E-mail all the applied patches'),
98 opt('--to', action = 'append',
99 short = 'Add TO to the To: list'),
100 opt('--cc', action = 'append',
101 short = 'Add CC to the Cc: list'),
102 opt('--bcc', action = 'append',
103 short = 'Add BCC to the Bcc: list'),
104 opt('--auto', action = 'store_true',
105 short = 'Automatically cc the patch signers'),
106 opt('--noreply', action = 'store_true',
107 short = 'Do not send subsequent messages as replies'),
108 opt('--unrelated', action = 'store_true',
109 short = 'Send patches without sequence numbering'),
110 opt('--attach', action = 'store_true',
111 short = 'Send a patch as attachment'),
112 opt('-v', '--version', metavar = 'VERSION',
113 short = 'Add VERSION to the [PATCH ...] prefix'),
114 opt('--prefix', metavar = 'PREFIX',
115 short = 'Add PREFIX to the [... PATCH ...] prefix'),
116 opt('-t', '--template', metavar = 'FILE',
117 short = 'Use FILE as the message template'),
118 opt('-c', '--cover', metavar = 'FILE',
119 short = 'Send FILE as the cover message'),
120 opt('-e', '--edit-cover', action = 'store_true',
121 short = 'Edit the cover message before sending'),
122 opt('-E', '--edit-patches', action = 'store_true',
123 short = 'Edit each patch before sending'),
124 opt('-s', '--sleep', type = 'int', metavar = 'SECONDS',
125 short = 'Sleep for SECONDS between e-mails sending'),
127 short = 'Use REFID as the reference id'),
128 opt('--smtp-server', metavar = 'HOST[:PORT] or "/path/to/sendmail -t -i"',
129 short = 'SMTP server or command to use for sending mail'),
130 opt('-u', '--smtp-user', metavar = 'USER',
131 short = 'Username for SMTP authentication'),
132 opt('-p', '--smtp-password', metavar = 'PASSWORD',
133 short = 'Password for SMTP authentication'),
134 opt('-T', '--smtp-tls', action = 'store_true',
135 short = 'Use SMTP with TLS encryption'),
136 opt('-b', '--branch',
137 short = 'Use BRANCH instead of the default branch'),
138 opt('-m', '--mbox', action = 'store_true',
139 short = 'Generate an mbox file instead of sending')
140 ] + argparse.diff_opts_option()
142 directory = DirectoryHasRepository(log = False)
145 """Return the 'authname <authemail>' string as read from the
148 sender=config.get('stgit.sender')
151 sender = str(git.user())
152 except git.GitException:
153 sender = str(git.author())
156 raise CmdException, 'unknown sender details'
158 return address_or_alias(sender)
160 def __parse_addresses(msg):
161 """Return a two elements tuple: (from, [to])
163 def __addr_list(msg, header):
164 return [name_addr[1] for name_addr in
165 email.Utils.getaddresses(msg.get_all(header, []))]
167 from_addr_list = __addr_list(msg, 'From')
168 if len(from_addr_list) == 0:
169 raise CmdException, 'No "From" address'
171 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
172 + __addr_list(msg, 'Bcc')
173 if len(to_addr_list) == 0:
174 raise CmdException, 'No "To/Cc/Bcc" addresses'
176 return (from_addr_list[0], to_addr_list)
178 def __send_message_sendmail(sendmail, msg):
179 """Send the message using the sendmail command.
181 cmd = sendmail.split()
182 Run(*cmd).raw_input(msg).discard_output()
184 def __send_message_smtp(smtpserver, from_addr, to_addr_list, msg,
185 smtpuser, smtppassword, use_tls):
186 """Send the message using the given SMTP server
189 s = smtplib.SMTP(smtpserver)
190 except Exception, err:
191 raise CmdException, str(err)
195 if smtpuser and smtppassword:
198 if not hasattr(socket, 'ssl'):
199 raise CmdException, "cannot use TLS - no SSL support in Python"
202 s.login(smtpuser, smtppassword)
204 result = s.sendmail(from_addr, to_addr_list, msg)
206 print "mail server refused delivery for the following recipients: %s" % result
207 except Exception, err:
208 raise CmdException, str(err)
212 def __send_message(smtpserver, from_addr, to_addr_list, msg,
213 sleep, smtpuser, smtppassword, use_tls):
214 """Message sending dispatcher.
216 if smtpserver.startswith('/'):
217 # Use the sendmail tool
218 __send_message_sendmail(smtpserver, msg)
220 # Use the SMTP server (we have host and port information)
221 __send_message_smtp(smtpserver, from_addr, to_addr_list, msg,
222 smtpuser, smtppassword, use_tls)
223 # give recipients a chance of receiving patches in the correct order
226 def __build_address_headers(msg, options, extra_cc = []):
227 """Build the address headers and check existing headers in the
230 def __replace_header(header, addr):
232 crt_addr = msg[header]
236 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
238 msg[header] = address_or_alias(addr)
244 autobcc = config.get('stgit.autobcc') or ''
247 to_addr = ', '.join(options.to)
249 cc_addr = ', '.join(options.cc + extra_cc)
250 cc_addr = ', '.join(options.cc + extra_cc)
252 cc_addr = ', '.join(extra_cc)
254 bcc_addr = ', '.join(options.bcc + [autobcc])
258 __replace_header('To', to_addr)
259 __replace_header('Cc', cc_addr)
260 __replace_header('Bcc', bcc_addr)
262 def __get_signers_list(msg):
263 """Return the address list generated from signed-off-by and
264 acked-by lines in the message.
268 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
269 for line in msg.split('\n'):
272 addr_list.append(m.expand('\g<2>'))
276 def __build_extra_headers(msg, msg_id, ref_id = None):
277 """Build extra email headers and encoding
280 msg['Date'] = email.Utils.formatdate(localtime = True)
281 msg['Message-ID'] = msg_id
283 # make sure the ref id has the angle brackets
284 ref_id = '<%s>' % ref_id.strip(' \t\n<>')
285 msg['In-Reply-To'] = ref_id
286 msg['References'] = ref_id
287 msg['User-Agent'] = 'StGIT/%s' % version.version
289 def __encode_message(msg):
290 # 7 or 8 bit encoding
291 charset = email.Charset.Charset('utf-8')
292 charset.body_encoding = None
295 for header, value in msg.items():
297 for word in value.split(' '):
299 uword = unicode(word, 'utf-8')
300 except UnicodeDecodeError:
301 # maybe we should try a different encoding or report
302 # the error. At the moment, we just ignore it
304 words.append(email.Header.Header(uword).encode())
305 new_val = ' '.join(words)
306 msg.replace_header(header, new_val)
308 # encode the body and set the MIME and encoding headers
309 if msg.is_multipart():
310 for p in msg.get_payload():
311 p.set_charset(charset)
313 msg.set_charset(charset)
315 def __edit_message(msg):
316 fname = '.stgitmail.txt'
318 # create the initial file
325 # read the message back
332 def __build_cover(tmpl, patches, msg_id, options):
333 """Build the cover message (series description) to be sent via SMTP
335 sender = __get_sender()
338 version_str = ' %s' % options.version
343 prefix_str = options.prefix + ' '
345 confprefix = config.get('stgit.mail.prefix')
347 prefix_str = confprefix + ' '
351 total_nr_str = str(len(patches))
352 patch_nr_str = '0'.zfill(len(total_nr_str))
354 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
358 tmpl_dict = {'sender': sender,
359 # for backward template compatibility
360 'maintainer': sender,
361 # for backward template compatibility
363 # for backward template compatibility
365 'version': version_str,
366 'prefix': prefix_str,
367 'patchnr': patch_nr_str,
368 'totalnr': total_nr_str,
369 'number': number_str,
370 'shortlog': stack.shortlog(crt_series.get_patch(p)
372 'diffstat': git.diffstat(git.diff(
373 rev1 = git_id(crt_series, '%s^' % patches[0]),
374 rev2 = git_id(crt_series, '%s' % patches[-1])))}
377 msg_string = tmpl % tmpl_dict
378 except KeyError, err:
379 raise CmdException, 'Unknown patch template variable: %s' \
382 raise CmdException, 'Only "%(name)s" variables are ' \
383 'supported in the patch template'
385 if options.edit_cover:
386 msg_string = __edit_message(msg_string)
388 # The Python email message
390 msg = email.message_from_string(msg_string)
391 except Exception, ex:
392 raise CmdException, 'template parsing error: %s' % str(ex)
394 __build_address_headers(msg, options)
395 __build_extra_headers(msg, msg_id, options.refid)
396 __encode_message(msg)
400 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
401 """Build the message to be sent via SMTP
403 p = crt_series.get_patch(patch)
405 if p.get_description():
406 descr = p.get_description().strip()
408 # provide a place holder and force the edit message option on
409 descr = '<empty message>'
410 options.edit_patches = True
412 descr_lines = descr.split('\n')
413 short_descr = descr_lines[0].strip()
414 long_descr = '\n'.join(l.rstrip() for l in descr_lines[1:]).lstrip('\n')
416 authname = p.get_authname();
417 authemail = p.get_authemail();
418 commname = p.get_commname();
419 commemail = p.get_commemail();
421 sender = __get_sender()
423 fromauth = '%s <%s>' % (authname, authemail)
424 if fromauth != sender:
425 fromauth = 'From: %s\n\n' % fromauth
430 version_str = ' %s' % options.version
435 prefix_str = options.prefix + ' '
437 confprefix = config.get('stgit.mail.prefix')
439 prefix_str = confprefix + ' '
443 total_nr_str = str(total_nr)
444 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
445 if not options.unrelated and total_nr > 1:
446 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
450 diff = git.diff(rev1 = git_id(crt_series, '%s^' % patch),
451 rev2 = git_id(crt_series, '%s' % patch),
452 diff_flags = options.diff_flags)
453 tmpl_dict = {'patch': patch,
455 # for backward template compatibility
456 'maintainer': sender,
457 'shortdescr': short_descr,
458 'longdescr': long_descr,
459 # for backward template compatibility
462 'diffstat': git.diffstat(diff),
463 # for backward template compatibility
465 'version': version_str,
466 'prefix': prefix_str,
467 'patchnr': patch_nr_str,
468 'totalnr': total_nr_str,
469 'number': number_str,
470 'fromauth': fromauth,
471 'authname': authname,
472 'authemail': authemail,
473 'authdate': p.get_authdate(),
474 'commname': commname,
475 'commemail': commemail}
477 for key in tmpl_dict:
478 if not tmpl_dict[key]:
482 msg_string = tmpl % tmpl_dict
483 except KeyError, err:
484 raise CmdException, 'Unknown patch template variable: %s' \
487 raise CmdException, 'Only "%(name)s" variables are ' \
488 'supported in the patch template'
490 if options.edit_patches:
491 msg_string = __edit_message(msg_string)
493 # The Python email message
495 msg = email.message_from_string(msg_string)
496 except Exception, ex:
497 raise CmdException, 'template parsing error: %s' % str(ex)
500 extra_cc = __get_signers_list(descr)
504 __build_address_headers(msg, options, extra_cc)
505 __build_extra_headers(msg, msg_id, ref_id)
506 __encode_message(msg)
510 def func(parser, options, args):
511 """Send the patches by e-mail using the patchmail.tmpl file as
514 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
516 applied = crt_series.get_applied()
521 unapplied = crt_series.get_unapplied()
522 patches = parse_patches(args, applied + unapplied, len(applied))
524 raise CmdException, 'Incorrect options. Unknown patches to send'
526 out.start('Checking the validity of the patches')
528 if crt_series.empty_patch(p):
529 raise CmdException, 'Cannot send empty patch "%s"' % p
532 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
533 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
534 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
536 if (smtppassword and not smtpuser):
537 raise CmdException, 'SMTP password supplied, username needed'
538 if (smtpusetls and not smtpuser):
539 raise CmdException, 'SMTP over TLS requested, username needed'
540 if (smtpuser and not smtppassword):
541 smtppassword = getpass.getpass("Please enter SMTP password: ")
543 total_nr = len(patches)
545 raise CmdException, 'No patches to send'
548 if options.noreply or options.unrelated:
549 raise CmdException, \
550 '--refid option not allowed with --noreply or --unrelated'
551 ref_id = options.refid
555 sleep = options.sleep or config.getint('stgit.smtpdelay')
557 # send the cover message (if any)
558 if options.cover or options.edit_cover:
559 if options.unrelated:
560 raise CmdException, 'cover sending not allowed with --unrelated'
562 # find the template file
564 tmpl = file(options.cover).read()
566 tmpl = templates.get_template('covermail.tmpl')
568 raise CmdException, 'No cover message template file found'
570 msg_id = email.Utils.make_msgid('stgit')
571 msg = __build_cover(tmpl, patches, msg_id, options)
572 from_addr, to_addr_list = __parse_addresses(msg)
574 msg_string = msg.as_string(options.mbox)
576 # subsequent e-mails are seen as replies to the first one
577 if not options.noreply:
581 out.stdout_raw(msg_string + '\n')
583 out.start('Sending the cover message')
584 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
585 sleep, smtpuser, smtppassword, smtpusetls)
590 tmpl = file(options.template).read()
593 tmpl = templates.get_template('mailattch.tmpl')
595 tmpl = templates.get_template('patchmail.tmpl')
597 raise CmdException, 'No e-mail template file found'
599 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
600 msg_id = email.Utils.make_msgid('stgit')
601 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
603 from_addr, to_addr_list = __parse_addresses(msg)
605 msg_string = msg.as_string(options.mbox)
607 # subsequent e-mails are seen as replies to the first one
608 if not options.noreply and not options.unrelated and not ref_id:
612 out.stdout_raw(msg_string + '\n')
614 out.start('Sending patch "%s"' % p)
615 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
616 sleep, smtpuser, smtppassword, smtpusetls)