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, see http://www.gnu.org/licenses/.
17 import sys
, os
, re
, time
, datetime
, socket
, smtplib
, getpass
18 import email
, email
.Utils
, email
.Header
19 from stgit
.argparse
import opt
20 from stgit
.commands
.common
import *
21 from stgit
.utils
import *
22 from stgit
.out
import *
23 from stgit
import argparse
, stack
, git
, version
, templates
24 from stgit
.config
import config
25 from stgit
.run
import Run
26 from stgit
.lib
import git
as gitlib
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 '--in-reply-to' 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 %(snumber)s - stripped version of '%(number)s'
71 %(nspace)s - ' ' if %(number)s is non-empty, otherwise empty string
72 %(patchnr)s - patch number
73 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
74 %(totalnr)s - total number of patches to be sent
75 %(version)s - 'version' string passed on the command line (or empty)
76 %(vspace)s - ' ' if %(version)s is non-empty, otherwise empty string
78 In addition to the common variables, the preamble e-mail template
79 accepts the following:
81 %(shortlog)s - first line of each patch description, listed by author
83 In addition to the common variables, the patch e-mail template accepts
86 %(authdate)s - patch creation date
87 %(authemail)s - author's email
88 %(authname)s - author's name
89 %(commemail)s - committer's e-mail
90 %(commname)s - committer's name
91 %(diff)s - unified diff of the patch
92 %(fromauth)s - 'From: author\n\n' if different from sender
93 %(longdescr)s - the rest of the patch description, after the first line
94 %(patch)s - patch name
95 %(prefix)s - 'prefix' string passed on the command line
96 %(pspace)s - ' ' if %(prefix)s is non-empty, otherwise empty string
97 %(shortdescr)s - the first line of the patch description"""
99 args
= [argparse
.patch_range(argparse
.applied_patches
,
100 argparse
.unapplied_patches
,
101 argparse
.hidden_patches
)]
103 opt('-a', '--all', action
= 'store_true',
104 short
= 'E-mail all the applied patches'),
105 opt('--to', action
= 'append',
106 short
= 'Add TO to the To: list'),
107 opt('--cc', action
= 'append',
108 short
= 'Add CC to the Cc: list'),
109 opt('--bcc', action
= 'append',
110 short
= 'Add BCC to the Bcc: list'),
111 opt('--auto', action
= 'store_true',
112 short
= 'Automatically cc the patch signers'),
113 opt('--no-thread', action
= 'store_true',
114 short
= 'Do not send subsequent messages as replies'),
115 opt('--unrelated', action
= 'store_true',
116 short
= 'Send patches without sequence numbering'),
117 opt('--attach', action
= 'store_true',
118 short
= 'Send a patch as attachment'),
119 opt('--attach-inline', action
= 'store_true',
120 short
= 'Send a patch inline and as an attachment'),
121 opt('-v', '--version', metavar
= 'VERSION',
122 short
= 'Add VERSION to the [PATCH ...] prefix'),
123 opt('--prefix', metavar
= 'PREFIX',
124 short
= 'Add PREFIX to the [... PATCH ...] prefix'),
125 opt('-t', '--template', metavar
= 'FILE',
126 short
= 'Use FILE as the message template'),
127 opt('-c', '--cover', metavar
= 'FILE',
128 short
= 'Send FILE as the cover message'),
129 opt('-e', '--edit-cover', action
= 'store_true',
130 short
= 'Edit the cover message before sending'),
131 opt('-E', '--edit-patches', action
= 'store_true',
132 short
= 'Edit each patch before sending'),
133 opt('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
134 short
= 'Sleep for SECONDS between e-mails sending'),
135 opt('--in-reply-to', metavar
= 'REFID',
136 short
= 'Use REFID as the reference id'),
137 opt('--smtp-server', metavar
= 'HOST[:PORT] or "/path/to/sendmail -t -i"',
138 short
= 'SMTP server or command to use for sending mail'),
139 opt('-u', '--smtp-user', metavar
= 'USER',
140 short
= 'Username for SMTP authentication'),
141 opt('-p', '--smtp-password', metavar
= 'PASSWORD',
142 short
= 'Password for SMTP authentication'),
143 opt('-T', '--smtp-tls', action
= 'store_true',
144 short
= 'Use SMTP with TLS encryption'),
145 opt('-b', '--branch', args
= [argparse
.stg_branches
],
146 short
= 'Use BRANCH instead of the default branch'),
147 opt('-m', '--mbox', action
= 'store_true',
148 short
= 'Generate an mbox file instead of sending'),
149 opt('--git', action
= 'store_true',
150 short
= 'Use git send-email (EXPERIMENTAL)')
151 ] + argparse
.diff_opts_option()
153 directory
= DirectoryHasRepository(log
= False)
156 """Return the 'authname <authemail>' string as read from the
159 sender
=config
.get('stgit.sender')
162 sender
= str(git
.user())
163 except git
.GitException
:
165 sender
= str(git
.author())
166 except git
.GitException
:
169 raise CmdException
, ('Unknown sender name and e-mail; you should'
170 ' for example set git config user.name and'
172 sender
= email
.Utils
.parseaddr(sender
)
174 return email
.Utils
.formataddr(address_or_alias(sender
))
176 def __addr_list(msg
, header
):
177 return [addr
for name
, addr
in
178 email
.Utils
.getaddresses(msg
.get_all(header
, []))]
180 def __parse_addresses(msg
):
181 """Return a two elements tuple: (from, [to])
183 from_addr_list
= __addr_list(msg
, 'From')
184 if len(from_addr_list
) == 0:
185 raise CmdException
, 'No "From" address'
187 to_addr_list
= __addr_list(msg
, 'To') + __addr_list(msg
, 'Cc') \
188 + __addr_list(msg
, 'Bcc')
189 if len(to_addr_list
) == 0:
190 raise CmdException
, 'No "To/Cc/Bcc" addresses'
192 return (from_addr_list
[0], set(to_addr_list
))
194 def __send_message_sendmail(sendmail
, msg
):
195 """Send the message using the sendmail command.
197 cmd
= sendmail
.split()
198 Run(*cmd
).raw_input(msg
).discard_output()
200 __smtp_credentials
= None
202 def __set_smtp_credentials(options
):
203 """Set the (smtpuser, smtppassword, smtpusetls) credentials if the method
206 global __smtp_credentials
208 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
209 if options
.mbox
or options
.git
or smtpserver
.startswith('/'):
212 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
213 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
214 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
216 if (smtppassword
and not smtpuser
):
217 raise CmdException('SMTP password supplied, username needed')
218 if (smtpusetls
and not smtpuser
):
219 raise CmdException('SMTP over TLS requested, username needed')
220 if (smtpuser
and not smtppassword
):
221 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
223 __smtp_credentials
= (smtpuser
, smtppassword
, smtpusetls
)
225 def __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
, options
):
226 """Send the message using the given SMTP server
228 smtpuser
, smtppassword
, smtpusetls
= __smtp_credentials
231 s
= smtplib
.SMTP(smtpserver
)
232 except Exception, err
:
233 raise CmdException
, str(err
)
237 if smtpuser
and smtppassword
:
240 if not hasattr(socket
, 'ssl'):
241 raise CmdException
, "cannot use TLS - no SSL support in Python"
244 s
.login(smtpuser
, smtppassword
)
246 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
248 print "mail server refused delivery for the following recipients: %s" % result
249 except Exception, err
:
250 raise CmdException
, str(err
)
254 def __send_message_git(msg
, options
):
255 """Send the message using git send-email
257 from subprocess
import call
258 from tempfile
import mkstemp
260 cmd
= ["git", "send-email", "--from=%s" % msg
['From']]
261 cmd
.append("--quiet")
262 cmd
.append("--suppress-cc=self")
264 cmd
.append("--suppress-cc=body")
265 if options
.in_reply_to
:
266 cmd
.extend(["--in-reply-to", options
.in_reply_to
])
267 if options
.no_thread
:
268 cmd
.append("--no-thread")
270 # We only support To/Cc/Bcc in git send-email for now.
271 for x
in ['to', 'cc', 'bcc']:
272 if getattr(options
, x
):
273 cmd
.extend('--%s=%s' % (x
, a
) for a
in getattr(options
, x
))
275 (fd
, path
) = mkstemp()
276 os
.write(fd
, msg
.as_string(options
.mbox
))
283 except Exception, err
:
284 raise CmdException
, str(err
)
288 def __send_message(type, tmpl
, options
, *args
):
289 """Message sending dispatcher.
291 (build
, outstr
) = {'cover': (__build_cover
, 'the cover message'),
292 'patch': (__build_message
, 'patch "%s"' % args
[0])}[type]
294 (patch_nr
, total_nr
) = (args
[1], args
[2])
296 msg_id
= email
.Utils
.make_msgid('stgit')
297 msg
= build(tmpl
, msg_id
, options
, *args
)
299 msg_str
= msg
.as_string(options
.mbox
)
301 out
.stdout_raw(msg_str
+ '\n')
305 from_addr
, to_addrs
= __parse_addresses(msg
)
306 out
.start('Sending ' + outstr
)
308 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
310 __send_message_git(msg
, options
)
311 elif smtpserver
.startswith('/'):
312 # Use the sendmail tool
313 __send_message_sendmail(smtpserver
, msg_str
)
315 # Use the SMTP server (we have host and port information)
316 __send_message_smtp(smtpserver
, from_addr
, to_addrs
, msg_str
, options
)
318 # give recipients a chance of receiving related patches in correct order
319 if type == 'cover' or (type == 'patch' and patch_nr
< total_nr
):
320 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
326 def __update_header(msg
, header
, addr
= '', ignore
= ()):
327 def __addr_pairs(msg
, header
, extra
):
328 pairs
= email
.Utils
.getaddresses(msg
.get_all(header
, []) + extra
)
329 # remove pairs without an address and resolve the aliases
330 return [address_or_alias(p
) for p
in pairs
if p
[1]]
332 addr_pairs
= __addr_pairs(msg
, header
, [addr
])
334 # remove the duplicates and filter the addresses
335 addr_dict
= dict((addr
, email
.Utils
.formataddr((name
, addr
)))
336 for name
, addr
in addr_pairs
if addr
not in ignore
)
338 msg
[header
] = ', '.join(addr_dict
.itervalues())
339 return set(addr_dict
.iterkeys())
341 def __build_address_headers(msg
, options
, extra_cc
= []):
342 """Build the address headers and check existing headers in the
350 autobcc
= config
.get('stgit.autobcc') or ''
353 to_addr
= ', '.join(options
.to
)
355 cc_addr
= ', '.join(options
.cc
)
357 extra_cc_addr
= ', '.join(extra_cc
)
359 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
363 # if an address is on a header, ignore it from the rest
364 from_set
= __update_header(msg
, 'From')
365 to_set
= __update_header(msg
, 'To', to_addr
)
366 # --auto generated addresses, don't include the sender
367 __update_header(msg
, 'Cc', extra_cc_addr
, from_set
)
368 cc_set
= __update_header(msg
, 'Cc', cc_addr
, to_set
)
369 bcc_set
= __update_header(msg
, 'Bcc', bcc_addr
, to_set
.union(cc_set
))
371 def __get_signers_list(msg
):
372 """Return the address list generated from signed-off-by and
373 acked-by lines in the message.
376 tags
= '%s|%s|%s|%s|%s|%s|%s|%s' % (
384 'reported-and-tested-by')
385 regex
= '^(%s):\s+(.+)$' % tags
387 r
= re
.compile(regex
, re
.I
)
388 for line
in msg
.split('\n'):
391 addr_list
.append(m
.expand('\g<2>'))
395 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
396 """Build extra email headers and encoding
399 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
400 msg
['Message-ID'] = msg_id
402 # make sure the ref id has the angle brackets
403 ref_id
= '<%s>' % ref_id
.strip(' \t\n<>')
404 msg
['In-Reply-To'] = ref_id
405 msg
['References'] = ref_id
406 msg
['User-Agent'] = 'StGit/%s' % version
.version
408 # update other address headers
409 __update_header(msg
, 'Reply-To')
410 __update_header(msg
, 'Mail-Reply-To')
411 __update_header(msg
, 'Mail-Followup-To')
414 def __encode_message(msg
):
415 # 7 or 8 bit encoding
416 charset
= email
.Charset
.Charset('utf-8')
417 charset
.body_encoding
= None
420 for header
, value
in msg
.items():
422 for word
in value
.split(' '):
424 uword
= unicode(word
, 'utf-8')
425 except UnicodeDecodeError:
426 # maybe we should try a different encoding or report
427 # the error. At the moment, we just ignore it
429 words
.append(email
.Header
.Header(uword
).encode())
430 new_val
= ' '.join(words
)
431 msg
.replace_header(header
, new_val
)
433 # replace the Subject string with a Header() object otherwise the long
434 # line folding is done using "\n\t" rather than "\n ", causing issues with
435 # some e-mail clients
436 subject
= msg
.get('subject', '')
437 msg
.replace_header('subject',
438 email
.Header
.Header(subject
, header_name
= 'subject'))
440 # encode the body and set the MIME and encoding headers
441 if msg
.is_multipart():
442 for p
in msg
.get_payload():
443 p
.set_charset(charset
)
445 msg
.set_charset(charset
)
447 def __edit_message(msg
):
448 fname
= '.stgitmail.txt'
450 # create the initial file
457 # read the message back
464 def __build_cover(tmpl
, msg_id
, options
, patches
):
465 """Build the cover message (series description) to be sent via SMTP
467 sender
= __get_sender()
470 version_str
= '%s' % options
.version
477 prefix_str
= options
.prefix
479 prefix_str
= config
.get('stgit.mail.prefix')
486 total_nr_str
= str(len(patches
))
487 patch_nr_str
= '0'.zfill(len(total_nr_str
))
489 number_str
= '%s/%s' % (patch_nr_str
, total_nr_str
)
495 tmpl_dict
= {'sender': sender
,
496 # for backward template compatibility
497 'maintainer': sender
,
498 # for backward template compatibility
500 # for backward template compatibility
502 'version': version_str
,
503 'vspace': version_space
,
504 'prefix': prefix_str
,
505 'pspace': prefix_space
,
506 'patchnr': patch_nr_str
,
507 'totalnr': total_nr_str
,
508 'number': number_str
,
509 'nspace': number_space
,
510 'snumber': number_str
.strip(),
511 'shortlog': stack
.shortlog(crt_series
.get_patch(p
)
512 for p
in reversed(patches
)),
513 'diffstat': gitlib
.diffstat(git
.diff(
514 rev1
= git_id(crt_series
, '%s^' % patches
[0]),
515 rev2
= git_id(crt_series
, '%s' % patches
[-1]),
516 diff_flags
= options
.diff_flags
))}
519 msg_string
= tmpl
% tmpl_dict
520 except KeyError, err
:
521 raise CmdException
, 'Unknown patch template variable: %s' \
524 raise CmdException
, 'Only "%(name)s" variables are ' \
525 'supported in the patch template'
527 if options
.edit_cover
:
528 msg_string
= __edit_message(msg_string
)
530 # The Python email message
532 msg
= email
.message_from_string(msg_string
)
533 except Exception, ex
:
534 raise CmdException
, 'template parsing error: %s' % str(ex
)
538 for patch
in patches
:
539 p
= crt_series
.get_patch(patch
)
540 if p
.get_description():
541 descr
= p
.get_description().strip()
542 extra_cc
.extend(__get_signers_list(descr
))
543 extra_cc
= list(set(extra_cc
))
547 __build_address_headers(msg
, options
, extra_cc
)
548 __build_extra_headers(msg
, msg_id
, options
.in_reply_to
)
549 __encode_message(msg
)
553 def __build_message(tmpl
, msg_id
, options
, patch
, patch_nr
, total_nr
, ref_id
):
554 """Build the message to be sent via SMTP
556 p
= crt_series
.get_patch(patch
)
558 if p
.get_description():
559 descr
= p
.get_description().strip()
561 # provide a place holder and force the edit message option on
562 descr
= '<empty message>'
563 options
.edit_patches
= True
565 descr_lines
= descr
.split('\n')
566 short_descr
= descr_lines
[0].strip()
567 long_descr
= '\n'.join(l
.rstrip() for l
in descr_lines
[1:]).lstrip('\n')
569 authname
= p
.get_authname();
570 authemail
= p
.get_authemail();
571 commname
= p
.get_commname();
572 commemail
= p
.get_commemail();
574 sender
= __get_sender()
576 fromauth
= '%s <%s>' % (authname
, authemail
)
577 if fromauth
!= sender
:
578 fromauth
= 'From: %s\n\n' % fromauth
583 version_str
= '%s' % options
.version
590 prefix_str
= options
.prefix
592 prefix_str
= config
.get('stgit.mail.prefix')
599 total_nr_str
= str(total_nr
)
600 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
601 if not options
.unrelated
and total_nr
> 1:
602 number_str
= '%s/%s' % (patch_nr_str
, total_nr_str
)
608 diff
= git
.diff(rev1
= git_id(crt_series
, '%s^' % patch
),
609 rev2
= git_id(crt_series
, '%s' % patch
),
610 diff_flags
= options
.diff_flags
)
611 tmpl_dict
= {'patch': patch
,
613 # for backward template compatibility
614 'maintainer': sender
,
615 'shortdescr': short_descr
,
616 'longdescr': long_descr
,
617 # for backward template compatibility
620 'diffstat': gitlib
.diffstat(diff
),
621 # for backward template compatibility
623 'version': version_str
,
624 'vspace': version_space
,
625 'prefix': prefix_str
,
626 'pspace': prefix_space
,
627 'patchnr': patch_nr_str
,
628 'totalnr': total_nr_str
,
629 'number': number_str
,
630 'nspace': number_space
,
631 'snumber': number_str
.strip(),
632 'fromauth': fromauth
,
633 'authname': authname
,
634 'authemail': authemail
,
635 'authdate': p
.get_authdate(),
636 'commname': commname
,
637 'commemail': commemail
}
639 for key
in tmpl_dict
:
640 if not tmpl_dict
[key
]:
644 msg_string
= tmpl
% tmpl_dict
645 except KeyError, err
:
646 raise CmdException
, 'Unknown patch template variable: %s' \
649 raise CmdException
, 'Only "%(name)s" variables are ' \
650 'supported in the patch template'
652 if options
.edit_patches
:
653 msg_string
= __edit_message(msg_string
)
655 # The Python email message
657 msg
= email
.message_from_string(msg_string
)
658 except Exception, ex
:
659 raise CmdException
, 'template parsing error: %s' % str(ex
)
662 extra_cc
= __get_signers_list(descr
)
667 __build_address_headers(msg
, options
, extra_cc
)
668 __build_extra_headers(msg
, msg_id
, ref_id
)
669 __encode_message(msg
)
673 def func(parser
, options
, args
):
674 """Send the patches by e-mail using the patchmail.tmpl file as
677 applied
= crt_series
.get_applied()
682 unapplied
= crt_series
.get_unapplied()
683 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
685 raise CmdException
, 'Incorrect options. Unknown patches to send'
687 # early test for sender identity
690 out
.start('Checking the validity of the patches')
692 if crt_series
.empty_patch(p
):
693 raise CmdException
, 'Cannot send empty patch "%s"' % p
696 total_nr
= len(patches
)
698 raise CmdException
, 'No patches to send'
700 if options
.in_reply_to
:
701 if options
.no_thread
or options
.unrelated
:
702 raise CmdException
, \
703 '--in-reply-to option not allowed with --no-thread or --unrelated'
704 ref_id
= options
.in_reply_to
708 # get username/password if sending by SMTP
709 __set_smtp_credentials(options
)
711 # send the cover message (if any)
712 if options
.cover
or options
.edit_cover
:
713 if options
.unrelated
:
714 raise CmdException
, 'cover sending not allowed with --unrelated'
716 # find the template file
718 tmpl
= file(options
.cover
).read()
720 tmpl
= templates
.get_template('covermail.tmpl')
722 raise CmdException
, 'No cover message template file found'
724 msg_id
= __send_message('cover', tmpl
, options
, patches
)
726 # subsequent e-mails are seen as replies to the first one
727 if not options
.no_thread
:
732 tmpl
= file(options
.template
).read()
735 tmpl
= templates
.get_template('mailattch.tmpl')
736 elif options
.attach_inline
:
737 tmpl
= templates
.get_template('patchandattch.tmpl')
739 tmpl
= templates
.get_template('patchmail.tmpl')
741 raise CmdException
, 'No e-mail template file found'
743 for (p
, n
) in zip(patches
, range(1, total_nr
+ 1)):
744 msg_id
= __send_message('patch', tmpl
, options
, p
, n
, total_nr
, ref_id
)
746 # subsequent e-mails are seen as replies to the first one
747 if not options
.no_thread
and not options
.unrelated
and not ref_id
: