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 '--refid' 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 %(patchnr)s - patch number
72 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
73 %(totalnr)s - total number of patches to be sent
74 %(version)s - ' version' string passed on the command line (or empty)
76 In addition to the common variables, the preamble e-mail template
77 accepts the following:
79 %(shortlog)s - first line of each patch description, listed by author
81 In addition to the common variables, the patch e-mail template accepts
84 %(authdate)s - patch creation date
85 %(authemail)s - author's email
86 %(authname)s - author's name
87 %(commemail)s - committer's e-mail
88 %(commname)s - committer's name
89 %(diff)s - unified diff of the patch
90 %(fromauth)s - 'From: author\n\n' if different from sender
91 %(longdescr)s - the rest of the patch description, after the first line
92 %(patch)s - patch name
93 %(prefix)s - 'prefix ' string passed on the command line
94 %(shortdescr)s - the first line of the patch description"""
96 args
= [argparse
.patch_range(argparse
.applied_patches
,
97 argparse
.unapplied_patches
,
98 argparse
.hidden_patches
)]
100 opt('-a', '--all', action
= 'store_true',
101 short
= 'E-mail all the applied patches'),
102 opt('--to', action
= 'append',
103 short
= 'Add TO to the To: list'),
104 opt('--cc', action
= 'append',
105 short
= 'Add CC to the Cc: list'),
106 opt('--bcc', action
= 'append',
107 short
= 'Add BCC to the Bcc: list'),
108 opt('--auto', action
= 'store_true',
109 short
= 'Automatically cc the patch signers'),
110 opt('--noreply', action
= 'store_true',
111 short
= 'Do not send subsequent messages as replies'),
112 opt('--unrelated', action
= 'store_true',
113 short
= 'Send patches without sequence numbering'),
114 opt('--attach', action
= 'store_true',
115 short
= 'Send a patch as attachment'),
116 opt('-v', '--version', metavar
= 'VERSION',
117 short
= 'Add VERSION to the [PATCH ...] prefix'),
118 opt('--prefix', metavar
= 'PREFIX',
119 short
= 'Add PREFIX to the [... PATCH ...] prefix'),
120 opt('-t', '--template', metavar
= 'FILE',
121 short
= 'Use FILE as the message template'),
122 opt('-c', '--cover', metavar
= 'FILE',
123 short
= 'Send FILE as the cover message'),
124 opt('-e', '--edit-cover', action
= 'store_true',
125 short
= 'Edit the cover message before sending'),
126 opt('-E', '--edit-patches', action
= 'store_true',
127 short
= 'Edit each patch before sending'),
128 opt('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
129 short
= 'Sleep for SECONDS between e-mails sending'),
131 short
= 'Use REFID as the reference id'),
132 opt('--smtp-server', metavar
= 'HOST[:PORT] or "/path/to/sendmail -t -i"',
133 short
= 'SMTP server or command to use for sending mail'),
134 opt('-u', '--smtp-user', metavar
= 'USER',
135 short
= 'Username for SMTP authentication'),
136 opt('-p', '--smtp-password', metavar
= 'PASSWORD',
137 short
= 'Password for SMTP authentication'),
138 opt('-T', '--smtp-tls', action
= 'store_true',
139 short
= 'Use SMTP with TLS encryption'),
140 opt('-b', '--branch', args
= [argparse
.stg_branches
],
141 short
= 'Use BRANCH instead of the default branch'),
142 opt('-m', '--mbox', action
= 'store_true',
143 short
= 'Generate an mbox file instead of sending')
144 ] + argparse
.diff_opts_option()
146 directory
= DirectoryHasRepository(log
= False)
149 """Return the 'authname <authemail>' string as read from the
152 sender
=config
.get('stgit.sender')
155 sender
= str(git
.user())
156 except git
.GitException
:
158 sender
= str(git
.author())
159 except git
.GitException
:
162 raise CmdException
, ('Unknown sender name and e-mail; you should'
163 ' for example set git config user.name and'
165 sender
= email
.Utils
.parseaddr(sender
)
167 return email
.Utils
.formataddr(address_or_alias(sender
))
169 def __addr_list(msg
, header
):
170 return [addr
for name
, addr
in
171 email
.Utils
.getaddresses(msg
.get_all(header
, []))]
173 def __parse_addresses(msg
):
174 """Return a two elements tuple: (from, [to])
176 from_addr_list
= __addr_list(msg
, 'From')
177 if len(from_addr_list
) == 0:
178 raise CmdException
, 'No "From" address'
180 to_addr_list
= __addr_list(msg
, 'To') + __addr_list(msg
, 'Cc') \
181 + __addr_list(msg
, 'Bcc')
182 if len(to_addr_list
) == 0:
183 raise CmdException
, 'No "To/Cc/Bcc" addresses'
185 return (from_addr_list
[0], set(to_addr_list
))
187 def __send_message_sendmail(sendmail
, msg
):
188 """Send the message using the sendmail command.
190 cmd
= sendmail
.split()
191 Run(*cmd
).raw_input(msg
).discard_output()
193 def __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
, options
):
194 """Send the message using the given SMTP server
196 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
197 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
198 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
200 if (smtppassword
and not smtpuser
):
201 raise CmdException('SMTP password supplied, username needed')
202 if (smtpusetls
and not smtpuser
):
203 raise CmdException('SMTP over TLS requested, username needed')
204 if (smtpuser
and not smtppassword
):
205 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
208 s
= smtplib
.SMTP(smtpserver
)
209 except Exception, err
:
210 raise CmdException
, str(err
)
214 if smtpuser
and smtppassword
:
217 if not hasattr(socket
, 'ssl'):
218 raise CmdException
, "cannot use TLS - no SSL support in Python"
221 s
.login(smtpuser
, smtppassword
)
223 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
225 print "mail server refused delivery for the following recipients: %s" % result
226 except Exception, err
:
227 raise CmdException
, str(err
)
231 def __send_message(from_addr
, to_addr_list
, msg
, options
):
232 """Message sending dispatcher.
234 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
236 if smtpserver
.startswith('/'):
237 # Use the sendmail tool
238 __send_message_sendmail(smtpserver
, msg
)
240 # Use the SMTP server (we have host and port information)
241 __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
, options
)
243 def __build_address_headers(msg
, options
, extra_cc
= []):
244 """Build the address headers and check existing headers in the
247 def __addr_pairs(msg
, header
, extra
):
248 pairs
= email
.Utils
.getaddresses(msg
.get_all(header
, []) + extra
)
249 # remove pairs without an address and resolve the aliases
250 return [address_or_alias(p
) for p
in pairs
if p
[1]]
252 def __update_header(header
, addr
= '', ignore
= ()):
253 addr_pairs
= __addr_pairs(msg
, header
, [addr
])
255 # remove the duplicates and filter the addresses
256 addr_dict
= dict((addr
, email
.Utils
.formataddr((name
, addr
)))
257 for name
, addr
in addr_pairs
if addr
not in ignore
)
259 msg
[header
] = ', '.join(addr_dict
.itervalues())
260 return set(addr_dict
.iterkeys())
267 autobcc
= config
.get('stgit.autobcc') or ''
270 to_addr
= ', '.join(options
.to
)
272 cc_addr
= ', '.join(options
.cc
)
274 extra_cc_addr
= ', '.join(extra_cc
)
276 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
280 # if an address is on a header, ignore it from the rest
281 to_set
= __update_header('To', to_addr
)
282 cc_set
= __update_header('Cc', cc_addr
, to_set
)
283 bcc_set
= __update_header('Bcc', bcc_addr
, to_set
.union(cc_set
))
285 # --auto generated addresses, don't include the sender
286 from_set
= __update_header('From')
287 __update_header('Cc', extra_cc_addr
, to_set
.union(bcc_set
).union(from_set
))
289 # update other address headers
290 __update_header('Reply-To')
291 __update_header('Mail-Reply-To')
292 __update_header('Mail-Followup-To')
294 def __get_signers_list(msg
):
295 """Return the address list generated from signed-off-by and
296 acked-by lines in the message.
299 tags
= '%s|%s|%s|%s|%s|%s|%s' %
(
306 'reported-and-tested-by')
307 regex
= '^(%s):\s+(.+)$' % tags
309 r
= re
.compile(regex
, re
.I
)
310 for line
in msg
.split('\n'):
313 addr_list
.append(m
.expand('\g<2>'))
317 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
318 """Build extra email headers and encoding
321 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
322 msg
['Message-ID'] = msg_id
324 # make sure the ref id has the angle brackets
325 ref_id
= '<%s>' % ref_id
.strip(' \t\n<>')
326 msg
['In-Reply-To'] = ref_id
327 msg
['References'] = ref_id
328 msg
['User-Agent'] = 'StGit/%s' % version
.version
330 def __encode_message(msg
):
331 # 7 or 8 bit encoding
332 charset
= email
.Charset
.Charset('utf-8')
333 charset
.body_encoding
= None
336 for header
, value
in msg
.items():
338 for word
in value
.split(' '):
340 uword
= unicode(word
, 'utf-8')
341 except UnicodeDecodeError:
342 # maybe we should try a different encoding or report
343 # the error. At the moment, we just ignore it
345 words
.append(email
.Header
.Header(uword
).encode())
346 new_val
= ' '.join(words
)
347 msg
.replace_header(header
, new_val
)
349 # encode the body and set the MIME and encoding headers
350 if msg
.is_multipart():
351 for p
in msg
.get_payload():
352 p
.set_charset(charset
)
354 msg
.set_charset(charset
)
356 def __edit_message(msg
):
357 fname
= '.stgitmail.txt'
359 # create the initial file
366 # read the message back
373 def __build_cover(tmpl
, msg_id
, options
, patches
):
374 """Build the cover message (series description) to be sent via SMTP
376 sender
= __get_sender()
379 version_str
= ' %s' % options
.version
384 prefix_str
= options
.prefix
+ ' '
386 confprefix
= config
.get('stgit.mail.prefix')
388 prefix_str
= confprefix
+ ' '
392 total_nr_str
= str(len(patches
))
393 patch_nr_str
= '0'.zfill(len(total_nr_str
))
395 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
399 tmpl_dict
= {'sender': sender
,
400 # for backward template compatibility
401 'maintainer': sender
,
402 # for backward template compatibility
404 # for backward template compatibility
406 'version': version_str
,
407 'prefix': prefix_str
,
408 'patchnr': patch_nr_str
,
409 'totalnr': total_nr_str
,
410 'number': number_str
,
411 'shortlog': stack
.shortlog(crt_series
.get_patch(p
)
412 for p
in reversed(patches
)),
413 'diffstat': gitlib
.diffstat(git
.diff(
414 rev1
= git_id(crt_series
, '%s^' % patches
[0]),
415 rev2
= git_id(crt_series
, '%s' % patches
[-1]),
416 diff_flags
= options
.diff_flags
))}
419 msg_string
= tmpl % tmpl_dict
420 except KeyError, err
:
421 raise CmdException
, 'Unknown patch template variable: %s' \
424 raise CmdException
, 'Only "%(name)s" variables are ' \
425 'supported in the patch template'
427 if options
.edit_cover
:
428 msg_string
= __edit_message(msg_string
)
430 # The Python email message
432 msg
= email
.message_from_string(msg_string
)
433 except Exception, ex
:
434 raise CmdException
, 'template parsing error: %s' % str
(ex
)
436 __build_address_headers(msg
, options
)
437 __build_extra_headers(msg
, msg_id
, options
.refid
)
438 __encode_message(msg
)
442 def __build_message(tmpl
, msg_id
, options
, patch
, patch_nr
, total_nr
, ref_id
):
443 """Build the message to be sent via SMTP
445 p
= crt_series
.get_patch(patch
)
447 if p
.get_description():
448 descr
= p
.get_description().strip()
450 # provide a place holder and force the edit message option on
451 descr
= '<empty message>'
452 options
.edit_patches
= True
454 descr_lines
= descr
.split('\n')
455 short_descr
= descr_lines
[0].strip()
456 long_descr
= '\n'.join(l
.rstrip() for l
in descr_lines
[1:]).lstrip('\n')
458 authname
= p
.get_authname();
459 authemail
= p
.get_authemail();
460 commname
= p
.get_commname();
461 commemail
= p
.get_commemail();
463 sender
= __get_sender()
465 fromauth
= '%s <%s>' %
(authname
, authemail
)
466 if fromauth
!= sender
:
467 fromauth
= 'From: %s\n\n' % fromauth
472 version_str
= ' %s' % options
.version
477 prefix_str
= options
.prefix
+ ' '
479 confprefix
= config
.get('stgit.mail.prefix')
481 prefix_str
= confprefix
+ ' '
485 total_nr_str
= str(total_nr
)
486 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
487 if not options
.unrelated
and total_nr
> 1:
488 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
492 diff
= git
.diff(rev1
= git_id(crt_series
, '%s^' % patch
),
493 rev2
= git_id(crt_series
, '%s' % patch
),
494 diff_flags
= options
.diff_flags
)
495 tmpl_dict
= {'patch': patch
,
497 # for backward template compatibility
498 'maintainer': sender
,
499 'shortdescr': short_descr
,
500 'longdescr': long_descr
,
501 # for backward template compatibility
504 'diffstat': gitlib
.diffstat(diff
),
505 # for backward template compatibility
507 'version': version_str
,
508 'prefix': prefix_str
,
509 'patchnr': patch_nr_str
,
510 'totalnr': total_nr_str
,
511 'number': number_str
,
512 'fromauth': fromauth
,
513 'authname': authname
,
514 'authemail': authemail
,
515 'authdate': p
.get_authdate(),
516 'commname': commname
,
517 'commemail': commemail
}
519 for key
in tmpl_dict
:
520 if not tmpl_dict
[key
]:
524 msg_string
= tmpl % tmpl_dict
525 except KeyError, err
:
526 raise CmdException
, 'Unknown patch template variable: %s' \
529 raise CmdException
, 'Only "%(name)s" variables are ' \
530 'supported in the patch template'
532 if options
.edit_patches
:
533 msg_string
= __edit_message(msg_string
)
535 # The Python email message
537 msg
= email
.message_from_string(msg_string
)
538 except Exception, ex
:
539 raise CmdException
, 'template parsing error: %s' % str
(ex
)
542 extra_cc
= __get_signers_list(descr
)
546 __build_address_headers(msg
, options
, extra_cc
)
547 __build_extra_headers(msg
, msg_id
, ref_id
)
548 __encode_message(msg
)
552 def func(parser
, options
, args
):
553 """Send the patches by e-mail using the patchmail.tmpl file as
556 applied
= crt_series
.get_applied()
561 unapplied
= crt_series
.get_unapplied()
562 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
564 raise CmdException
, 'Incorrect options. Unknown patches to send'
566 # early test for sender identity
569 out
.start('Checking the validity of the patches')
571 if crt_series
.empty_patch(p
):
572 raise CmdException
, 'Cannot send empty patch "%s"' % p
575 total_nr
= len(patches
)
577 raise CmdException
, 'No patches to send'
580 if options
.noreply
or options
.unrelated
:
581 raise CmdException
, \
582 '--refid option not allowed with --noreply or --unrelated'
583 ref_id
= options
.refid
587 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
589 # send the cover message (if any)
590 if options
.cover
or options
.edit_cover
:
591 if options
.unrelated
:
592 raise CmdException
, 'cover sending not allowed with --unrelated'
594 # find the template file
596 tmpl
= file(options
.cover
).read()
598 tmpl
= templates
.get_template('covermail.tmpl')
600 raise CmdException
, 'No cover message template file found'
602 msg_id
= email
.Utils
.make_msgid('stgit')
603 msg
= __build_cover(tmpl
, msg_id
, options
, patches
)
604 from_addr
, to_addr_list
= __parse_addresses(msg
)
606 msg_string
= msg
.as_string(options
.mbox
)
608 # subsequent e-mails are seen as replies to the first one
609 if not options
.noreply
:
613 out
.stdout_raw(msg_string
+ '\n')
615 out
.start('Sending the cover message')
616 __send_message(from_addr
, to_addr_list
, msg_string
, options
)
622 tmpl
= file(options
.template
).read()
625 tmpl
= templates
.get_template('mailattch.tmpl')
627 tmpl
= templates
.get_template('patchmail.tmpl')
629 raise CmdException
, 'No e-mail template file found'
631 for (p
, patch_nr
) in zip(patches
, range(1, total_nr
+ 1)):
632 msg_id
= email
.Utils
.make_msgid('stgit')
633 msg
= __build_message(tmpl
, msg_id
, options
, p
, patch_nr
, total_nr
,
635 from_addr
, to_addr_list
= __parse_addresses(msg
)
637 msg_string
= msg
.as_string(options
.mbox
)
639 # subsequent e-mails are seen as replies to the first one
640 if not options
.noreply
and not options
.unrelated
and not ref_id
:
644 out
.stdout_raw(msg_string
+ '\n')
646 out
.start('Sending patch "%s"' % p
)
647 __send_message(from_addr
, to_addr_list
, msg_string
, options
)
648 # give recipients a chance of receiving related patches in the
650 if patch_nr
< total_nr
: