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
import stack
, git
, version
, templates
25 from stgit
.config
import config
28 help = 'send a patch or series of patches by e-mail'
29 usage
= """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
31 Send a patch or a range of patches by e-mail using the SMTP server
32 specified by the 'stgit.smtpserver' configuration option, or the
33 '--smtp-server' command line option. The From address and the e-mail
34 format are generated from the template file passed as argument to
35 '--template' (defaulting to '.git/patchmail.tmpl' or
36 '~/.stgit/templates/patchmail.tmpl' or
37 '/usr/share/stgit/templates/patchmail.tmpl').
39 The To/Cc/Bcc addresses can either be added to the template file or
40 passed via the corresponding command line options. They can be e-mail
41 addresses or aliases which are automatically expanded to the values
42 stored in the [mail "alias"] section of GIT configuration files.
44 A preamble e-mail can be sent using the '--cover' and/or
45 '--edit-cover' options. The first allows the user to specify a file to
46 be used as a template. The latter option will invoke the editor on the
47 specified file (defaulting to '.git/covermail.tmpl' or
48 '~/.stgit/templates/covermail.tmpl' or
49 '/usr/share/stgit/templates/covermail.tmpl').
51 All the subsequent e-mails appear as replies to the first e-mail sent
52 (either the preamble or the first patch). E-mails can be seen as
53 replies to a different e-mail by using the '--refid' option.
55 SMTP authentication is also possible with '--smtp-user' and
56 '--smtp-password' options, also available as configuration settings:
57 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
58 '--smtp-tls' option and 'smtptls' setting.
60 The patch e-mail template accepts the following variables:
62 %(patch)s - patch name
63 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
64 %(shortdescr)s - the first line of the patch description
65 %(longdescr)s - the rest of the patch description, after the first line
66 %(diff)s - unified diff of the patch
67 %(diffstat)s - diff statistics
68 %(version)s - ' version' string passed on the command line (or empty)
69 %(prefix)s - 'prefix ' string passed on the command line
70 %(patchnr)s - patch number
71 %(totalnr)s - total number of patches to be sent
72 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
73 %(fromauth)s - 'From: author\\n\\n' if different from sender
74 %(authname)s - author's name
75 %(authemail)s - author's email
76 %(authdate)s - patch creation date
77 %(commname)s - committer's name
78 %(commemail)s - committer's e-mail
80 For the preamble e-mail template, only the %(sender)s, %(version)s,
81 %(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
83 options
= [make_option('-a', '--all',
84 help = 'e-mail all the applied patches',
85 action
= 'store_true'),
87 help = 'add TO to the To: list',
90 help = 'add CC to the Cc: list',
93 help = 'add BCC to the Bcc: list',
96 help = 'automatically cc the patch signers',
97 action
= 'store_true'),
98 make_option('--noreply',
99 help = 'do not send subsequent messages as replies',
100 action
= 'store_true'),
101 make_option('--unrelated',
102 help = 'send patches without sequence numbering',
103 action
= 'store_true'),
104 make_option('-v', '--version', metavar
= 'VERSION',
105 help = 'add VERSION to the [PATCH ...] prefix'),
106 make_option('--prefix', metavar
= 'PREFIX',
107 help = 'add PREFIX to the [... PATCH ...] prefix'),
108 make_option('-t', '--template', metavar
= 'FILE',
109 help = 'use FILE as the message template'),
110 make_option('-c', '--cover', metavar
= 'FILE',
111 help = 'send FILE as the cover message'),
112 make_option('-e', '--edit-cover',
113 help = 'edit the cover message before sending',
114 action
= 'store_true'),
115 make_option('-E', '--edit-patches',
116 help = 'edit each patch before sending',
117 action
= 'store_true'),
118 make_option('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
119 help = 'sleep for SECONDS between e-mails sending'),
120 make_option('--refid',
121 help = 'use REFID as the reference id'),
122 make_option('--smtp-server', metavar
= 'HOST[:PORT]',
123 help = 'SMTP server to use for sending mail'),
124 make_option('-u', '--smtp-user', metavar
= 'USER',
125 help = 'username for SMTP authentication'),
126 make_option('-p', '--smtp-password', metavar
= 'PASSWORD',
127 help = 'username for SMTP authentication'),
128 make_option('-T', '--smtp-tls',
129 help = 'use SMTP with TLS encryption',
130 action
= 'store_true'),
131 make_option('-b', '--branch',
132 help = 'use BRANCH instead of the default one'),
133 make_option('-O', '--diff-opts',
134 help = 'options to pass to git-diff'),
135 make_option('-m', '--mbox',
136 help = 'generate an mbox file instead of sending',
137 action
= 'store_true')]
141 """Return the 'authname <authemail>' string as read from the
144 sender
=config
.get('stgit.sender')
147 sender
= str(git
.user())
148 except git
.GitException
:
149 sender
= str(git
.author())
152 raise CmdException
, 'unknown sender details'
154 return address_or_alias(sender
)
156 def __parse_addresses(msg
):
157 """Return a two elements tuple: (from, [to])
159 def __addr_list(msg
, header
):
160 return [name_addr
[1] for name_addr
in
161 email
.Utils
.getaddresses(msg
.get_all(header
, []))]
163 from_addr_list
= __addr_list(msg
, 'From')
164 if len(from_addr_list
) == 0:
165 raise CmdException
, 'No "From" address'
167 to_addr_list
= __addr_list(msg
, 'To') + __addr_list(msg
, 'Cc') \
168 + __addr_list(msg
, 'Bcc')
169 if len(to_addr_list
) == 0:
170 raise CmdException
, 'No "To/Cc/Bcc" addresses'
172 return (from_addr_list
[0], to_addr_list
)
174 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
, sleep
,
175 smtpuser
, smtppassword
, use_tls
):
176 """Send the message using the given SMTP server
179 s
= smtplib
.SMTP(smtpserver
)
180 except Exception, err
:
181 raise CmdException
, str(err
)
185 if smtpuser
and smtppassword
:
188 if not hasattr(socket
, 'ssl'):
189 raise CmdException
, "cannot use TLS - no SSL support in Python"
192 s
.login(smtpuser
, smtppassword
)
194 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
196 print "mail server refused delivery for the following recipients: %s" % result
197 # give recipients a chance of receiving patches in the correct order
199 except Exception, err
:
200 raise CmdException
, str(err
)
204 def __build_address_headers(msg
, options
, extra_cc
= []):
205 """Build the address headers and check existing headers in the
208 def __replace_header(header
, addr
):
210 crt_addr
= msg
[header
]
214 msg
[header
] = address_or_alias(', '.join([crt_addr
, addr
]))
216 msg
[header
] = address_or_alias(addr
)
222 autobcc
= config
.get('stgit.autobcc') or ''
225 to_addr
= ', '.join(options
.to
)
227 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
229 cc_addr
= ', '.join(extra_cc
)
231 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
235 __replace_header('To', to_addr
)
236 __replace_header('Cc', cc_addr
)
237 __replace_header('Bcc', bcc_addr
)
239 def __get_signers_list(msg
):
240 """Return the address list generated from signed-off-by and
241 acked-by lines in the message.
245 r
= re
.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re
.I
)
246 for line
in msg
.split('\n'):
249 addr_list
.append(m
.expand('\g<2>'))
253 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
254 """Build extra email headers and encoding
257 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
258 msg
['Message-ID'] = msg_id
260 msg
['In-Reply-To'] = ref_id
261 msg
['References'] = ref_id
262 msg
['User-Agent'] = 'StGIT/%s' % version
.version
264 def __encode_message(msg
):
265 # 7 or 8 bit encoding
266 charset
= email
.Charset
.Charset('utf-8')
267 charset
.body_encoding
= None
270 for header
, value
in msg
.items():
272 for word
in value
.split(' '):
274 uword
= unicode(word
, 'utf-8')
275 except UnicodeDecodeError:
276 # maybe we should try a different encoding or report
277 # the error. At the moment, we just ignore it
279 words
.append(email
.Header
.Header(uword
).encode())
280 new_val
= ' '.join(words
)
281 msg
.replace_header(header
, new_val
)
283 # encode the body and set the MIME and encoding headers
284 msg
.set_charset(charset
)
286 def __edit_message(msg
):
287 fname
= '.stgitmail.txt'
289 # create the initial file
296 # read the message back
303 def __build_cover(tmpl
, total_nr
, msg_id
, options
):
304 """Build the cover message (series description) to be sent via SMTP
306 sender
= __get_sender()
309 version_str
= ' %s' % options
.version
314 prefix_str
= options
.prefix
+ ' '
316 confprefix
= config
.get('stgit.mail.prefix')
318 prefix_str
= confprefix
+ ' '
322 total_nr_str
= str(total_nr
)
323 patch_nr_str
= '0'.zfill(len(total_nr_str
))
325 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
329 tmpl_dict
= {'sender': sender
,
330 # for backward template compatibility
331 'maintainer': sender
,
332 # for backward template compatibility
334 # for backward template compatibility
336 'version': version_str
,
337 'prefix': prefix_str
,
338 'patchnr': patch_nr_str
,
339 'totalnr': total_nr_str
,
340 'number': number_str
}
343 msg_string
= tmpl % tmpl_dict
344 except KeyError, err
:
345 raise CmdException
, 'Unknown patch template variable: %s' \
348 raise CmdException
, 'Only "%(name)s" variables are ' \
349 'supported in the patch template'
351 if options
.edit_cover
:
352 msg_string
= __edit_message(msg_string
)
354 # The Python email message
356 msg
= email
.message_from_string(msg_string
)
357 except Exception, ex
:
358 raise CmdException
, 'template parsing error: %s' % str
(ex
)
360 __build_address_headers(msg
, options
)
361 __build_extra_headers(msg
, msg_id
, options
.refid
)
362 __encode_message(msg
)
366 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
367 """Build the message to be sent via SMTP
369 p
= crt_series
.get_patch(patch
)
371 descr
= p
.get_description().strip()
372 descr_lines
= descr
.split('\n')
374 short_descr
= descr_lines
[0].rstrip()
375 long_descr
= '\n'.join(descr_lines
[1:]).lstrip()
377 authname
= p
.get_authname();
378 authemail
= p
.get_authemail();
379 commname
= p
.get_commname();
380 commemail
= p
.get_commemail();
382 sender
= __get_sender()
384 fromauth
= '%s <%s>' %
(authname
, authemail
)
385 if fromauth
!= sender
:
386 fromauth
= 'From: %s\n\n' % fromauth
391 version_str
= ' %s' % options
.version
396 prefix_str
= options
.prefix
+ ' '
398 confprefix
= config
.get('stgit.mail.prefix')
400 prefix_str
= confprefix
+ ' '
404 if options
.diff_opts
:
405 diff_flags
= options
.diff_opts
.split()
409 total_nr_str
= str(total_nr
)
410 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
411 if not options
.unrelated
and total_nr
> 1:
412 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
416 tmpl_dict
= {'patch': patch
,
418 # for backward template compatibility
419 'maintainer': sender
,
420 'shortdescr': short_descr
,
421 'longdescr': long_descr
,
422 # for backward template compatibility
424 'diff': git
.diff(rev1
= git_id('%s//bottom' % patch
),
425 rev2
= git_id('%s//top' % patch
),
426 diff_flags
= diff_flags
),
427 'diffstat': git
.diffstat(rev1
= git_id('%s//bottom'%patch
),
428 rev2
= git_id('%s//top' % patch
)),
429 # for backward template compatibility
431 'version': version_str
,
432 'prefix': prefix_str
,
433 'patchnr': patch_nr_str
,
434 'totalnr': total_nr_str
,
435 'number': number_str
,
436 'fromauth': fromauth
,
437 'authname': authname
,
438 'authemail': authemail
,
439 'authdate': p
.get_authdate(),
440 'commname': commname
,
441 'commemail': commemail
}
443 for key
in tmpl_dict
:
444 if not tmpl_dict
[key
]:
448 msg_string
= tmpl % tmpl_dict
449 except KeyError, err
:
450 raise CmdException
, 'Unknown patch template variable: %s' \
453 raise CmdException
, 'Only "%(name)s" variables are ' \
454 'supported in the patch template'
456 if options
.edit_patches
:
457 msg_string
= __edit_message(msg_string
)
459 # The Python email message
461 msg
= email
.message_from_string(msg_string
)
462 except Exception, ex
:
463 raise CmdException
, 'template parsing error: %s' % str
(ex
)
466 extra_cc
= __get_signers_list(descr
)
470 __build_address_headers(msg
, options
, extra_cc
)
471 __build_extra_headers(msg
, msg_id
, ref_id
)
472 __encode_message(msg
)
476 def func(parser
, options
, args
):
477 """Send the patches by e-mail using the patchmail.tmpl file as
480 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
482 applied
= crt_series
.get_applied()
487 unapplied
= crt_series
.get_unapplied()
488 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
490 raise CmdException
, 'Incorrect options. Unknown patches to send'
492 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
493 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
494 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
496 if (smtppassword
and not smtpuser
):
497 raise CmdException
, 'SMTP password supplied, username needed'
498 if (smtpusetls
and not smtpuser
):
499 raise CmdException
, 'SMTP over TLS requested, username needed'
500 if (smtpuser
and not smtppassword
):
501 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
503 total_nr
= len(patches
)
505 raise CmdException
, 'No patches to send'
508 if options
.noreply
or options
.unrelated
:
509 raise CmdException
, \
510 '--refid option not allowed with --noreply or --unrelated'
511 ref_id
= options
.refid
515 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
517 # send the cover message (if any)
518 if options
.cover
or options
.edit_cover
:
519 if options
.unrelated
:
520 raise CmdException
, 'cover sending not allowed with --unrelated'
522 # find the template file
524 tmpl
= file(options
.cover
).read()
526 tmpl
= templates
.get_template('covermail.tmpl')
528 raise CmdException
, 'No cover message template file found'
530 msg_id
= email
.Utils
.make_msgid('stgit')
531 msg
= __build_cover(tmpl
, total_nr
, msg_id
, options
)
532 from_addr
, to_addr_list
= __parse_addresses(msg
)
534 msg_string
= msg
.as_string(options
.mbox
)
536 # subsequent e-mails are seen as replies to the first one
537 if not options
.noreply
:
541 out
.stdout_raw(msg_string
+ '\n')
543 out
.start('Sending the cover message')
544 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
545 sleep
, smtpuser
, smtppassword
, smtpusetls
)
550 tmpl
= file(options
.template
).read()
552 tmpl
= templates
.get_template('patchmail.tmpl')
554 raise CmdException
, 'No e-mail template file found'
556 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
557 msg_id
= email
.Utils
.make_msgid('stgit')
558 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
560 from_addr
, to_addr_list
= __parse_addresses(msg
)
562 msg_string
= msg
.as_string(options
.mbox
)
564 # subsequent e-mails are seen as replies to the first one
565 if not options
.noreply
and not options
.unrelated
and not ref_id
:
569 out
.stdout_raw(msg_string
+ '\n')
571 out
.start('Sending patch "%s"' % p
)
572 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
573 sleep
, smtpuser
, smtppassword
, smtpusetls
)