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 following variables are accepted by both the preamble and the
62 patch e-mail templates:
64 %(diffstat)s - diff statistics
65 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
66 %(patchnr)s - patch number
67 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
68 %(totalnr)s - total number of patches to be sent
69 %(version)s - ' version' string passed on the command line (or empty)
71 In addition to the common variables, the preamble e-mail template
72 accepts the following:
74 %(shortlog)s - first line of each patch description, listed by author
76 In addition to the common variables, the patch e-mail template accepts
79 %(authdate)s - patch creation date
80 %(authemail)s - author's email
81 %(authname)s - author's name
82 %(commemail)s - committer's e-mail
83 %(commname)s - committer's name
84 %(diff)s - unified diff of the patch
85 %(fromauth)s - 'From: author\\n\\n' if different from sender
86 %(longdescr)s - the rest of the patch description, after the first line
87 %(patch)s - patch name
88 %(prefix)s - 'prefix ' string passed on the command line
89 %(shortdescr)s - the first line of the patch description"""
91 options
= [make_option('-a', '--all',
92 help = 'e-mail all the applied patches',
93 action
= 'store_true'),
95 help = 'add TO to the To: list',
98 help = 'add CC to the Cc: list',
101 help = 'add BCC to the Bcc: list',
103 make_option('--auto',
104 help = 'automatically cc the patch signers',
105 action
= 'store_true'),
106 make_option('--noreply',
107 help = 'do not send subsequent messages as replies',
108 action
= 'store_true'),
109 make_option('--unrelated',
110 help = 'send patches without sequence numbering',
111 action
= 'store_true'),
112 make_option('-v', '--version', metavar
= 'VERSION',
113 help = 'add VERSION to the [PATCH ...] prefix'),
114 make_option('--prefix', metavar
= 'PREFIX',
115 help = 'add PREFIX to the [... PATCH ...] prefix'),
116 make_option('-t', '--template', metavar
= 'FILE',
117 help = 'use FILE as the message template'),
118 make_option('-c', '--cover', metavar
= 'FILE',
119 help = 'send FILE as the cover message'),
120 make_option('-e', '--edit-cover',
121 help = 'edit the cover message before sending',
122 action
= 'store_true'),
123 make_option('-E', '--edit-patches',
124 help = 'edit each patch before sending',
125 action
= 'store_true'),
126 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
127 help = 'sleep for SECONDS between e-mails sending'),
128 make_option('--refid',
129 help = 'use REFID as the reference id'),
130 make_option('--smtp-server', metavar
= 'HOST[:PORT]',
131 help = 'SMTP server to use for sending mail'),
132 make_option('-u', '--smtp-user', metavar
= 'USER',
133 help = 'username for SMTP authentication'),
134 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
135 help = 'username for SMTP authentication'),
136 make_option('-T', '--smtp-tls',
137 help = 'use SMTP with TLS encryption',
138 action
= 'store_true'),
139 make_option('-b', '--branch',
140 help = 'use BRANCH instead of the default one'),
141 make_option('-O', '--diff-opts',
142 help = 'options to pass to git-diff'),
143 make_option('-m', '--mbox',
144 help = 'generate an mbox file instead of sending',
145 action
= 'store_true')]
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(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
183 smtpuser
, smtppassword
, use_tls
):
184 """Send the message using the given SMTP server
187 s
= smtplib
.SMTP(smtpserver
)
188 except Exception, err
:
189 raise CmdException
, str(err
)
193 if smtpuser
and smtppassword
:
196 if not hasattr(socket
, 'ssl'):
197 raise CmdException
, "cannot use TLS - no SSL support in Python"
200 s
.login(smtpuser
, smtppassword
)
202 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
204 print "mail server refused delivery for the following recipients: %s" % result
205 # give recipients a chance of receiving patches in the correct order
207 except Exception, err
:
208 raise CmdException
, str(err
)
212 def __build_address_headers(msg
, options
, extra_cc
= []):
213 """Build the address headers and check existing headers in the
216 def __replace_header(header
, addr
):
218 crt_addr
= msg
[header
]
222 msg
[header
] = address_or_alias(', '.join([crt_addr
, addr
]))
224 msg
[header
] = address_or_alias(addr
)
230 autobcc
= config
.get('stgit.autobcc') or ''
233 to_addr
= ', '.join(options
.to
)
235 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
237 cc_addr
= ', '.join(extra_cc
)
239 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
243 __replace_header('To', to_addr
)
244 __replace_header('Cc', cc_addr
)
245 __replace_header('Bcc', bcc_addr
)
247 def __get_signers_list(msg
):
248 """Return the address list generated from signed-off-by and
249 acked-by lines in the message.
253 r
= re
.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re
.I
)
254 for line
in msg
.split('\n'):
257 addr_list
.append(m
.expand('\g<2>'))
261 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
262 """Build extra email headers and encoding
265 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
266 msg
['Message-ID'] = msg_id
268 msg
['In-Reply-To'] = ref_id
269 msg
['References'] = ref_id
270 msg
['User-Agent'] = 'StGIT/%s' % version
.version
272 def __encode_message(msg
):
273 # 7 or 8 bit encoding
274 charset
= email
.Charset
.Charset('utf-8')
275 charset
.body_encoding
= None
278 for header
, value
in msg
.items():
280 for word
in value
.split(' '):
282 uword
= unicode(word
, 'utf-8')
283 except UnicodeDecodeError:
284 # maybe we should try a different encoding or report
285 # the error. At the moment, we just ignore it
287 words
.append(email
.Header
.Header(uword
).encode())
288 new_val
= ' '.join(words
)
289 msg
.replace_header(header
, new_val
)
291 # encode the body and set the MIME and encoding headers
292 msg
.set_charset(charset
)
294 def __edit_message(msg
):
295 fname
= '.stgitmail.txt'
297 # create the initial file
304 # read the message back
311 def __build_cover(tmpl
, patches
, msg_id
, options
):
312 """Build the cover message (series description) to be sent via SMTP
314 sender
= __get_sender()
317 version_str
= ' %s' % options
.version
322 prefix_str
= options
.prefix
+ ' '
324 confprefix
= config
.get('stgit.mail.prefix')
326 prefix_str
= confprefix
+ ' '
330 total_nr_str
= str(len(patches
))
331 patch_nr_str
= '0'.zfill(len(total_nr_str
))
333 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
337 tmpl_dict
= {'sender': sender
,
338 # for backward template compatibility
339 'maintainer': sender
,
340 # for backward template compatibility
342 # for backward template compatibility
344 'version': version_str
,
345 'prefix': prefix_str
,
346 'patchnr': patch_nr_str
,
347 'totalnr': total_nr_str
,
348 'number': number_str
,
349 'shortlog': stack
.shortlog(crt_series
.get_patch(p
)
351 'diffstat': git
.diffstat(
352 rev1
= git_id('%s//bottom' % patches
[0]),
353 rev2
= git_id('%s//top' % patches
[-1]))}
356 msg_string
= tmpl % tmpl_dict
357 except KeyError, err
:
358 raise CmdException
, 'Unknown patch template variable: %s' \
361 raise CmdException
, 'Only "%(name)s" variables are ' \
362 'supported in the patch template'
364 if options
.edit_cover
:
365 msg_string
= __edit_message(msg_string
)
367 # The Python email message
369 msg
= email
.message_from_string(msg_string
)
370 except Exception, ex
:
371 raise CmdException
, 'template parsing error: %s' % str
(ex
)
373 __build_address_headers(msg
, options
)
374 __build_extra_headers(msg
, msg_id
, options
.refid
)
375 __encode_message(msg
)
379 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
380 """Build the message to be sent via SMTP
382 p
= crt_series
.get_patch(patch
)
384 descr
= p
.get_description().strip()
385 descr_lines
= descr
.split('\n')
387 short_descr
= descr_lines
[0].rstrip()
388 long_descr
= '\n'.join(descr_lines
[1:]).lstrip()
390 authname
= p
.get_authname();
391 authemail
= p
.get_authemail();
392 commname
= p
.get_commname();
393 commemail
= p
.get_commemail();
395 sender
= __get_sender()
397 fromauth
= '%s <%s>' %
(authname
, authemail
)
398 if fromauth
!= sender
:
399 fromauth
= 'From: %s\n\n' % fromauth
404 version_str
= ' %s' % options
.version
409 prefix_str
= options
.prefix
+ ' '
411 confprefix
= config
.get('stgit.mail.prefix')
413 prefix_str
= confprefix
+ ' '
417 if options
.diff_opts
:
418 diff_flags
= options
.diff_opts
.split()
422 total_nr_str
= str(total_nr
)
423 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
424 if not options
.unrelated
and total_nr
> 1:
425 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
429 tmpl_dict
= {'patch': patch
,
431 # for backward template compatibility
432 'maintainer': sender
,
433 'shortdescr': short_descr
,
434 'longdescr': long_descr
,
435 # for backward template compatibility
437 'diff': git
.diff(rev1
= git_id('%s//bottom' % patch
),
438 rev2
= git_id('%s//top' % patch
),
439 diff_flags
= diff_flags
),
440 'diffstat': git
.diffstat(rev1
= git_id('%s//bottom'%patch
),
441 rev2
= git_id('%s//top' % patch
)),
442 # for backward template compatibility
444 'version': version_str
,
445 'prefix': prefix_str
,
446 'patchnr': patch_nr_str
,
447 'totalnr': total_nr_str
,
448 'number': number_str
,
449 'fromauth': fromauth
,
450 'authname': authname
,
451 'authemail': authemail
,
452 'authdate': p
.get_authdate(),
453 'commname': commname
,
454 'commemail': commemail
}
456 for key
in tmpl_dict
:
457 if not tmpl_dict
[key
]:
461 msg_string
= tmpl % tmpl_dict
462 except KeyError, err
:
463 raise CmdException
, 'Unknown patch template variable: %s' \
466 raise CmdException
, 'Only "%(name)s" variables are ' \
467 'supported in the patch template'
469 if options
.edit_patches
:
470 msg_string
= __edit_message(msg_string
)
472 # The Python email message
474 msg
= email
.message_from_string(msg_string
)
475 except Exception, ex
:
476 raise CmdException
, 'template parsing error: %s' % str
(ex
)
479 extra_cc
= __get_signers_list(descr
)
483 __build_address_headers(msg
, options
, extra_cc
)
484 __build_extra_headers(msg
, msg_id
, ref_id
)
485 __encode_message(msg
)
489 def func(parser
, options
, args
):
490 """Send the patches by e-mail using the patchmail.tmpl file as
493 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
495 applied
= crt_series
.get_applied()
500 unapplied
= crt_series
.get_unapplied()
501 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
503 raise CmdException
, 'Incorrect options. Unknown patches to send'
505 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
506 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
507 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
509 if (smtppassword
and not smtpuser
):
510 raise CmdException
, 'SMTP password supplied, username needed'
511 if (smtpusetls
and not smtpuser
):
512 raise CmdException
, 'SMTP over TLS requested, username needed'
513 if (smtpuser
and not smtppassword
):
514 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
516 total_nr
= len(patches
)
518 raise CmdException
, 'No patches to send'
521 if options
.noreply
or options
.unrelated
:
522 raise CmdException
, \
523 '--refid option not allowed with --noreply or --unrelated'
524 ref_id
= options
.refid
528 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
530 # send the cover message (if any)
531 if options
.cover
or options
.edit_cover
:
532 if options
.unrelated
:
533 raise CmdException
, 'cover sending not allowed with --unrelated'
535 # find the template file
537 tmpl
= file(options
.cover
).read()
539 tmpl
= templates
.get_template('covermail.tmpl')
541 raise CmdException
, 'No cover message template file found'
543 msg_id
= email
.Utils
.make_msgid('stgit')
544 msg
= __build_cover(tmpl
, patches
, msg_id
, options
)
545 from_addr
, to_addr_list
= __parse_addresses(msg
)
547 msg_string
= msg
.as_string(options
.mbox
)
549 # subsequent e-mails are seen as replies to the first one
550 if not options
.noreply
:
554 out
.stdout_raw(msg_string
+ '\n')
556 out
.start('Sending the cover message')
557 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
558 sleep
, smtpuser
, smtppassword
, smtpusetls
)
563 tmpl
= file(options
.template
).read()
565 tmpl
= templates
.get_template('patchmail.tmpl')
567 raise CmdException
, 'No e-mail template file found'
569 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
570 msg_id
= email
.Utils
.make_msgid('stgit')
571 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
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
and not options
.unrelated
and not ref_id
:
582 out
.stdout_raw(msg_string
+ '\n')
584 out
.start('Sending patch "%s"' % p
)
585 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
586 sleep
, smtpuser
, smtppassword
, smtpusetls
)