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"""
97 opt('-a', '--all', action
= 'store_true',
98 short
= 'E-mail all the applied patches'),
99 opt('--to', action
= 'append',
100 short
= 'Add TO to the To: list'),
101 opt('--cc', action
= 'append',
102 short
= 'Add CC to the Cc: list'),
103 opt('--bcc', action
= 'append',
104 short
= 'Add BCC to the Bcc: list'),
105 opt('--auto', action
= 'store_true',
106 short
= 'Automatically cc the patch signers'),
107 opt('--noreply', action
= 'store_true',
108 short
= 'Do not send subsequent messages as replies'),
109 opt('--unrelated', action
= 'store_true',
110 short
= 'Send patches without sequence numbering'),
111 opt('--attach', action
= 'store_true',
112 short
= 'Send a patch as attachment'),
113 opt('-v', '--version', metavar
= 'VERSION',
114 short
= 'Add VERSION to the [PATCH ...] prefix'),
115 opt('--prefix', metavar
= 'PREFIX',
116 short
= 'Add PREFIX to the [... PATCH ...] prefix'),
117 opt('-t', '--template', metavar
= 'FILE',
118 short
= 'Use FILE as the message template'),
119 opt('-c', '--cover', metavar
= 'FILE',
120 short
= 'Send FILE as the cover message'),
121 opt('-e', '--edit-cover', action
= 'store_true',
122 short
= 'Edit the cover message before sending'),
123 opt('-E', '--edit-patches', action
= 'store_true',
124 short
= 'Edit each patch before sending'),
125 opt('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
126 short
= 'Sleep for SECONDS between e-mails sending'),
128 short
= 'Use REFID as the reference id'),
129 opt('--smtp-server', metavar
= 'HOST[:PORT] or "/path/to/sendmail -t -i"',
130 short
= 'SMTP server or command to use for sending mail'),
131 opt('-u', '--smtp-user', metavar
= 'USER',
132 short
= 'Username for SMTP authentication'),
133 opt('-p', '--smtp-password', metavar
= 'PASSWORD',
134 short
= 'Password for SMTP authentication'),
135 opt('-T', '--smtp-tls', action
= 'store_true',
136 short
= 'Use SMTP with TLS encryption'),
137 opt('-b', '--branch',
138 short
= 'Use BRANCH instead of the default branch'),
139 opt('-m', '--mbox', action
= 'store_true',
140 short
= 'Generate an mbox file instead of sending')
141 ] + argparse
.diff_opts_option()
143 directory
= DirectoryHasRepository(log
= False)
146 """Return the 'authname <authemail>' string as read from the
149 sender
=config
.get('stgit.sender')
152 sender
= str(git
.user())
153 except git
.GitException
:
154 sender
= str(git
.author())
157 raise CmdException
, 'unknown sender details'
159 return address_or_alias(sender
)
161 def __parse_addresses(msg
):
162 """Return a two elements tuple: (from, [to])
164 def __addr_list(msg
, header
):
165 return [name_addr
[1] for name_addr
in
166 email
.Utils
.getaddresses(msg
.get_all(header
, []))]
168 from_addr_list
= __addr_list(msg
, 'From')
169 if len(from_addr_list
) == 0:
170 raise CmdException
, 'No "From" address'
172 to_addr_list
= __addr_list(msg
, 'To') + __addr_list(msg
, 'Cc') \
173 + __addr_list(msg
, 'Bcc')
174 if len(to_addr_list
) == 0:
175 raise CmdException
, 'No "To/Cc/Bcc" addresses'
177 return (from_addr_list
[0], to_addr_list
)
179 def __send_message_sendmail(sendmail
, msg
):
180 """Send the message using the sendmail command.
182 cmd
= sendmail
.split()
183 Run(*cmd
).raw_input(msg
).discard_output()
185 def __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
,
186 smtpuser
, smtppassword
, use_tls
):
187 """Send the message using the given SMTP server
190 s
= smtplib
.SMTP(smtpserver
)
191 except Exception, err
:
192 raise CmdException
, str(err
)
196 if smtpuser
and smtppassword
:
199 if not hasattr(socket
, 'ssl'):
200 raise CmdException
, "cannot use TLS - no SSL support in Python"
203 s
.login(smtpuser
, smtppassword
)
205 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
207 print "mail server refused delivery for the following recipients: %s" % result
208 except Exception, err
:
209 raise CmdException
, str(err
)
213 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
,
214 sleep
, smtpuser
, smtppassword
, use_tls
):
215 """Message sending dispatcher.
217 if smtpserver
.startswith('/'):
218 # Use the sendmail tool
219 __send_message_sendmail(smtpserver
, msg
)
221 # Use the SMTP server (we have host and port information)
222 __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
,
223 smtpuser
, smtppassword
, use_tls
)
224 # give recipients a chance of receiving patches in the correct order
227 def __build_address_headers(msg
, options
, extra_cc
= []):
228 """Build the address headers and check existing headers in the
231 def __replace_header(header
, addr
):
233 crt_addr
= msg
[header
]
237 msg
[header
] = address_or_alias(', '.join([crt_addr
, addr
]))
239 msg
[header
] = address_or_alias(addr
)
245 autobcc
= config
.get('stgit.autobcc') or ''
248 to_addr
= ', '.join(options
.to
)
250 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
251 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
253 cc_addr
= ', '.join(extra_cc
)
255 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
259 __replace_header('To', to_addr
)
260 __replace_header('Cc', cc_addr
)
261 __replace_header('Bcc', bcc_addr
)
263 def __get_signers_list(msg
):
264 """Return the address list generated from signed-off-by and
265 acked-by lines in the message.
269 r
= re
.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re
.I
)
270 for line
in msg
.split('\n'):
273 addr_list
.append(m
.expand('\g<2>'))
277 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
278 """Build extra email headers and encoding
281 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
282 msg
['Message-ID'] = msg_id
284 # make sure the ref id has the angle brackets
285 ref_id
= '<%s>' % ref_id
.strip(' \t\n<>')
286 msg
['In-Reply-To'] = ref_id
287 msg
['References'] = ref_id
288 msg
['User-Agent'] = 'StGIT/%s' % version
.version
290 def __encode_message(msg
):
291 # 7 or 8 bit encoding
292 charset
= email
.Charset
.Charset('utf-8')
293 charset
.body_encoding
= None
296 for header
, value
in msg
.items():
298 for word
in value
.split(' '):
300 uword
= unicode(word
, 'utf-8')
301 except UnicodeDecodeError:
302 # maybe we should try a different encoding or report
303 # the error. At the moment, we just ignore it
305 words
.append(email
.Header
.Header(uword
).encode())
306 new_val
= ' '.join(words
)
307 msg
.replace_header(header
, new_val
)
309 # encode the body and set the MIME and encoding headers
310 if msg
.is_multipart():
311 for p
in msg
.get_payload():
312 p
.set_charset(charset
)
314 msg
.set_charset(charset
)
316 def __edit_message(msg
):
317 fname
= '.stgitmail.txt'
319 # create the initial file
326 # read the message back
333 def __build_cover(tmpl
, patches
, msg_id
, options
):
334 """Build the cover message (series description) to be sent via SMTP
336 sender
= __get_sender()
339 version_str
= ' %s' % options
.version
344 prefix_str
= options
.prefix
+ ' '
346 confprefix
= config
.get('stgit.mail.prefix')
348 prefix_str
= confprefix
+ ' '
352 total_nr_str
= str(len(patches
))
353 patch_nr_str
= '0'.zfill(len(total_nr_str
))
355 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
359 tmpl_dict
= {'sender': sender
,
360 # for backward template compatibility
361 'maintainer': sender
,
362 # for backward template compatibility
364 # for backward template compatibility
366 'version': version_str
,
367 'prefix': prefix_str
,
368 'patchnr': patch_nr_str
,
369 'totalnr': total_nr_str
,
370 'number': number_str
,
371 'shortlog': stack
.shortlog(crt_series
.get_patch(p
)
373 'diffstat': gitlib
.diffstat(git
.diff(
374 rev1
= git_id(crt_series
, '%s^' % patches
[0]),
375 rev2
= git_id(crt_series
, '%s' % patches
[-1])))}
378 msg_string
= tmpl % tmpl_dict
379 except KeyError, err
:
380 raise CmdException
, 'Unknown patch template variable: %s' \
383 raise CmdException
, 'Only "%(name)s" variables are ' \
384 'supported in the patch template'
386 if options
.edit_cover
:
387 msg_string
= __edit_message(msg_string
)
389 # The Python email message
391 msg
= email
.message_from_string(msg_string
)
392 except Exception, ex
:
393 raise CmdException
, 'template parsing error: %s' % str
(ex
)
395 __build_address_headers(msg
, options
)
396 __build_extra_headers(msg
, msg_id
, options
.refid
)
397 __encode_message(msg
)
401 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
402 """Build the message to be sent via SMTP
404 p
= crt_series
.get_patch(patch
)
406 if p
.get_description():
407 descr
= p
.get_description().strip()
409 # provide a place holder and force the edit message option on
410 descr
= '<empty message>'
411 options
.edit_patches
= True
413 descr_lines
= descr
.split('\n')
414 short_descr
= descr_lines
[0].strip()
415 long_descr
= '\n'.join(l
.rstrip() for l
in descr_lines
[1:]).lstrip('\n')
417 authname
= p
.get_authname();
418 authemail
= p
.get_authemail();
419 commname
= p
.get_commname();
420 commemail
= p
.get_commemail();
422 sender
= __get_sender()
424 fromauth
= '%s <%s>' %
(authname
, authemail
)
425 if fromauth
!= sender
:
426 fromauth
= 'From: %s\n\n' % fromauth
431 version_str
= ' %s' % options
.version
436 prefix_str
= options
.prefix
+ ' '
438 confprefix
= config
.get('stgit.mail.prefix')
440 prefix_str
= confprefix
+ ' '
444 total_nr_str
= str(total_nr
)
445 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
446 if not options
.unrelated
and total_nr
> 1:
447 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
451 diff
= git
.diff(rev1
= git_id(crt_series
, '%s^' % patch
),
452 rev2
= git_id(crt_series
, '%s' % patch
),
453 diff_flags
= options
.diff_flags
)
454 tmpl_dict
= {'patch': patch
,
456 # for backward template compatibility
457 'maintainer': sender
,
458 'shortdescr': short_descr
,
459 'longdescr': long_descr
,
460 # for backward template compatibility
463 'diffstat': gitlib
.diffstat(diff
),
464 # for backward template compatibility
466 'version': version_str
,
467 'prefix': prefix_str
,
468 'patchnr': patch_nr_str
,
469 'totalnr': total_nr_str
,
470 'number': number_str
,
471 'fromauth': fromauth
,
472 'authname': authname
,
473 'authemail': authemail
,
474 'authdate': p
.get_authdate(),
475 'commname': commname
,
476 'commemail': commemail
}
478 for key
in tmpl_dict
:
479 if not tmpl_dict
[key
]:
483 msg_string
= tmpl % tmpl_dict
484 except KeyError, err
:
485 raise CmdException
, 'Unknown patch template variable: %s' \
488 raise CmdException
, 'Only "%(name)s" variables are ' \
489 'supported in the patch template'
491 if options
.edit_patches
:
492 msg_string
= __edit_message(msg_string
)
494 # The Python email message
496 msg
= email
.message_from_string(msg_string
)
497 except Exception, ex
:
498 raise CmdException
, 'template parsing error: %s' % str
(ex
)
501 extra_cc
= __get_signers_list(descr
)
505 __build_address_headers(msg
, options
, extra_cc
)
506 __build_extra_headers(msg
, msg_id
, ref_id
)
507 __encode_message(msg
)
511 def func(parser
, options
, args
):
512 """Send the patches by e-mail using the patchmail.tmpl file as
515 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
517 applied
= crt_series
.get_applied()
522 unapplied
= crt_series
.get_unapplied()
523 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
525 raise CmdException
, 'Incorrect options. Unknown patches to send'
527 out
.start('Checking the validity of the patches')
529 if crt_series
.empty_patch(p
):
530 raise CmdException
, 'Cannot send empty patch "%s"' % p
533 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
534 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
535 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
537 if (smtppassword
and not smtpuser
):
538 raise CmdException
, 'SMTP password supplied, username needed'
539 if (smtpusetls
and not smtpuser
):
540 raise CmdException
, 'SMTP over TLS requested, username needed'
541 if (smtpuser
and not smtppassword
):
542 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
544 total_nr
= len(patches
)
546 raise CmdException
, 'No patches to send'
549 if options
.noreply
or options
.unrelated
:
550 raise CmdException
, \
551 '--refid option not allowed with --noreply or --unrelated'
552 ref_id
= options
.refid
556 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
558 # send the cover message (if any)
559 if options
.cover
or options
.edit_cover
:
560 if options
.unrelated
:
561 raise CmdException
, 'cover sending not allowed with --unrelated'
563 # find the template file
565 tmpl
= file(options
.cover
).read()
567 tmpl
= templates
.get_template('covermail.tmpl')
569 raise CmdException
, 'No cover message template file found'
571 msg_id
= email
.Utils
.make_msgid('stgit')
572 msg
= __build_cover(tmpl
, patches
, msg_id
, options
)
573 from_addr
, to_addr_list
= __parse_addresses(msg
)
575 msg_string
= msg
.as_string(options
.mbox
)
577 # subsequent e-mails are seen as replies to the first one
578 if not options
.noreply
:
582 out
.stdout_raw(msg_string
+ '\n')
584 out
.start('Sending the cover message')
585 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
586 sleep
, smtpuser
, smtppassword
, smtpusetls
)
591 tmpl
= file(options
.template
).read()
594 tmpl
= templates
.get_template('mailattch.tmpl')
596 tmpl
= templates
.get_template('patchmail.tmpl')
598 raise CmdException
, 'No e-mail template file found'
600 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
601 msg_id
= email
.Utils
.make_msgid('stgit')
602 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
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
and not options
.unrelated
and not ref_id
:
613 out
.stdout_raw(msg_string
+ '\n')
615 out
.start('Sending patch "%s"' % p
)
616 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
617 sleep
, smtpuser
, smtppassword
, smtpusetls
)