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
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 import stack, git, version, templates
25 from stgit.config import config
28 help = 'send a patch or series of patches by e-mail'
29 usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
31 Send a patch or a range of patches by e-mail using the 'smtpserver'
32 configuration option. The From address and the e-mail format are
33 generated from the template file passed as argument to '--template'
34 (defaulting to '.git/patchmail.tmpl' or
35 '~/.stgit/templates/patchmail.tmpl' or
36 '/usr/share/stgit/templates/patchmail.tmpl').
38 The To/Cc/Bcc addresses can either be added to the template file or
39 passed via the corresponding command line options. They can be e-mail
40 addresses or aliases which are automatically expanded to the values
41 stored in the [mail "alias"] section of GIT configuration files.
43 A preamble e-mail can be sent using the '--cover' and/or
44 '--edit-cover' options. The first allows the user to specify a file to
45 be used as a template. The latter option will invoke the editor on the
46 specified file (defaulting to '.git/covermail.tmpl' or
47 '~/.stgit/templates/covermail.tmpl' or
48 '/usr/share/stgit/templates/covermail.tmpl').
50 All the subsequent e-mails appear as replies to the first e-mail sent
51 (either the preamble or the first patch). E-mails can be seen as
52 replies to a different e-mail by using the '--refid' option.
54 SMTP authentication is also possible with '--smtp-user' and
55 '--smtp-password' options, also available as configuration settings:
56 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
57 '--smtp-tls' option and 'smtptls' setting.
59 The patch e-mail template accepts the following variables:
61 %(patch)s - patch name
62 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
63 %(shortdescr)s - the first line of the patch description
64 %(longdescr)s - the rest of the patch description, after the first line
65 %(diff)s - unified diff of the patch
66 %(diffstat)s - diff statistics
67 %(version)s - ' version' string passed on the command line (or empty)
68 %(prefix)s - 'prefix ' string passed on the command line
69 %(patchnr)s - patch number
70 %(totalnr)s - total number of patches to be sent
71 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
72 %(fromauth)s - 'From: author\\n\\n' if different from sender
73 %(authname)s - author's name
74 %(authemail)s - author's email
75 %(authdate)s - patch creation date
76 %(commname)s - committer's name
77 %(commemail)s - committer's e-mail
79 For the preamble e-mail template, only the %(sender)s, %(version)s,
80 %(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
82 options = [make_option('-a', '--all',
83 help = 'e-mail all the applied patches',
84 action = 'store_true'),
86 help = 'add TO to the To: list',
89 help = 'add CC to the Cc: list',
92 help = 'add BCC to the Bcc: list',
95 help = 'automatically cc the patch signers',
96 action = 'store_true'),
97 make_option('--noreply',
98 help = 'do not send subsequent messages as replies',
99 action = 'store_true'),
100 make_option('--unrelated',
101 help = 'send patches without sequence numbering',
102 action = 'store_true'),
103 make_option('-v', '--version', metavar = 'VERSION',
104 help = 'add VERSION to the [PATCH ...] prefix'),
105 make_option('--prefix', metavar = 'PREFIX',
106 help = 'add PREFIX to the [... PATCH ...] prefix'),
107 make_option('-t', '--template', metavar = 'FILE',
108 help = 'use FILE as the message template'),
109 make_option('-c', '--cover', metavar = 'FILE',
110 help = 'send FILE as the cover message'),
111 make_option('-e', '--edit-cover',
112 help = 'edit the cover message before sending',
113 action = 'store_true'),
114 make_option('-E', '--edit-patches',
115 help = 'edit each patch before sending',
116 action = 'store_true'),
117 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
118 help = 'sleep for SECONDS between e-mails sending'),
119 make_option('--refid',
120 help = 'use REFID as the reference id'),
121 make_option('-u', '--smtp-user', metavar = 'USER',
122 help = 'username for SMTP authentication'),
123 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
124 help = 'username for SMTP authentication'),
125 make_option('-T', '--smtp-tls',
126 help = 'use SMTP with TLS encryption',
127 action = 'store_true'),
128 make_option('-b', '--branch',
129 help = 'use BRANCH instead of the default one'),
130 make_option('-O', '--diff-opts',
131 help = 'options to pass to git-diff'),
132 make_option('-m', '--mbox',
133 help = 'generate an mbox file instead of sending',
134 action = 'store_true')]
138 """Return the 'authname <authemail>' string as read from the
141 sender=config.get('stgit.sender')
144 sender = str(git.user())
145 except git.GitException:
146 sender = str(git.author())
149 raise CmdException, 'unknown sender details'
151 return address_or_alias(sender)
153 def __parse_addresses(msg):
154 """Return a two elements tuple: (from, [to])
156 def __addr_list(msg, header):
157 return [name_addr[1] for name_addr in
158 email.Utils.getaddresses(msg.get_all(header, []))]
160 from_addr_list = __addr_list(msg, 'From')
161 if len(from_addr_list) == 0:
162 raise CmdException, 'No "From" address'
164 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
165 + __addr_list(msg, 'Bcc')
166 if len(to_addr_list) == 0:
167 raise CmdException, 'No "To/Cc/Bcc" addresses'
169 return (from_addr_list[0], to_addr_list)
171 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
172 smtpuser, smtppassword, use_tls):
173 """Send the message using the given SMTP server
176 s = smtplib.SMTP(smtpserver)
177 except Exception, err:
178 raise CmdException, str(err)
182 if smtpuser and smtppassword:
185 if not hasattr(socket, 'ssl'):
186 raise CmdException, "cannot use TLS - no SSL support in Python"
189 s.login(smtpuser, smtppassword)
191 result = s.sendmail(from_addr, to_addr_list, msg)
193 print "mail server refused delivery for the following recipients: %s" % result
194 # give recipients a chance of receiving patches in the correct order
196 except Exception, err:
197 raise CmdException, str(err)
201 def __build_address_headers(msg, options, extra_cc = []):
202 """Build the address headers and check existing headers in the
205 def __replace_header(header, addr):
207 crt_addr = msg[header]
211 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
213 msg[header] = address_or_alias(addr)
219 autobcc = config.get('stgit.autobcc') or ''
222 to_addr = ', '.join(options.to)
224 cc_addr = ', '.join(options.cc + extra_cc)
226 cc_addr = ', '.join(extra_cc)
228 bcc_addr = ', '.join(options.bcc + [autobcc])
232 __replace_header('To', to_addr)
233 __replace_header('Cc', cc_addr)
234 __replace_header('Bcc', bcc_addr)
236 def __get_signers_list(msg):
237 """Return the address list generated from signed-off-by and
238 acked-by lines in the message.
242 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
243 for line in msg.split('\n'):
246 addr_list.append(m.expand('\g<2>'))
250 def __build_extra_headers(msg, msg_id, ref_id = None):
251 """Build extra email headers and encoding
254 msg['Date'] = email.Utils.formatdate(localtime = True)
255 msg['Message-ID'] = msg_id
257 msg['In-Reply-To'] = ref_id
258 msg['References'] = ref_id
259 msg['User-Agent'] = 'StGIT/%s' % version.version
261 def __encode_message(msg):
262 # 7 or 8 bit encoding
263 charset = email.Charset.Charset('utf-8')
264 charset.body_encoding = None
267 for header, value in msg.items():
269 for word in value.split(' '):
271 uword = unicode(word, 'utf-8')
272 except UnicodeDecodeError:
273 # maybe we should try a different encoding or report
274 # the error. At the moment, we just ignore it
276 words.append(email.Header.Header(uword).encode())
277 new_val = ' '.join(words)
278 msg.replace_header(header, new_val)
280 # encode the body and set the MIME and encoding headers
281 msg.set_charset(charset)
283 def __edit_message(msg):
284 fname = '.stgitmail.txt'
286 # create the initial file
293 # read the message back
300 def __build_cover(tmpl, total_nr, msg_id, options):
301 """Build the cover message (series description) to be sent via SMTP
303 sender = __get_sender()
306 version_str = ' %s' % options.version
311 prefix_str = options.prefix + ' '
313 confprefix = config.get('stgit.mail.prefix')
315 prefix_str = confprefix + ' '
319 total_nr_str = str(total_nr)
320 patch_nr_str = '0'.zfill(len(total_nr_str))
322 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
326 tmpl_dict = {'sender': sender,
327 # for backward template compatibility
328 'maintainer': sender,
329 # for backward template compatibility
331 # for backward template compatibility
333 'version': version_str,
334 'prefix': prefix_str,
335 'patchnr': patch_nr_str,
336 'totalnr': total_nr_str,
337 'number': number_str}
340 msg_string = tmpl % tmpl_dict
341 except KeyError, err:
342 raise CmdException, 'Unknown patch template variable: %s' \
345 raise CmdException, 'Only "%(name)s" variables are ' \
346 'supported in the patch template'
348 if options.edit_cover:
349 msg_string = __edit_message(msg_string)
351 # The Python email message
353 msg = email.message_from_string(msg_string)
354 except Exception, ex:
355 raise CmdException, 'template parsing error: %s' % str(ex)
357 __build_address_headers(msg, options)
358 __build_extra_headers(msg, msg_id, options.refid)
359 __encode_message(msg)
363 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
364 """Build the message to be sent via SMTP
366 p = crt_series.get_patch(patch)
368 descr = p.get_description().strip()
369 descr_lines = descr.split('\n')
371 short_descr = descr_lines[0].rstrip()
372 long_descr = '\n'.join(descr_lines[1:]).lstrip()
374 authname = p.get_authname();
375 authemail = p.get_authemail();
376 commname = p.get_commname();
377 commemail = p.get_commemail();
379 sender = __get_sender()
381 fromauth = '%s <%s>' % (authname, authemail)
382 if fromauth != sender:
383 fromauth = 'From: %s\n\n' % fromauth
388 version_str = ' %s' % options.version
393 prefix_str = options.prefix + ' '
395 confprefix = config.get('stgit.mail.prefix')
397 prefix_str = confprefix + ' '
401 if options.diff_opts:
402 diff_flags = options.diff_opts.split()
406 total_nr_str = str(total_nr)
407 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
408 if not options.unrelated and total_nr > 1:
409 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
413 tmpl_dict = {'patch': patch,
415 # for backward template compatibility
416 'maintainer': sender,
417 'shortdescr': short_descr,
418 'longdescr': long_descr,
419 # for backward template compatibility
421 'diff': git.diff(rev1 = git_id('%s//bottom' % patch),
422 rev2 = git_id('%s//top' % patch),
423 diff_flags = diff_flags ),
424 'diffstat': git.diffstat(rev1 = git_id('%s//bottom'%patch),
425 rev2 = git_id('%s//top' % patch)),
426 # for backward template compatibility
428 'version': version_str,
429 'prefix': prefix_str,
430 'patchnr': patch_nr_str,
431 'totalnr': total_nr_str,
432 'number': number_str,
433 'fromauth': fromauth,
434 'authname': authname,
435 'authemail': authemail,
436 'authdate': p.get_authdate(),
437 'commname': commname,
438 'commemail': commemail}
440 for key in tmpl_dict:
441 if not tmpl_dict[key]:
445 msg_string = tmpl % tmpl_dict
446 except KeyError, err:
447 raise CmdException, 'Unknown patch template variable: %s' \
450 raise CmdException, 'Only "%(name)s" variables are ' \
451 'supported in the patch template'
453 if options.edit_patches:
454 msg_string = __edit_message(msg_string)
456 # The Python email message
458 msg = email.message_from_string(msg_string)
459 except Exception, ex:
460 raise CmdException, 'template parsing error: %s' % str(ex)
463 extra_cc = __get_signers_list(descr)
467 __build_address_headers(msg, options, extra_cc)
468 __build_extra_headers(msg, msg_id, ref_id)
469 __encode_message(msg)
473 def func(parser, options, args):
474 """Send the patches by e-mail using the patchmail.tmpl file as
477 smtpserver = config.get('stgit.smtpserver')
479 applied = crt_series.get_applied()
484 unapplied = crt_series.get_unapplied()
485 patches = parse_patches(args, applied + unapplied, len(applied))
487 raise CmdException, 'Incorrect options. Unknown patches to send'
489 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
490 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
491 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
493 if (smtppassword and not smtpuser):
494 raise CmdException, 'SMTP password supplied, username needed'
495 if (smtpuser and not smtppassword):
496 raise CmdException, 'SMTP username supplied, password needed'
497 if (smtpusetls and not smtpuser):
498 raise CmdException, 'SMTP over TLS requested, username needed'
500 total_nr = len(patches)
502 raise CmdException, 'No patches to send'
505 if options.noreply or options.unrelated:
506 raise CmdException, \
507 '--refid option not allowed with --noreply or --unrelated'
508 ref_id = options.refid
512 sleep = options.sleep or config.getint('stgit.smtpdelay')
514 # send the cover message (if any)
515 if options.cover or options.edit_cover:
516 if options.unrelated:
517 raise CmdException, 'cover sending not allowed with --unrelated'
519 # find the template file
521 tmpl = file(options.cover).read()
523 tmpl = templates.get_template('covermail.tmpl')
525 raise CmdException, 'No cover message template file found'
527 msg_id = email.Utils.make_msgid('stgit')
528 msg = __build_cover(tmpl, total_nr, msg_id, options)
529 from_addr, to_addr_list = __parse_addresses(msg)
531 msg_string = msg.as_string(options.mbox)
533 # subsequent e-mails are seen as replies to the first one
534 if not options.noreply:
538 out.stdout_raw(msg_string + '\n')
540 out.start('Sending the cover message')
541 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
542 sleep, smtpuser, smtppassword, smtpusetls)
547 tmpl = file(options.template).read()
549 tmpl = templates.get_template('patchmail.tmpl')
551 raise CmdException, 'No e-mail template file found'
553 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
554 msg_id = email.Utils.make_msgid('stgit')
555 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
557 from_addr, to_addr_list = __parse_addresses(msg)
559 msg_string = msg.as_string(options.mbox)
561 # subsequent e-mails are seen as replies to the first one
562 if not options.noreply and not options.unrelated and not ref_id:
566 out.stdout_raw(msg_string + '\n')
568 out.start('Sending patch "%s"' % p)
569 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
570 sleep, smtpuser, smtppassword, smtpusetls)