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 stack, git, version, templates
26 from stgit.config import config
29 help = 'send a patch or series of patches by e-mail'
30 usage = """%prog [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. The From address and the e-mail
35 format are generated from the template file passed as argument to
36 '--template' (defaulting to '.git/patchmail.tmpl' or
37 '~/.stgit/templates/patchmail.tmpl' or
38 '/usr/share/stgit/templates/patchmail.tmpl').
40 The To/Cc/Bcc addresses can either be added to the template file or
41 passed via the corresponding command line options. They can be e-mail
42 addresses or aliases which are automatically expanded to the values
43 stored in the [mail "alias"] section of GIT configuration files.
45 A preamble e-mail can be sent using the '--cover' and/or
46 '--edit-cover' options. The first allows the user to specify a file to
47 be used as a template. The latter option will invoke the editor on the
48 specified file (defaulting to '.git/covermail.tmpl' or
49 '~/.stgit/templates/covermail.tmpl' or
50 '/usr/share/stgit/templates/covermail.tmpl').
52 All the subsequent e-mails appear as replies to the first e-mail sent
53 (either the preamble or the first patch). E-mails can be seen as
54 replies to a different e-mail by using the '--refid' option.
56 SMTP authentication is also possible with '--smtp-user' and
57 '--smtp-password' options, also available as configuration settings:
58 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
59 '--smtp-tls' option and 'smtptls' setting.
61 The patch e-mail template accepts the following variables:
63 %(patch)s - patch name
64 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
65 %(shortdescr)s - the first line of the patch description
66 %(longdescr)s - the rest of the patch description, after the first line
67 %(diff)s - unified diff of the patch
68 %(diffstat)s - diff statistics
69 %(version)s - ' version' string passed on the command line (or empty)
70 %(prefix)s - 'prefix ' string passed on the command line
71 %(patchnr)s - patch number
72 %(totalnr)s - total number of patches to be sent
73 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
74 %(fromauth)s - 'From: author\\n\\n' if different from sender
75 %(authname)s - author's name
76 %(authemail)s - author's email
77 %(authdate)s - patch creation date
78 %(commname)s - committer's name
79 %(commemail)s - committer's e-mail
81 For the preamble e-mail template, only the %(sender)s, %(version)s,
82 %(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
84 options = [make_option('-a', '--all',
85 help = 'e-mail all the applied patches',
86 action = 'store_true'),
88 help = 'add TO to the To: list',
91 help = 'add CC to the Cc: list',
94 help = 'add BCC to the Bcc: list',
97 help = 'automatically cc the patch signers',
98 action = 'store_true'),
99 make_option('--noreply',
100 help = 'do not send subsequent messages as replies',
101 action = 'store_true'),
102 make_option('--unrelated',
103 help = 'send patches without sequence numbering',
104 action = 'store_true'),
105 make_option('-v', '--version', metavar = 'VERSION',
106 help = 'add VERSION to the [PATCH ...] prefix'),
107 make_option('--prefix', metavar = 'PREFIX',
108 help = 'add PREFIX to the [... PATCH ...] prefix'),
109 make_option('-t', '--template', metavar = 'FILE',
110 help = 'use FILE as the message template'),
111 make_option('-c', '--cover', metavar = 'FILE',
112 help = 'send FILE as the cover message'),
113 make_option('-e', '--edit-cover',
114 help = 'edit the cover message before sending',
115 action = 'store_true'),
116 make_option('-E', '--edit-patches',
117 help = 'edit each patch before sending',
118 action = 'store_true'),
119 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
120 help = 'sleep for SECONDS between e-mails sending'),
121 make_option('--refid',
122 help = 'use REFID as the reference id'),
123 make_option('--smtp-server', metavar = 'HOST[:PORT]',
124 help = 'SMTP server to use for sending mail'),
125 make_option('-u', '--smtp-user', metavar = 'USER',
126 help = 'username for SMTP authentication'),
127 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
128 help = 'username for SMTP authentication'),
129 make_option('-T', '--smtp-tls',
130 help = 'use SMTP with TLS encryption',
131 action = 'store_true'),
132 make_option('-b', '--branch',
133 help = 'use BRANCH instead of the default one'),
134 make_option('-O', '--diff-opts',
135 help = 'options to pass to git-diff'),
136 make_option('-m', '--mbox',
137 help = 'generate an mbox file instead of sending',
138 action = 'store_true')]
142 """Return the 'authname <authemail>' string as read from the
145 sender=config.get('stgit.sender')
148 sender = str(git.user())
149 except git.GitException:
150 sender = str(git.author())
153 raise CmdException, 'unknown sender details'
155 return address_or_alias(sender)
157 def __parse_addresses(msg):
158 """Return a two elements tuple: (from, [to])
160 def __addr_list(msg, header):
161 return [name_addr[1] for name_addr in
162 email.Utils.getaddresses(msg.get_all(header, []))]
164 from_addr_list = __addr_list(msg, 'From')
165 if len(from_addr_list) == 0:
166 raise CmdException, 'No "From" address'
168 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
169 + __addr_list(msg, 'Bcc')
170 if len(to_addr_list) == 0:
171 raise CmdException, 'No "To/Cc/Bcc" addresses'
173 return (from_addr_list[0], to_addr_list)
175 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
176 smtpuser, smtppassword, use_tls):
177 """Send the message using the given SMTP server
180 s = smtplib.SMTP(smtpserver)
181 except Exception, err:
182 raise CmdException, str(err)
186 if smtpuser and smtppassword:
189 if not hasattr(socket, 'ssl'):
190 raise CmdException, "cannot use TLS - no SSL support in Python"
193 s.login(smtpuser, smtppassword)
195 result = s.sendmail(from_addr, to_addr_list, msg)
197 print "mail server refused delivery for the following recipients: %s" % result
198 # give recipients a chance of receiving patches in the correct order
200 except Exception, err:
201 raise CmdException, str(err)
205 def __build_address_headers(msg, options, extra_cc = []):
206 """Build the address headers and check existing headers in the
209 def __replace_header(header, addr):
211 crt_addr = msg[header]
215 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
217 msg[header] = address_or_alias(addr)
223 autobcc = config.get('stgit.autobcc') or ''
226 to_addr = ', '.join(options.to)
228 cc_addr = ', '.join(options.cc + extra_cc)
230 cc_addr = ', '.join(extra_cc)
232 bcc_addr = ', '.join(options.bcc + [autobcc])
236 __replace_header('To', to_addr)
237 __replace_header('Cc', cc_addr)
238 __replace_header('Bcc', bcc_addr)
240 def __get_signers_list(msg):
241 """Return the address list generated from signed-off-by and
242 acked-by lines in the message.
246 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
247 for line in msg.split('\n'):
250 addr_list.append(m.expand('\g<2>'))
254 def __build_extra_headers(msg, msg_id, ref_id = None):
255 """Build extra email headers and encoding
258 msg['Date'] = email.Utils.formatdate(localtime = True)
259 msg['Message-ID'] = msg_id
261 msg['In-Reply-To'] = ref_id
262 msg['References'] = ref_id
263 msg['User-Agent'] = 'StGIT/%s' % version.version
265 def __encode_message(msg):
266 # 7 or 8 bit encoding
267 charset = email.Charset.Charset('utf-8')
268 charset.body_encoding = None
271 for header, value in msg.items():
273 for word in value.split(' '):
275 uword = unicode(word, 'utf-8')
276 except UnicodeDecodeError:
277 # maybe we should try a different encoding or report
278 # the error. At the moment, we just ignore it
280 words.append(email.Header.Header(uword).encode())
281 new_val = ' '.join(words)
282 msg.replace_header(header, new_val)
284 # encode the body and set the MIME and encoding headers
285 msg.set_charset(charset)
287 def __edit_message(msg):
288 fname = '.stgitmail.txt'
290 # create the initial file
297 # read the message back
304 def __build_cover(tmpl, total_nr, msg_id, options):
305 """Build the cover message (series description) to be sent via SMTP
307 sender = __get_sender()
310 version_str = ' %s' % options.version
315 prefix_str = options.prefix + ' '
317 confprefix = config.get('stgit.mail.prefix')
319 prefix_str = confprefix + ' '
323 total_nr_str = str(total_nr)
324 patch_nr_str = '0'.zfill(len(total_nr_str))
326 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
330 tmpl_dict = {'sender': sender,
331 # for backward template compatibility
332 'maintainer': sender,
333 # for backward template compatibility
335 # for backward template compatibility
337 'version': version_str,
338 'prefix': prefix_str,
339 'patchnr': patch_nr_str,
340 'totalnr': total_nr_str,
341 'number': number_str}
344 msg_string = tmpl % tmpl_dict
345 except KeyError, err:
346 raise CmdException, 'Unknown patch template variable: %s' \
349 raise CmdException, 'Only "%(name)s" variables are ' \
350 'supported in the patch template'
352 if options.edit_cover:
353 msg_string = __edit_message(msg_string)
355 # The Python email message
357 msg = email.message_from_string(msg_string)
358 except Exception, ex:
359 raise CmdException, 'template parsing error: %s' % str(ex)
361 __build_address_headers(msg, options)
362 __build_extra_headers(msg, msg_id, options.refid)
363 __encode_message(msg)
367 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
368 """Build the message to be sent via SMTP
370 p = crt_series.get_patch(patch)
372 descr = p.get_description().strip()
373 descr_lines = descr.split('\n')
375 short_descr = descr_lines[0].rstrip()
376 long_descr = '\n'.join(descr_lines[1:]).lstrip()
378 authname = p.get_authname();
379 authemail = p.get_authemail();
380 commname = p.get_commname();
381 commemail = p.get_commemail();
383 sender = __get_sender()
385 fromauth = '%s <%s>' % (authname, authemail)
386 if fromauth != sender:
387 fromauth = 'From: %s\n\n' % fromauth
392 version_str = ' %s' % options.version
397 prefix_str = options.prefix + ' '
399 confprefix = config.get('stgit.mail.prefix')
401 prefix_str = confprefix + ' '
405 if options.diff_opts:
406 diff_flags = options.diff_opts.split()
410 total_nr_str = str(total_nr)
411 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
412 if not options.unrelated and total_nr > 1:
413 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
417 tmpl_dict = {'patch': patch,
419 # for backward template compatibility
420 'maintainer': sender,
421 'shortdescr': short_descr,
422 'longdescr': long_descr,
423 # for backward template compatibility
425 'diff': git.diff(rev1 = git_id('%s//bottom' % patch),
426 rev2 = git_id('%s//top' % patch),
427 diff_flags = diff_flags ),
428 'diffstat': git.diffstat(rev1 = git_id('%s//bottom'%patch),
429 rev2 = git_id('%s//top' % patch)),
430 # for backward template compatibility
432 'version': version_str,
433 'prefix': prefix_str,
434 'patchnr': patch_nr_str,
435 'totalnr': total_nr_str,
436 'number': number_str,
437 'fromauth': fromauth,
438 'authname': authname,
439 'authemail': authemail,
440 'authdate': p.get_authdate(),
441 'commname': commname,
442 'commemail': commemail}
444 for key in tmpl_dict:
445 if not tmpl_dict[key]:
449 msg_string = tmpl % tmpl_dict
450 except KeyError, err:
451 raise CmdException, 'Unknown patch template variable: %s' \
454 raise CmdException, 'Only "%(name)s" variables are ' \
455 'supported in the patch template'
457 if options.edit_patches:
458 msg_string = __edit_message(msg_string)
460 # The Python email message
462 msg = email.message_from_string(msg_string)
463 except Exception, ex:
464 raise CmdException, 'template parsing error: %s' % str(ex)
467 extra_cc = __get_signers_list(descr)
471 __build_address_headers(msg, options, extra_cc)
472 __build_extra_headers(msg, msg_id, ref_id)
473 __encode_message(msg)
477 def func(parser, options, args):
478 """Send the patches by e-mail using the patchmail.tmpl file as
481 smtpserver = options.smtp_server or config.get('stgit.smtpserver')
483 applied = crt_series.get_applied()
488 unapplied = crt_series.get_unapplied()
489 patches = parse_patches(args, applied + unapplied, len(applied))
491 raise CmdException, 'Incorrect options. Unknown patches to send'
493 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
494 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
495 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
497 if (smtppassword and not smtpuser):
498 raise CmdException, 'SMTP password supplied, username needed'
499 if (smtpusetls and not smtpuser):
500 raise CmdException, 'SMTP over TLS requested, username needed'
501 if (smtpuser and not smtppassword):
502 smtppassword = getpass.getpass("Please enter SMTP password: ")
504 total_nr = len(patches)
506 raise CmdException, 'No patches to send'
509 if options.noreply or options.unrelated:
510 raise CmdException, \
511 '--refid option not allowed with --noreply or --unrelated'
512 ref_id = options.refid
516 sleep = options.sleep or config.getint('stgit.smtpdelay')
518 # send the cover message (if any)
519 if options.cover or options.edit_cover:
520 if options.unrelated:
521 raise CmdException, 'cover sending not allowed with --unrelated'
523 # find the template file
525 tmpl = file(options.cover).read()
527 tmpl = templates.get_template('covermail.tmpl')
529 raise CmdException, 'No cover message template file found'
531 msg_id = email.Utils.make_msgid('stgit')
532 msg = __build_cover(tmpl, total_nr, msg_id, options)
533 from_addr, to_addr_list = __parse_addresses(msg)
535 msg_string = msg.as_string(options.mbox)
537 # subsequent e-mails are seen as replies to the first one
538 if not options.noreply:
542 out.stdout_raw(msg_string + '\n')
544 out.start('Sending the cover message')
545 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
546 sleep, smtpuser, smtppassword, smtpusetls)
551 tmpl = file(options.template).read()
553 tmpl = templates.get_template('patchmail.tmpl')
555 raise CmdException, 'No e-mail template file found'
557 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
558 msg_id = email.Utils.make_msgid('stgit')
559 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
561 from_addr, to_addr_list = __parse_addresses(msg)
563 msg_string = msg.as_string(options.mbox)
565 # subsequent e-mails are seen as replies to the first one
566 if not options.noreply and not options.unrelated and not ref_id:
570 out.stdout_raw(msg_string + '\n')
572 out.start('Sending patch "%s"' % p)
573 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
574 sleep, smtpuser, smtppassword, smtpusetls)