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
27 from stgit
.lib
import git
as gitlib
29 help = 'Send a patch or series of patches by e-mail'
31 usage
= [' [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 '--in-reply-to' 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 %(snumber)s - stripped version of '%(number)s'
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)
77 In addition to the common variables, the preamble e-mail template
78 accepts the following:
80 %(shortlog)s - first line of each patch description, listed by author
82 In addition to the common variables, the patch e-mail template accepts
85 %(authdate)s - patch creation date
86 %(authemail)s - author's email
87 %(authname)s - author's name
88 %(commemail)s - committer's e-mail
89 %(commname)s - committer's name
90 %(diff)s - unified diff of the patch
91 %(fromauth)s - 'From: author\n\n' if different from sender
92 %(longdescr)s - the rest of the patch description, after the first line
93 %(patch)s - patch name
94 %(prefix)s - 'prefix ' string passed on the command line
95 %(shortdescr)s - the first line of the patch description"""
97 args
= [argparse
.patch_range(argparse
.applied_patches
,
98 argparse
.unapplied_patches
,
99 argparse
.hidden_patches
)]
101 opt('-a', '--all', action
= 'store_true',
102 short
= 'E-mail all the applied patches'),
103 opt('--to', action
= 'append',
104 short
= 'Add TO to the To: list'),
105 opt('--cc', action
= 'append',
106 short
= 'Add CC to the Cc: list'),
107 opt('--bcc', action
= 'append',
108 short
= 'Add BCC to the Bcc: list'),
109 opt('--auto', action
= 'store_true',
110 short
= 'Automatically cc the patch signers'),
111 opt('--no-thread', action
= 'store_true',
112 short
= 'Do not send subsequent messages as replies'),
113 opt('--unrelated', action
= 'store_true',
114 short
= 'Send patches without sequence numbering'),
115 opt('--attach', action
= 'store_true',
116 short
= 'Send a patch as attachment'),
117 opt('-v', '--version', metavar
= 'VERSION',
118 short
= 'Add VERSION to the [PATCH ...] prefix'),
119 opt('--prefix', metavar
= 'PREFIX',
120 short
= 'Add PREFIX to the [... PATCH ...] prefix'),
121 opt('-t', '--template', metavar
= 'FILE',
122 short
= 'Use FILE as the message template'),
123 opt('-c', '--cover', metavar
= 'FILE',
124 short
= 'Send FILE as the cover message'),
125 opt('-e', '--edit-cover', action
= 'store_true',
126 short
= 'Edit the cover message before sending'),
127 opt('-E', '--edit-patches', action
= 'store_true',
128 short
= 'Edit each patch before sending'),
129 opt('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
130 short
= 'Sleep for SECONDS between e-mails sending'),
131 opt('--in-reply-to', metavar
= 'REFID',
132 short
= 'Use REFID as the reference id'),
133 opt('--smtp-server', metavar
= 'HOST[:PORT] or "/path/to/sendmail -t -i"',
134 short
= 'SMTP server or command to use for sending mail'),
135 opt('-u', '--smtp-user', metavar
= 'USER',
136 short
= 'Username for SMTP authentication'),
137 opt('-p', '--smtp-password', metavar
= 'PASSWORD',
138 short
= 'Password for SMTP authentication'),
139 opt('-T', '--smtp-tls', action
= 'store_true',
140 short
= 'Use SMTP with TLS encryption'),
141 opt('-b', '--branch', args
= [argparse
.stg_branches
],
142 short
= 'Use BRANCH instead of the default branch'),
143 opt('-m', '--mbox', action
= 'store_true',
144 short
= 'Generate an mbox file instead of sending'),
145 opt('--git', action
= 'store_true',
146 short
= 'Use git send-email (EXPERIMENTAL)')
147 ] + argparse
.diff_opts_option()
149 directory
= DirectoryHasRepository(log
= False)
152 """Return the 'authname <authemail>' string as read from the
155 sender
=config
.get('stgit.sender')
158 sender
= str(git
.user())
159 except git
.GitException
:
161 sender
= str(git
.author())
162 except git
.GitException
:
165 raise CmdException
, ('Unknown sender name and e-mail; you should'
166 ' for example set git config user.name and'
168 sender
= email
.Utils
.parseaddr(sender
)
170 return email
.Utils
.formataddr(address_or_alias(sender
))
172 def __addr_list(msg
, header
):
173 return [addr
for name
, addr
in
174 email
.Utils
.getaddresses(msg
.get_all(header
, []))]
176 def __parse_addresses(msg
):
177 """Return a two elements tuple: (from, [to])
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], set(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 __smtp_credentials
= None
198 def __set_smtp_credentials(options
):
199 """Set the (smtpuser, smtppassword, smtpusetls) credentials if the method
202 global __smtp_credentials
204 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
205 if options
.mbox
or options
.git
or smtpserver
.startswith('/'):
208 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
209 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
210 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
212 if (smtppassword
and not smtpuser
):
213 raise CmdException('SMTP password supplied, username needed')
214 if (smtpusetls
and not smtpuser
):
215 raise CmdException('SMTP over TLS requested, username needed')
216 if (smtpuser
and not smtppassword
):
217 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
219 __smtp_credentials
= (smtpuser
, smtppassword
, smtpusetls
)
221 def __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
, options
):
222 """Send the message using the given SMTP server
224 smtpuser
, smtppassword
, smtpusetls
= __smtp_credentials
227 s
= smtplib
.SMTP(smtpserver
)
228 except Exception, err
:
229 raise CmdException
, str(err
)
233 if smtpuser
and smtppassword
:
236 if not hasattr(socket
, 'ssl'):
237 raise CmdException
, "cannot use TLS - no SSL support in Python"
240 s
.login(smtpuser
, smtppassword
)
242 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
244 print "mail server refused delivery for the following recipients: %s" % result
245 except Exception, err
:
246 raise CmdException
, str(err
)
250 def __send_message_git(msg
, options
):
251 """Send the message using git send-email
253 from subprocess
import call
254 from tempfile
import mkstemp
256 cmd
= ["git", "send-email", "--from=%s" % msg
['From']]
257 cmd
.append("--quiet")
258 cmd
.append("--suppress-cc=self")
260 cmd
.append("--suppress-cc=body")
261 if options
.in_reply_to
:
262 cmd
.extend(["--in-reply-to", options
.in_reply_to
])
263 if options
.no_thread
:
264 cmd
.append("--no-thread")
266 # We only support To/Cc/Bcc in git send-email for now.
267 for x
in ['to', 'cc', 'bcc']:
268 if getattr(options
, x
):
269 cmd
.extend('--%s=%s' % (x
, a
) for a
in getattr(options
, x
))
271 (fd
, path
) = mkstemp()
272 os
.write(fd
, msg
.as_string(options
.mbox
))
279 except Exception, err
:
280 raise CmdException
, str(err
)
284 def __send_message(type, tmpl
, options
, *args
):
285 """Message sending dispatcher.
287 (build
, outstr
) = {'cover': (__build_cover
, 'the cover message'),
288 'patch': (__build_message
, 'patch "%s"' % args
[0])}[type]
290 (patch_nr
, total_nr
) = (args
[1], args
[2])
292 msg_id
= email
.Utils
.make_msgid('stgit')
293 msg
= build(tmpl
, msg_id
, options
, *args
)
295 msg_str
= msg
.as_string(options
.mbox
)
297 out
.stdout_raw(msg_str
+ '\n')
301 from_addr
, to_addrs
= __parse_addresses(msg
)
302 out
.start('Sending ' + outstr
)
304 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
306 __send_message_git(msg
, options
)
307 elif smtpserver
.startswith('/'):
308 # Use the sendmail tool
309 __send_message_sendmail(smtpserver
, msg_str
)
311 # Use the SMTP server (we have host and port information)
312 __send_message_smtp(smtpserver
, from_addr
, to_addrs
, msg_str
, options
)
314 # give recipients a chance of receiving related patches in correct order
315 if type == 'cover' or (type == 'patch' and patch_nr
< total_nr
):
316 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
322 def __update_header(msg
, header
, addr
= '', ignore
= ()):
323 def __addr_pairs(msg
, header
, extra
):
324 pairs
= email
.Utils
.getaddresses(msg
.get_all(header
, []) + extra
)
325 # remove pairs without an address and resolve the aliases
326 return [address_or_alias(p
) for p
in pairs
if p
[1]]
328 addr_pairs
= __addr_pairs(msg
, header
, [addr
])
330 # remove the duplicates and filter the addresses
331 addr_dict
= dict((addr
, email
.Utils
.formataddr((name
, addr
)))
332 for name
, addr
in addr_pairs
if addr
not in ignore
)
334 msg
[header
] = ', '.join(addr_dict
.itervalues())
335 return set(addr_dict
.iterkeys())
337 def __build_address_headers(msg
, options
, extra_cc
= []):
338 """Build the address headers and check existing headers in the
346 autobcc
= config
.get('stgit.autobcc') or ''
349 to_addr
= ', '.join(options
.to
)
351 cc_addr
= ', '.join(options
.cc
)
353 extra_cc_addr
= ', '.join(extra_cc
)
355 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
359 # if an address is on a header, ignore it from the rest
360 to_set
= __update_header(msg
, 'To', to_addr
)
361 cc_set
= __update_header(msg
, 'Cc', cc_addr
, to_set
)
362 bcc_set
= __update_header(msg
, 'Bcc', bcc_addr
, to_set
.union(cc_set
))
364 # --auto generated addresses, don't include the sender
365 from_set
= __update_header(msg
, 'From')
366 __update_header(msg
, 'Cc', extra_cc_addr
,
367 to_set
.union(bcc_set
).union(from_set
))
369 def __get_signers_list(msg
):
370 """Return the address list generated from signed-off-by and
371 acked-by lines in the message.
374 tags
= '%s|%s|%s|%s|%s|%s|%s' % (
381 'reported-and-tested-by')
382 regex
= '^(%s):\s+(.+)$' % tags
384 r
= re
.compile(regex
, re
.I
)
385 for line
in msg
.split('\n'):
388 addr_list
.append(m
.expand('\g<2>'))
392 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
393 """Build extra email headers and encoding
396 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
397 msg
['Message-ID'] = msg_id
399 # make sure the ref id has the angle brackets
400 ref_id
= '<%s>' % ref_id
.strip(' \t\n<>')
401 msg
['In-Reply-To'] = ref_id
402 msg
['References'] = ref_id
403 msg
['User-Agent'] = 'StGit/%s' % version
.version
405 # update other address headers
406 __update_header(msg
, 'Reply-To')
407 __update_header(msg
, 'Mail-Reply-To')
408 __update_header(msg
, 'Mail-Followup-To')
411 def __encode_message(msg
):
412 # 7 or 8 bit encoding
413 charset
= email
.Charset
.Charset('utf-8')
414 charset
.body_encoding
= None
417 for header
, value
in msg
.items():
419 for word
in value
.split(' '):
421 uword
= unicode(word
, 'utf-8')
422 except UnicodeDecodeError:
423 # maybe we should try a different encoding or report
424 # the error. At the moment, we just ignore it
426 words
.append(email
.Header
.Header(uword
).encode())
427 new_val
= ' '.join(words
)
428 msg
.replace_header(header
, new_val
)
430 # replace the Subject string with a Header() object otherwise the long
431 # line folding is done using "\n\t" rather than "\n ", causing issues with
432 # some e-mail clients
433 subject
= msg
.get('subject', '')
434 msg
.replace_header('subject',
435 email
.Header
.Header(subject
, header_name
= 'subject'))
437 # encode the body and set the MIME and encoding headers
438 if msg
.is_multipart():
439 for p
in msg
.get_payload():
440 p
.set_charset(charset
)
442 msg
.set_charset(charset
)
444 def __edit_message(msg
):
445 fname
= '.stgitmail.txt'
447 # create the initial file
454 # read the message back
461 def __build_cover(tmpl
, msg_id
, options
, patches
):
462 """Build the cover message (series description) to be sent via SMTP
464 sender
= __get_sender()
467 version_str
= ' %s' % options
.version
472 prefix_str
= options
.prefix
+ ' '
474 confprefix
= config
.get('stgit.mail.prefix')
476 prefix_str
= confprefix
+ ' '
480 total_nr_str
= str(len(patches
))
481 patch_nr_str
= '0'.zfill(len(total_nr_str
))
483 number_str
= ' %s/%s' % (patch_nr_str
, total_nr_str
)
487 tmpl_dict
= {'sender': sender
,
488 # for backward template compatibility
489 'maintainer': sender
,
490 # for backward template compatibility
492 # for backward template compatibility
494 'version': version_str
,
495 'prefix': prefix_str
,
496 'patchnr': patch_nr_str
,
497 'totalnr': total_nr_str
,
498 'number': number_str
,
499 'snumber': number_str
.strip(),
500 'shortlog': stack
.shortlog(crt_series
.get_patch(p
)
501 for p
in reversed(patches
)),
502 'diffstat': gitlib
.diffstat(git
.diff(
503 rev1
= git_id(crt_series
, '%s^' % patches
[0]),
504 rev2
= git_id(crt_series
, '%s' % patches
[-1]),
505 diff_flags
= options
.diff_flags
))}
508 msg_string
= tmpl
% tmpl_dict
509 except KeyError, err
:
510 raise CmdException
, 'Unknown patch template variable: %s' \
513 raise CmdException
, 'Only "%(name)s" variables are ' \
514 'supported in the patch template'
516 if options
.edit_cover
:
517 msg_string
= __edit_message(msg_string
)
519 # The Python email message
521 msg
= email
.message_from_string(msg_string
)
522 except Exception, ex
:
523 raise CmdException
, 'template parsing error: %s' % str(ex
)
526 __build_address_headers(msg
, options
)
527 __build_extra_headers(msg
, msg_id
, options
.in_reply_to
)
528 __encode_message(msg
)
532 def __build_message(tmpl
, msg_id
, options
, patch
, patch_nr
, total_nr
, ref_id
):
533 """Build the message to be sent via SMTP
535 p
= crt_series
.get_patch(patch
)
537 if p
.get_description():
538 descr
= p
.get_description().strip()
540 # provide a place holder and force the edit message option on
541 descr
= '<empty message>'
542 options
.edit_patches
= True
544 descr_lines
= descr
.split('\n')
545 short_descr
= descr_lines
[0].strip()
546 long_descr
= '\n'.join(l
.rstrip() for l
in descr_lines
[1:]).lstrip('\n')
548 authname
= p
.get_authname();
549 authemail
= p
.get_authemail();
550 commname
= p
.get_commname();
551 commemail
= p
.get_commemail();
553 sender
= __get_sender()
555 fromauth
= '%s <%s>' % (authname
, authemail
)
556 if fromauth
!= sender
:
557 fromauth
= 'From: %s\n\n' % fromauth
562 version_str
= ' %s' % options
.version
567 prefix_str
= options
.prefix
+ ' '
569 confprefix
= config
.get('stgit.mail.prefix')
571 prefix_str
= confprefix
+ ' '
575 total_nr_str
= str(total_nr
)
576 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
577 if not options
.unrelated
and total_nr
> 1:
578 number_str
= ' %s/%s' % (patch_nr_str
, total_nr_str
)
582 diff
= git
.diff(rev1
= git_id(crt_series
, '%s^' % patch
),
583 rev2
= git_id(crt_series
, '%s' % patch
),
584 diff_flags
= options
.diff_flags
)
585 tmpl_dict
= {'patch': patch
,
587 # for backward template compatibility
588 'maintainer': sender
,
589 'shortdescr': short_descr
,
590 'longdescr': long_descr
,
591 # for backward template compatibility
594 'diffstat': gitlib
.diffstat(diff
),
595 # for backward template compatibility
597 'version': version_str
,
598 'prefix': prefix_str
,
599 'patchnr': patch_nr_str
,
600 'totalnr': total_nr_str
,
601 'number': number_str
,
602 'snumber': number_str
.strip(),
603 'fromauth': fromauth
,
604 'authname': authname
,
605 'authemail': authemail
,
606 'authdate': p
.get_authdate(),
607 'commname': commname
,
608 'commemail': commemail
}
610 for key
in tmpl_dict
:
611 if not tmpl_dict
[key
]:
615 msg_string
= tmpl
% tmpl_dict
616 except KeyError, err
:
617 raise CmdException
, 'Unknown patch template variable: %s' \
620 raise CmdException
, 'Only "%(name)s" variables are ' \
621 'supported in the patch template'
623 if options
.edit_patches
:
624 msg_string
= __edit_message(msg_string
)
626 # The Python email message
628 msg
= email
.message_from_string(msg_string
)
629 except Exception, ex
:
630 raise CmdException
, 'template parsing error: %s' % str(ex
)
633 extra_cc
= __get_signers_list(descr
)
638 __build_address_headers(msg
, options
, extra_cc
)
639 __build_extra_headers(msg
, msg_id
, ref_id
)
640 __encode_message(msg
)
644 def func(parser
, options
, args
):
645 """Send the patches by e-mail using the patchmail.tmpl file as
648 applied
= crt_series
.get_applied()
653 unapplied
= crt_series
.get_unapplied()
654 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
656 raise CmdException
, 'Incorrect options. Unknown patches to send'
658 # early test for sender identity
661 out
.start('Checking the validity of the patches')
663 if crt_series
.empty_patch(p
):
664 raise CmdException
, 'Cannot send empty patch "%s"' % p
667 total_nr
= len(patches
)
669 raise CmdException
, 'No patches to send'
671 if options
.in_reply_to
:
672 if options
.no_thread
or options
.unrelated
:
673 raise CmdException
, \
674 '--in-reply-to option not allowed with --no-thread or --unrelated'
675 ref_id
= options
.in_reply_to
679 # get username/password if sending by SMTP
680 __set_smtp_credentials(options
)
682 # send the cover message (if any)
683 if options
.cover
or options
.edit_cover
:
684 if options
.unrelated
:
685 raise CmdException
, 'cover sending not allowed with --unrelated'
687 # find the template file
689 tmpl
= file(options
.cover
).read()
691 tmpl
= templates
.get_template('covermail.tmpl')
693 raise CmdException
, 'No cover message template file found'
695 msg_id
= __send_message('cover', tmpl
, options
, patches
)
697 # subsequent e-mails are seen as replies to the first one
698 if not options
.no_thread
:
703 tmpl
= file(options
.template
).read()
706 tmpl
= templates
.get_template('mailattch.tmpl')
708 tmpl
= templates
.get_template('patchmail.tmpl')
710 raise CmdException
, 'No e-mail template file found'
712 for (p
, n
) in zip(patches
, range(1, total_nr
+ 1)):
713 msg_id
= __send_message('patch', tmpl
, options
, p
, n
, total_nr
, ref_id
)
715 # subsequent e-mails are seen as replies to the first one
716 if not options
.no_thread
and not options
.unrelated
and not ref_id
: