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
:
157 sender
= str(git
.author())
160 raise CmdException
, 'unknown sender details'
162 return address_or_alias(sender
)
164 def __parse_addresses(msg
):
165 """Return a two elements tuple: (from, [to])
167 def __addr_list(msg
, header
):
168 return [name_addr
[1] for name_addr
in
169 email
.Utils
.getaddresses(msg
.get_all(header
, []))]
171 from_addr_list
= __addr_list(msg
, 'From')
172 if len(from_addr_list
) == 0:
173 raise CmdException
, 'No "From" address'
175 to_addr_list
= __addr_list(msg
, 'To') + __addr_list(msg
, 'Cc') \
176 + __addr_list(msg
, 'Bcc')
177 if len(to_addr_list
) == 0:
178 raise CmdException
, 'No "To/Cc/Bcc" addresses'
180 return (from_addr_list
[0], to_addr_list
)
182 def __send_message_sendmail(sendmail
, msg
):
183 """Send the message using the sendmail command.
185 cmd
= sendmail
.split()
186 Run(*cmd
).raw_input(msg
).discard_output()
188 def __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
,
189 smtpuser
, smtppassword
, use_tls
):
190 """Send the message using the given SMTP server
193 s
= smtplib
.SMTP(smtpserver
)
194 except Exception, err
:
195 raise CmdException
, str(err
)
199 if smtpuser
and smtppassword
:
202 if not hasattr(socket
, 'ssl'):
203 raise CmdException
, "cannot use TLS - no SSL support in Python"
206 s
.login(smtpuser
, smtppassword
)
208 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
210 print "mail server refused delivery for the following recipients: %s" % result
211 except Exception, err
:
212 raise CmdException
, str(err
)
216 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
,
217 sleep
, smtpuser
, smtppassword
, use_tls
):
218 """Message sending dispatcher.
220 if smtpserver
.startswith('/'):
221 # Use the sendmail tool
222 __send_message_sendmail(smtpserver
, msg
)
224 # Use the SMTP server (we have host and port information)
225 __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
,
226 smtpuser
, smtppassword
, use_tls
)
227 # give recipients a chance of receiving patches in the correct order
230 def __build_address_headers(msg
, options
, extra_cc
= []):
231 """Build the address headers and check existing headers in the
234 def __replace_header(header
, addr
):
236 crt_addr
= msg
[header
]
240 msg
[header
] = address_or_alias(', '.join([crt_addr
, addr
]))
242 msg
[header
] = address_or_alias(addr
)
248 autobcc
= config
.get('stgit.autobcc') or ''
251 to_addr
= ', '.join(options
.to
)
253 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
254 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
256 cc_addr
= ', '.join(extra_cc
)
258 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
262 __replace_header('To', to_addr
)
263 __replace_header('Cc', cc_addr
)
264 __replace_header('Bcc', bcc_addr
)
266 def __get_signers_list(msg
):
267 """Return the address list generated from signed-off-by and
268 acked-by lines in the message.
272 r
= re
.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re
.I
)
273 for line
in msg
.split('\n'):
276 addr_list
.append(m
.expand('\g<2>'))
280 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
281 """Build extra email headers and encoding
284 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
285 msg
['Message-ID'] = msg_id
287 # make sure the ref id has the angle brackets
288 ref_id
= '<%s>' % ref_id
.strip(' \t\n<>')
289 msg
['In-Reply-To'] = ref_id
290 msg
['References'] = ref_id
291 msg
['User-Agent'] = 'StGit/%s' % version
.version
293 def __encode_message(msg
):
294 # 7 or 8 bit encoding
295 charset
= email
.Charset
.Charset('utf-8')
296 charset
.body_encoding
= None
299 for header
, value
in msg
.items():
301 for word
in value
.split(' '):
303 uword
= unicode(word
, 'utf-8')
304 except UnicodeDecodeError:
305 # maybe we should try a different encoding or report
306 # the error. At the moment, we just ignore it
308 words
.append(email
.Header
.Header(uword
).encode())
309 new_val
= ' '.join(words
)
310 msg
.replace_header(header
, new_val
)
312 # encode the body and set the MIME and encoding headers
313 if msg
.is_multipart():
314 for p
in msg
.get_payload():
315 p
.set_charset(charset
)
317 msg
.set_charset(charset
)
319 def __edit_message(msg
):
320 fname
= '.stgitmail.txt'
322 # create the initial file
329 # read the message back
336 def __build_cover(tmpl
, patches
, msg_id
, options
):
337 """Build the cover message (series description) to be sent via SMTP
339 sender
= __get_sender()
342 version_str
= ' %s' % options
.version
347 prefix_str
= options
.prefix
+ ' '
349 confprefix
= config
.get('stgit.mail.prefix')
351 prefix_str
= confprefix
+ ' '
355 total_nr_str
= str(len(patches
))
356 patch_nr_str
= '0'.zfill(len(total_nr_str
))
358 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
362 tmpl_dict
= {'sender': sender
,
363 # for backward template compatibility
364 'maintainer': sender
,
365 # for backward template compatibility
367 # for backward template compatibility
369 'version': version_str
,
370 'prefix': prefix_str
,
371 'patchnr': patch_nr_str
,
372 'totalnr': total_nr_str
,
373 'number': number_str
,
374 'shortlog': stack
.shortlog(crt_series
.get_patch(p
)
376 'diffstat': gitlib
.diffstat(git
.diff(
377 rev1
= git_id(crt_series
, '%s^' % patches
[0]),
378 rev2
= git_id(crt_series
, '%s' % patches
[-1])))}
381 msg_string
= tmpl % tmpl_dict
382 except KeyError, err
:
383 raise CmdException
, 'Unknown patch template variable: %s' \
386 raise CmdException
, 'Only "%(name)s" variables are ' \
387 'supported in the patch template'
389 if options
.edit_cover
:
390 msg_string
= __edit_message(msg_string
)
392 # The Python email message
394 msg
= email
.message_from_string(msg_string
)
395 except Exception, ex
:
396 raise CmdException
, 'template parsing error: %s' % str
(ex
)
398 __build_address_headers(msg
, options
)
399 __build_extra_headers(msg
, msg_id
, options
.refid
)
400 __encode_message(msg
)
404 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
405 """Build the message to be sent via SMTP
407 p
= crt_series
.get_patch(patch
)
409 if p
.get_description():
410 descr
= p
.get_description().strip()
412 # provide a place holder and force the edit message option on
413 descr
= '<empty message>'
414 options
.edit_patches
= True
416 descr_lines
= descr
.split('\n')
417 short_descr
= descr_lines
[0].strip()
418 long_descr
= '\n'.join(l
.rstrip() for l
in descr_lines
[1:]).lstrip('\n')
420 authname
= p
.get_authname();
421 authemail
= p
.get_authemail();
422 commname
= p
.get_commname();
423 commemail
= p
.get_commemail();
425 sender
= __get_sender()
427 fromauth
= '%s <%s>' %
(authname
, authemail
)
428 if fromauth
!= sender
:
429 fromauth
= 'From: %s\n\n' % fromauth
434 version_str
= ' %s' % options
.version
439 prefix_str
= options
.prefix
+ ' '
441 confprefix
= config
.get('stgit.mail.prefix')
443 prefix_str
= confprefix
+ ' '
447 total_nr_str
= str(total_nr
)
448 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
449 if not options
.unrelated
and total_nr
> 1:
450 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
454 diff
= git
.diff(rev1
= git_id(crt_series
, '%s^' % patch
),
455 rev2
= git_id(crt_series
, '%s' % patch
),
456 diff_flags
= options
.diff_flags
)
457 tmpl_dict
= {'patch': patch
,
459 # for backward template compatibility
460 'maintainer': sender
,
461 'shortdescr': short_descr
,
462 'longdescr': long_descr
,
463 # for backward template compatibility
466 'diffstat': gitlib
.diffstat(diff
),
467 # for backward template compatibility
469 'version': version_str
,
470 'prefix': prefix_str
,
471 'patchnr': patch_nr_str
,
472 'totalnr': total_nr_str
,
473 'number': number_str
,
474 'fromauth': fromauth
,
475 'authname': authname
,
476 'authemail': authemail
,
477 'authdate': p
.get_authdate(),
478 'commname': commname
,
479 'commemail': commemail
}
481 for key
in tmpl_dict
:
482 if not tmpl_dict
[key
]:
486 msg_string
= tmpl % tmpl_dict
487 except KeyError, err
:
488 raise CmdException
, 'Unknown patch template variable: %s' \
491 raise CmdException
, 'Only "%(name)s" variables are ' \
492 'supported in the patch template'
494 if options
.edit_patches
:
495 msg_string
= __edit_message(msg_string
)
497 # The Python email message
499 msg
= email
.message_from_string(msg_string
)
500 except Exception, ex
:
501 raise CmdException
, 'template parsing error: %s' % str
(ex
)
504 extra_cc
= __get_signers_list(descr
)
508 __build_address_headers(msg
, options
, extra_cc
)
509 __build_extra_headers(msg
, msg_id
, ref_id
)
510 __encode_message(msg
)
514 def func(parser
, options
, args
):
515 """Send the patches by e-mail using the patchmail.tmpl file as
518 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
520 applied
= crt_series
.get_applied()
525 unapplied
= crt_series
.get_unapplied()
526 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
528 raise CmdException
, 'Incorrect options. Unknown patches to send'
530 out
.start('Checking the validity of the patches')
532 if crt_series
.empty_patch(p
):
533 raise CmdException
, 'Cannot send empty patch "%s"' % p
536 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
537 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
538 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
540 if (smtppassword
and not smtpuser
):
541 raise CmdException
, 'SMTP password supplied, username needed'
542 if (smtpusetls
and not smtpuser
):
543 raise CmdException
, 'SMTP over TLS requested, username needed'
544 if (smtpuser
and not smtppassword
):
545 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
547 total_nr
= len(patches
)
549 raise CmdException
, 'No patches to send'
552 if options
.noreply
or options
.unrelated
:
553 raise CmdException
, \
554 '--refid option not allowed with --noreply or --unrelated'
555 ref_id
= options
.refid
559 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
561 # send the cover message (if any)
562 if options
.cover
or options
.edit_cover
:
563 if options
.unrelated
:
564 raise CmdException
, 'cover sending not allowed with --unrelated'
566 # find the template file
568 tmpl
= file(options
.cover
).read()
570 tmpl
= templates
.get_template('covermail.tmpl')
572 raise CmdException
, 'No cover message template file found'
574 msg_id
= email
.Utils
.make_msgid('stgit')
575 msg
= __build_cover(tmpl
, patches
, msg_id
, options
)
576 from_addr
, to_addr_list
= __parse_addresses(msg
)
578 msg_string
= msg
.as_string(options
.mbox
)
580 # subsequent e-mails are seen as replies to the first one
581 if not options
.noreply
:
585 out
.stdout_raw(msg_string
+ '\n')
587 out
.start('Sending the cover message')
588 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
589 sleep
, smtpuser
, smtppassword
, smtpusetls
)
594 tmpl
= file(options
.template
).read()
597 tmpl
= templates
.get_template('mailattch.tmpl')
599 tmpl
= templates
.get_template('patchmail.tmpl')
601 raise CmdException
, 'No e-mail template file found'
603 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
604 msg_id
= email
.Utils
.make_msgid('stgit')
605 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
607 from_addr
, to_addr_list
= __parse_addresses(msg
)
609 msg_string
= msg
.as_string(options
.mbox
)
611 # subsequent e-mails are seen as replies to the first one
612 if not options
.noreply
and not options
.unrelated
and not ref_id
:
616 out
.stdout_raw(msg_string
+ '\n')
618 out
.start('Sending patch "%s"' % p
)
619 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
620 sleep
, smtpuser
, smtppassword
, smtpusetls
)