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 optparse
import OptionParser
, make_option
22 from stgit
.commands
.common
import *
23 from stgit
.utils
import *
24 from stgit
.out
import *
25 from stgit
import stack
, git
, version
, templates
26 from stgit
.config
import config
29 help = 'send a patch or series of patches by e-mail'
30 usage
= """%prog [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. The From address and the e-mail
35 format are generated from the template file passed as argument to
36 '--template' (defaulting to '.git/patchmail.tmpl' or
37 '~/.stgit/templates/patchmail.tmpl' or
38 '/usr/share/stgit/templates/patchmail.tmpl').
40 The To/Cc/Bcc addresses can either be added to the template file or
41 passed via the corresponding command line options. They can be e-mail
42 addresses or aliases which are automatically expanded to the values
43 stored in the [mail "alias"] section of GIT configuration files.
45 A preamble e-mail can be sent using the '--cover' and/or
46 '--edit-cover' options. The first allows the user to specify a file to
47 be used as a template. The latter option will invoke the editor on the
48 specified file (defaulting to '.git/covermail.tmpl' or
49 '~/.stgit/templates/covermail.tmpl' or
50 '/usr/share/stgit/templates/covermail.tmpl').
52 All the subsequent e-mails appear as replies to the first e-mail sent
53 (either the preamble or the first patch). E-mails can be seen as
54 replies to a different e-mail by using the '--refid' option.
56 SMTP authentication is also possible with '--smtp-user' and
57 '--smtp-password' options, also available as configuration settings:
58 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
59 '--smtp-tls' option and 'smtptls' setting.
61 The patch e-mail template accepts the following variables:
63 %(patch)s - patch name
64 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
65 %(shortdescr)s - the first line of the patch description
66 %(longdescr)s - the rest of the patch description, after the first line
67 %(diff)s - unified diff of the patch
68 %(diffstat)s - diff statistics
69 %(version)s - ' version' string passed on the command line (or empty)
70 %(prefix)s - 'prefix ' string passed on the command line
71 %(patchnr)s - patch number
72 %(totalnr)s - total number of patches to be sent
73 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
74 %(fromauth)s - 'From: author\\n\\n' if different from sender
75 %(authname)s - author's name
76 %(authemail)s - author's email
77 %(authdate)s - patch creation date
78 %(commname)s - committer's name
79 %(commemail)s - committer's e-mail
81 For the preamble e-mail template, only the %(diffstat)s, %(sender)s,
82 %(version)s, %(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
84 options
= [make_option('-a', '--all',
85 help = 'e-mail all the applied patches',
86 action
= 'store_true'),
88 help = 'add TO to the To: list',
91 help = 'add CC to the Cc: list',
94 help = 'add BCC to the Bcc: list',
97 help = 'automatically cc the patch signers',
98 action
= 'store_true'),
99 make_option('--noreply',
100 help = 'do not send subsequent messages as replies',
101 action
= 'store_true'),
102 make_option('--unrelated',
103 help = 'send patches without sequence numbering',
104 action
= 'store_true'),
105 make_option('-v', '--version', metavar
= 'VERSION',
106 help = 'add VERSION to the [PATCH ...] prefix'),
107 make_option('--prefix', metavar
= 'PREFIX',
108 help = 'add PREFIX to the [... PATCH ...] prefix'),
109 make_option('-t', '--template', metavar
= 'FILE',
110 help = 'use FILE as the message template'),
111 make_option('-c', '--cover', metavar
= 'FILE',
112 help = 'send FILE as the cover message'),
113 make_option('-e', '--edit-cover',
114 help = 'edit the cover message before sending',
115 action
= 'store_true'),
116 make_option('-E', '--edit-patches',
117 help = 'edit each patch before sending',
118 action
= 'store_true'),
119 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
120 help = 'sleep for SECONDS between e-mails sending'),
121 make_option('--refid',
122 help = 'use REFID as the reference id'),
123 make_option('--smtp-server', metavar
= 'HOST[:PORT]',
124 help = 'SMTP server to use for sending mail'),
125 make_option('-u', '--smtp-user', metavar
= 'USER',
126 help = 'username for SMTP authentication'),
127 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
128 help = 'username for SMTP authentication'),
129 make_option('-T', '--smtp-tls',
130 help = 'use SMTP with TLS encryption',
131 action
= 'store_true'),
132 make_option('-b', '--branch',
133 help = 'use BRANCH instead of the default one'),
134 make_option('-O', '--diff-opts',
135 help = 'options to pass to git-diff'),
136 make_option('-m', '--mbox',
137 help = 'generate an mbox file instead of sending',
138 action
= 'store_true')]
142 """Return the 'authname <authemail>' string as read from the
145 sender
=config
.get('stgit.sender')
148 sender
= str(git
.user())
149 except git
.GitException
:
150 sender
= str(git
.author())
153 raise CmdException
, 'unknown sender details'
155 return address_or_alias(sender
)
157 def __parse_addresses(msg
):
158 """Return a two elements tuple: (from, [to])
160 def __addr_list(msg
, header
):
161 return [name_addr
[1] for name_addr
in
162 email
.Utils
.getaddresses(msg
.get_all(header
, []))]
164 from_addr_list
= __addr_list(msg
, 'From')
165 if len(from_addr_list
) == 0:
166 raise CmdException
, 'No "From" address'
168 to_addr_list
= __addr_list(msg
, 'To') + __addr_list(msg
, 'Cc') \
169 + __addr_list(msg
, 'Bcc')
170 if len(to_addr_list
) == 0:
171 raise CmdException
, 'No "To/Cc/Bcc" addresses'
173 return (from_addr_list
[0], to_addr_list
)
175 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
176 smtpuser
, smtppassword
, use_tls
):
177 """Send the message using the given SMTP server
180 s
= smtplib
.SMTP(smtpserver
)
181 except Exception, err
:
182 raise CmdException
, str(err
)
186 if smtpuser
and smtppassword
:
189 if not hasattr(socket
, 'ssl'):
190 raise CmdException
, "cannot use TLS - no SSL support in Python"
193 s
.login(smtpuser
, smtppassword
)
195 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
197 print "mail server refused delivery for the following recipients: %s" % result
198 # give recipients a chance of receiving patches in the correct order
200 except Exception, err
:
201 raise CmdException
, str(err
)
205 def __build_address_headers(msg
, options
, extra_cc
= []):
206 """Build the address headers and check existing headers in the
209 def __replace_header(header
, addr
):
211 crt_addr
= msg
[header
]
215 msg
[header
] = address_or_alias(', '.join([crt_addr
, addr
]))
217 msg
[header
] = address_or_alias(addr
)
223 autobcc
= config
.get('stgit.autobcc') or ''
226 to_addr
= ', '.join(options
.to
)
228 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
230 cc_addr
= ', '.join(extra_cc
)
232 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
236 __replace_header('To', to_addr
)
237 __replace_header('Cc', cc_addr
)
238 __replace_header('Bcc', bcc_addr
)
240 def __get_signers_list(msg
):
241 """Return the address list generated from signed-off-by and
242 acked-by lines in the message.
246 r
= re
.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re
.I
)
247 for line
in msg
.split('\n'):
250 addr_list
.append(m
.expand('\g<2>'))
254 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
255 """Build extra email headers and encoding
258 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
259 msg
['Message-ID'] = msg_id
261 msg
['In-Reply-To'] = ref_id
262 msg
['References'] = ref_id
263 msg
['User-Agent'] = 'StGIT/%s' % version
.version
265 def __encode_message(msg
):
266 # 7 or 8 bit encoding
267 charset
= email
.Charset
.Charset('utf-8')
268 charset
.body_encoding
= None
271 for header
, value
in msg
.items():
273 for word
in value
.split(' '):
275 uword
= unicode(word
, 'utf-8')
276 except UnicodeDecodeError:
277 # maybe we should try a different encoding or report
278 # the error. At the moment, we just ignore it
280 words
.append(email
.Header
.Header(uword
).encode())
281 new_val
= ' '.join(words
)
282 msg
.replace_header(header
, new_val
)
284 # encode the body and set the MIME and encoding headers
285 msg
.set_charset(charset
)
287 def __edit_message(msg
):
288 fname
= '.stgitmail.txt'
290 # create the initial file
297 # read the message back
304 def __build_cover(tmpl
, patches
, msg_id
, options
):
305 """Build the cover message (series description) to be sent via SMTP
307 sender
= __get_sender()
310 version_str
= ' %s' % options
.version
315 prefix_str
= options
.prefix
+ ' '
317 confprefix
= config
.get('stgit.mail.prefix')
319 prefix_str
= confprefix
+ ' '
323 total_nr_str
= str(len(patches
))
324 patch_nr_str
= '0'.zfill(len(total_nr_str
))
326 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
330 tmpl_dict
= {'sender': sender
,
331 # for backward template compatibility
332 'maintainer': sender
,
333 # for backward template compatibility
335 # for backward template compatibility
337 'version': version_str
,
338 'prefix': prefix_str
,
339 'patchnr': patch_nr_str
,
340 'totalnr': total_nr_str
,
341 'number': number_str
,
342 'diffstat': git
.diffstat(
343 rev1
= git_id('%s//bottom' % patches
[0]),
344 rev2
= git_id('%s//top' % patches
[-1]))}
347 msg_string
= tmpl % tmpl_dict
348 except KeyError, err
:
349 raise CmdException
, 'Unknown patch template variable: %s' \
352 raise CmdException
, 'Only "%(name)s" variables are ' \
353 'supported in the patch template'
355 if options
.edit_cover
:
356 msg_string
= __edit_message(msg_string
)
358 # The Python email message
360 msg
= email
.message_from_string(msg_string
)
361 except Exception, ex
:
362 raise CmdException
, 'template parsing error: %s' % str
(ex
)
364 __build_address_headers(msg
, options
)
365 __build_extra_headers(msg
, msg_id
, options
.refid
)
366 __encode_message(msg
)
370 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
371 """Build the message to be sent via SMTP
373 p
= crt_series
.get_patch(patch
)
375 descr
= p
.get_description().strip()
376 descr_lines
= descr
.split('\n')
378 short_descr
= descr_lines
[0].rstrip()
379 long_descr
= '\n'.join(descr_lines
[1:]).lstrip()
381 authname
= p
.get_authname();
382 authemail
= p
.get_authemail();
383 commname
= p
.get_commname();
384 commemail
= p
.get_commemail();
386 sender
= __get_sender()
388 fromauth
= '%s <%s>' %
(authname
, authemail
)
389 if fromauth
!= sender
:
390 fromauth
= 'From: %s\n\n' % fromauth
395 version_str
= ' %s' % options
.version
400 prefix_str
= options
.prefix
+ ' '
402 confprefix
= config
.get('stgit.mail.prefix')
404 prefix_str
= confprefix
+ ' '
408 if options
.diff_opts
:
409 diff_flags
= options
.diff_opts
.split()
413 total_nr_str
= str(total_nr
)
414 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
415 if not options
.unrelated
and total_nr
> 1:
416 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
420 tmpl_dict
= {'patch': patch
,
422 # for backward template compatibility
423 'maintainer': sender
,
424 'shortdescr': short_descr
,
425 'longdescr': long_descr
,
426 # for backward template compatibility
428 'diff': git
.diff(rev1
= git_id('%s//bottom' % patch
),
429 rev2
= git_id('%s//top' % patch
),
430 diff_flags
= diff_flags
),
431 'diffstat': git
.diffstat(rev1
= git_id('%s//bottom'%patch
),
432 rev2
= git_id('%s//top' % patch
)),
433 # for backward template compatibility
435 'version': version_str
,
436 'prefix': prefix_str
,
437 'patchnr': patch_nr_str
,
438 'totalnr': total_nr_str
,
439 'number': number_str
,
440 'fromauth': fromauth
,
441 'authname': authname
,
442 'authemail': authemail
,
443 'authdate': p
.get_authdate(),
444 'commname': commname
,
445 'commemail': commemail
}
447 for key
in tmpl_dict
:
448 if not tmpl_dict
[key
]:
452 msg_string
= tmpl % tmpl_dict
453 except KeyError, err
:
454 raise CmdException
, 'Unknown patch template variable: %s' \
457 raise CmdException
, 'Only "%(name)s" variables are ' \
458 'supported in the patch template'
460 if options
.edit_patches
:
461 msg_string
= __edit_message(msg_string
)
463 # The Python email message
465 msg
= email
.message_from_string(msg_string
)
466 except Exception, ex
:
467 raise CmdException
, 'template parsing error: %s' % str
(ex
)
470 extra_cc
= __get_signers_list(descr
)
474 __build_address_headers(msg
, options
, extra_cc
)
475 __build_extra_headers(msg
, msg_id
, ref_id
)
476 __encode_message(msg
)
480 def func(parser
, options
, args
):
481 """Send the patches by e-mail using the patchmail.tmpl file as
484 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
486 applied
= crt_series
.get_applied()
491 unapplied
= crt_series
.get_unapplied()
492 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
494 raise CmdException
, 'Incorrect options. Unknown patches to send'
496 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
497 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
498 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
500 if (smtppassword
and not smtpuser
):
501 raise CmdException
, 'SMTP password supplied, username needed'
502 if (smtpusetls
and not smtpuser
):
503 raise CmdException
, 'SMTP over TLS requested, username needed'
504 if (smtpuser
and not smtppassword
):
505 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
507 total_nr
= len(patches
)
509 raise CmdException
, 'No patches to send'
512 if options
.noreply
or options
.unrelated
:
513 raise CmdException
, \
514 '--refid option not allowed with --noreply or --unrelated'
515 ref_id
= options
.refid
519 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
521 # send the cover message (if any)
522 if options
.cover
or options
.edit_cover
:
523 if options
.unrelated
:
524 raise CmdException
, 'cover sending not allowed with --unrelated'
526 # find the template file
528 tmpl
= file(options
.cover
).read()
530 tmpl
= templates
.get_template('covermail.tmpl')
532 raise CmdException
, 'No cover message template file found'
534 msg_id
= email
.Utils
.make_msgid('stgit')
535 msg
= __build_cover(tmpl
, patches
, msg_id
, options
)
536 from_addr
, to_addr_list
= __parse_addresses(msg
)
538 msg_string
= msg
.as_string(options
.mbox
)
540 # subsequent e-mails are seen as replies to the first one
541 if not options
.noreply
:
545 out
.stdout_raw(msg_string
+ '\n')
547 out
.start('Sending the cover message')
548 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
549 sleep
, smtpuser
, smtppassword
, smtpusetls
)
554 tmpl
= file(options
.template
).read()
556 tmpl
= templates
.get_template('patchmail.tmpl')
558 raise CmdException
, 'No e-mail template file found'
560 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
561 msg_id
= email
.Utils
.make_msgid('stgit')
562 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
564 from_addr
, to_addr_list
= __parse_addresses(msg
)
566 msg_string
= msg
.as_string(options
.mbox
)
568 # subsequent e-mails are seen as replies to the first one
569 if not options
.noreply
and not options
.unrelated
and not ref_id
:
573 out
.stdout_raw(msg_string
+ '\n')
575 out
.start('Sending patch "%s"' % p
)
576 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
577 sleep
, smtpuser
, smtppassword
, smtpusetls
)