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
28 help = 'Send a patch or series of patches by e-mail'
29 usage
= [' [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. This option can also be an
34 absolute path to 'sendmail' followed by command line arguments.
36 The From address and the e-mail format are generated from the template
37 file passed as argument to '--template' (defaulting to
38 '.git/patchmail.tmpl' or '~/.stgit/templates/patchmail.tmpl' or
39 '/usr/share/stgit/templates/patchmail.tmpl'). A patch can be sent as
40 attachment using the --attach option in which case the
41 'mailattch.tmpl' template will be used instead of 'patchmail.tmpl'.
43 The To/Cc/Bcc addresses can either be added to the template file or
44 passed via the corresponding command line options. They can be e-mail
45 addresses or aliases which are automatically expanded to the values
46 stored in the [mail "alias"] section of GIT configuration files.
48 A preamble e-mail can be sent using the '--cover' and/or
49 '--edit-cover' options. The first allows the user to specify a file to
50 be used as a template. The latter option will invoke the editor on the
51 specified file (defaulting to '.git/covermail.tmpl' or
52 '~/.stgit/templates/covermail.tmpl' or
53 '/usr/share/stgit/templates/covermail.tmpl').
55 All the subsequent e-mails appear as replies to the first e-mail sent
56 (either the preamble or the first patch). E-mails can be seen as
57 replies to a different e-mail by using the '--refid' option.
59 SMTP authentication is also possible with '--smtp-user' and
60 '--smtp-password' options, also available as configuration settings:
61 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
62 '--smtp-tls' option and 'smtptls' setting.
64 The following variables are accepted by both the preamble and the
65 patch e-mail templates:
67 %(diffstat)s - diff statistics
68 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
69 %(patchnr)s - patch number
70 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
71 %(totalnr)s - total number of patches to be sent
72 %(version)s - ' version' string passed on the command line (or empty)
74 In addition to the common variables, the preamble e-mail template
75 accepts the following:
77 %(shortlog)s - first line of each patch description, listed by author
79 In addition to the common variables, the patch e-mail template accepts
82 %(authdate)s - patch creation date
83 %(authemail)s - author's email
84 %(authname)s - author's name
85 %(commemail)s - committer's e-mail
86 %(commname)s - committer's name
87 %(diff)s - unified diff of the patch
88 %(fromauth)s - 'From: author\n\n' if different from sender
89 %(longdescr)s - the rest of the patch description, after the first line
90 %(patch)s - patch name
91 %(prefix)s - 'prefix ' string passed on the command line
92 %(shortdescr)s - the first line of the patch description"""
95 opt('-a', '--all', action
= 'store_true',
96 short
= 'E-mail all the applied patches'),
97 opt('--to', action
= 'append',
98 short
= 'Add TO to the To: list'),
99 opt('--cc', action
= 'append',
100 short
= 'Add CC to the Cc: list'),
101 opt('--bcc', action
= 'append',
102 short
= 'Add BCC to the Bcc: list'),
103 opt('--auto', action
= 'store_true',
104 short
= 'Automatically cc the patch signers'),
105 opt('--noreply', action
= 'store_true',
106 short
= 'Do not send subsequent messages as replies'),
107 opt('--unrelated', action
= 'store_true',
108 short
= 'Send patches without sequence numbering'),
109 opt('--attach', action
= 'store_true',
110 short
= 'Send a patch as attachment'),
111 opt('-v', '--version', metavar
= 'VERSION',
112 short
= 'Add VERSION to the [PATCH ...] prefix'),
113 opt('--prefix', metavar
= 'PREFIX',
114 short
= 'Add PREFIX to the [... PATCH ...] prefix'),
115 opt('-t', '--template', metavar
= 'FILE',
116 short
= 'Use FILE as the message template'),
117 opt('-c', '--cover', metavar
= 'FILE',
118 short
= 'Send FILE as the cover message'),
119 opt('-e', '--edit-cover', action
= 'store_true',
120 short
= 'Edit the cover message before sending'),
121 opt('-E', '--edit-patches', action
= 'store_true',
122 short
= 'Edit each patch before sending'),
123 opt('-s', '--sleep', type = 'int', metavar
= 'SECONDS',
124 short
= 'Sleep for SECONDS between e-mails sending'),
126 short
= 'Use REFID as the reference id'),
127 opt('--smtp-server', metavar
= 'HOST[:PORT] or "/path/to/sendmail -t -i"',
128 short
= 'SMTP server or command to use for sending mail'),
129 opt('-u', '--smtp-user', metavar
= 'USER',
130 short
= 'Username for SMTP authentication'),
131 opt('-p', '--smtp-password', metavar
= 'PASSWORD',
132 short
= 'Password for SMTP authentication'),
133 opt('-T', '--smtp-tls', action
= 'store_true',
134 short
= 'Use SMTP with TLS encryption'),
135 opt('-b', '--branch',
136 short
= 'Use BRANCH instead of the default branch'),
137 opt('-m', '--mbox', action
= 'store_true',
138 short
= 'Generate an mbox file instead of sending')
139 ] + argparse
.diff_opts_option()
141 directory
= DirectoryHasRepository()
144 """Return the 'authname <authemail>' string as read from the
147 sender
=config
.get('stgit.sender')
150 sender
= str(git
.user())
151 except git
.GitException
:
152 sender
= str(git
.author())
155 raise CmdException
, 'unknown sender details'
157 return address_or_alias(sender
)
159 def __parse_addresses(msg
):
160 """Return a two elements tuple: (from, [to])
162 def __addr_list(msg
, header
):
163 return [name_addr
[1] for name_addr
in
164 email
.Utils
.getaddresses(msg
.get_all(header
, []))]
166 from_addr_list
= __addr_list(msg
, 'From')
167 if len(from_addr_list
) == 0:
168 raise CmdException
, 'No "From" address'
170 to_addr_list
= __addr_list(msg
, 'To') + __addr_list(msg
, 'Cc') \
171 + __addr_list(msg
, 'Bcc')
172 if len(to_addr_list
) == 0:
173 raise CmdException
, 'No "To/Cc/Bcc" addresses'
175 return (from_addr_list
[0], to_addr_list
)
177 def __send_message_sendmail(sendmail
, msg
):
178 """Send the message using the sendmail command.
180 cmd
= sendmail
.split()
181 Run(*cmd
).raw_input(msg
).discard_output()
183 def __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
,
184 smtpuser
, smtppassword
, use_tls
):
185 """Send the message using the given SMTP server
188 s
= smtplib
.SMTP(smtpserver
)
189 except Exception, err
:
190 raise CmdException
, str(err
)
194 if smtpuser
and smtppassword
:
197 if not hasattr(socket
, 'ssl'):
198 raise CmdException
, "cannot use TLS - no SSL support in Python"
201 s
.login(smtpuser
, smtppassword
)
203 result
= s
.sendmail(from_addr
, to_addr_list
, msg
)
205 print "mail server refused delivery for the following recipients: %s" % result
206 except Exception, err
:
207 raise CmdException
, str(err
)
211 def __send_message(smtpserver
, from_addr
, to_addr_list
, msg
,
212 sleep
, smtpuser
, smtppassword
, use_tls
):
213 """Message sending dispatcher.
215 if smtpserver
.startswith('/'):
216 # Use the sendmail tool
217 __send_message_sendmail(smtpserver
, msg
)
219 # Use the SMTP server (we have host and port information)
220 __send_message_smtp(smtpserver
, from_addr
, to_addr_list
, msg
,
221 smtpuser
, smtppassword
, use_tls
)
222 # give recipients a chance of receiving patches in the correct order
225 def __build_address_headers(msg
, options
, extra_cc
= []):
226 """Build the address headers and check existing headers in the
229 def __replace_header(header
, addr
):
231 crt_addr
= msg
[header
]
235 msg
[header
] = address_or_alias(', '.join([crt_addr
, addr
]))
237 msg
[header
] = address_or_alias(addr
)
243 autobcc
= config
.get('stgit.autobcc') or ''
246 to_addr
= ', '.join(options
.to
)
248 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
249 cc_addr
= ', '.join(options
.cc
+ extra_cc
)
251 cc_addr
= ', '.join(extra_cc
)
253 bcc_addr
= ', '.join(options
.bcc
+ [autobcc
])
257 __replace_header('To', to_addr
)
258 __replace_header('Cc', cc_addr
)
259 __replace_header('Bcc', bcc_addr
)
261 def __get_signers_list(msg
):
262 """Return the address list generated from signed-off-by and
263 acked-by lines in the message.
267 r
= re
.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re
.I
)
268 for line
in msg
.split('\n'):
271 addr_list
.append(m
.expand('\g<2>'))
275 def __build_extra_headers(msg
, msg_id
, ref_id
= None):
276 """Build extra email headers and encoding
279 msg
['Date'] = email
.Utils
.formatdate(localtime
= True)
280 msg
['Message-ID'] = msg_id
282 # make sure the ref id has the angle brackets
283 ref_id
= '<%s>' % ref_id
.strip(' \t\n<>')
284 msg
['In-Reply-To'] = ref_id
285 msg
['References'] = ref_id
286 msg
['User-Agent'] = 'StGIT/%s' % version
.version
288 def __encode_message(msg
):
289 # 7 or 8 bit encoding
290 charset
= email
.Charset
.Charset('utf-8')
291 charset
.body_encoding
= None
294 for header
, value
in msg
.items():
296 for word
in value
.split(' '):
298 uword
= unicode(word
, 'utf-8')
299 except UnicodeDecodeError:
300 # maybe we should try a different encoding or report
301 # the error. At the moment, we just ignore it
303 words
.append(email
.Header
.Header(uword
).encode())
304 new_val
= ' '.join(words
)
305 msg
.replace_header(header
, new_val
)
307 # encode the body and set the MIME and encoding headers
308 if msg
.is_multipart():
309 for p
in msg
.get_payload():
310 p
.set_charset(charset
)
312 msg
.set_charset(charset
)
314 def __edit_message(msg
):
315 fname
= '.stgitmail.txt'
317 # create the initial file
324 # read the message back
331 def __build_cover(tmpl
, patches
, msg_id
, options
):
332 """Build the cover message (series description) to be sent via SMTP
334 sender
= __get_sender()
337 version_str
= ' %s' % options
.version
342 prefix_str
= options
.prefix
+ ' '
344 confprefix
= config
.get('stgit.mail.prefix')
346 prefix_str
= confprefix
+ ' '
350 total_nr_str
= str(len(patches
))
351 patch_nr_str
= '0'.zfill(len(total_nr_str
))
353 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
357 tmpl_dict
= {'sender': sender
,
358 # for backward template compatibility
359 'maintainer': sender
,
360 # for backward template compatibility
362 # for backward template compatibility
364 'version': version_str
,
365 'prefix': prefix_str
,
366 'patchnr': patch_nr_str
,
367 'totalnr': total_nr_str
,
368 'number': number_str
,
369 'shortlog': stack
.shortlog(crt_series
.get_patch(p
)
371 'diffstat': git
.diffstat(git
.diff(
372 rev1
= git_id(crt_series
, '%s^' % patches
[0]),
373 rev2
= git_id(crt_series
, '%s' % patches
[-1])))}
376 msg_string
= tmpl % tmpl_dict
377 except KeyError, err
:
378 raise CmdException
, 'Unknown patch template variable: %s' \
381 raise CmdException
, 'Only "%(name)s" variables are ' \
382 'supported in the patch template'
384 if options
.edit_cover
:
385 msg_string
= __edit_message(msg_string
)
387 # The Python email message
389 msg
= email
.message_from_string(msg_string
)
390 except Exception, ex
:
391 raise CmdException
, 'template parsing error: %s' % str
(ex
)
393 __build_address_headers(msg
, options
)
394 __build_extra_headers(msg
, msg_id
, options
.refid
)
395 __encode_message(msg
)
399 def __build_message(tmpl
, patch
, patch_nr
, total_nr
, msg_id
, ref_id
, options
):
400 """Build the message to be sent via SMTP
402 p
= crt_series
.get_patch(patch
)
404 if p
.get_description():
405 descr
= p
.get_description().strip()
407 # provide a place holder and force the edit message option on
408 descr
= '<empty message>'
409 options
.edit_patches
= True
411 descr_lines
= descr
.split('\n')
412 short_descr
= descr_lines
[0].strip()
413 long_descr
= '\n'.join(l
.rstrip() for l
in descr_lines
[1:]).lstrip('\n')
415 authname
= p
.get_authname();
416 authemail
= p
.get_authemail();
417 commname
= p
.get_commname();
418 commemail
= p
.get_commemail();
420 sender
= __get_sender()
422 fromauth
= '%s <%s>' %
(authname
, authemail
)
423 if fromauth
!= sender
:
424 fromauth
= 'From: %s\n\n' % fromauth
429 version_str
= ' %s' % options
.version
434 prefix_str
= options
.prefix
+ ' '
436 confprefix
= config
.get('stgit.mail.prefix')
438 prefix_str
= confprefix
+ ' '
442 total_nr_str
= str(total_nr
)
443 patch_nr_str
= str(patch_nr
).zfill(len(total_nr_str
))
444 if not options
.unrelated
and total_nr
> 1:
445 number_str
= ' %s/%s' %
(patch_nr_str
, total_nr_str
)
449 diff
= git
.diff(rev1
= git_id(crt_series
, '%s^' % patch
),
450 rev2
= git_id(crt_series
, '%s' % patch
),
451 diff_flags
= options
.diff_flags
)
452 tmpl_dict
= {'patch': patch
,
454 # for backward template compatibility
455 'maintainer': sender
,
456 'shortdescr': short_descr
,
457 'longdescr': long_descr
,
458 # for backward template compatibility
461 'diffstat': git
.diffstat(diff
),
462 # for backward template compatibility
464 'version': version_str
,
465 'prefix': prefix_str
,
466 'patchnr': patch_nr_str
,
467 'totalnr': total_nr_str
,
468 'number': number_str
,
469 'fromauth': fromauth
,
470 'authname': authname
,
471 'authemail': authemail
,
472 'authdate': p
.get_authdate(),
473 'commname': commname
,
474 'commemail': commemail
}
476 for key
in tmpl_dict
:
477 if not tmpl_dict
[key
]:
481 msg_string
= tmpl % tmpl_dict
482 except KeyError, err
:
483 raise CmdException
, 'Unknown patch template variable: %s' \
486 raise CmdException
, 'Only "%(name)s" variables are ' \
487 'supported in the patch template'
489 if options
.edit_patches
:
490 msg_string
= __edit_message(msg_string
)
492 # The Python email message
494 msg
= email
.message_from_string(msg_string
)
495 except Exception, ex
:
496 raise CmdException
, 'template parsing error: %s' % str
(ex
)
499 extra_cc
= __get_signers_list(descr
)
503 __build_address_headers(msg
, options
, extra_cc
)
504 __build_extra_headers(msg
, msg_id
, ref_id
)
505 __encode_message(msg
)
509 def func(parser
, options
, args
):
510 """Send the patches by e-mail using the patchmail.tmpl file as
513 smtpserver
= options
.smtp_server
or config
.get('stgit.smtpserver')
515 applied
= crt_series
.get_applied()
520 unapplied
= crt_series
.get_unapplied()
521 patches
= parse_patches(args
, applied
+ unapplied
, len(applied
))
523 raise CmdException
, 'Incorrect options. Unknown patches to send'
525 out
.start('Checking the validity of the patches')
527 if crt_series
.empty_patch(p
):
528 raise CmdException
, 'Cannot send empty patch "%s"' % p
531 smtppassword
= options
.smtp_password
or config
.get('stgit.smtppassword')
532 smtpuser
= options
.smtp_user
or config
.get('stgit.smtpuser')
533 smtpusetls
= options
.smtp_tls
or config
.get('stgit.smtptls') == 'yes'
535 if (smtppassword
and not smtpuser
):
536 raise CmdException
, 'SMTP password supplied, username needed'
537 if (smtpusetls
and not smtpuser
):
538 raise CmdException
, 'SMTP over TLS requested, username needed'
539 if (smtpuser
and not smtppassword
):
540 smtppassword
= getpass
.getpass("Please enter SMTP password: ")
542 total_nr
= len(patches
)
544 raise CmdException
, 'No patches to send'
547 if options
.noreply
or options
.unrelated
:
548 raise CmdException
, \
549 '--refid option not allowed with --noreply or --unrelated'
550 ref_id
= options
.refid
554 sleep
= options
.sleep
or config
.getint('stgit.smtpdelay')
556 # send the cover message (if any)
557 if options
.cover
or options
.edit_cover
:
558 if options
.unrelated
:
559 raise CmdException
, 'cover sending not allowed with --unrelated'
561 # find the template file
563 tmpl
= file(options
.cover
).read()
565 tmpl
= templates
.get_template('covermail.tmpl')
567 raise CmdException
, 'No cover message template file found'
569 msg_id
= email
.Utils
.make_msgid('stgit')
570 msg
= __build_cover(tmpl
, patches
, msg_id
, options
)
571 from_addr
, to_addr_list
= __parse_addresses(msg
)
573 msg_string
= msg
.as_string(options
.mbox
)
575 # subsequent e-mails are seen as replies to the first one
576 if not options
.noreply
:
580 out
.stdout_raw(msg_string
+ '\n')
582 out
.start('Sending the cover message')
583 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
584 sleep
, smtpuser
, smtppassword
, smtpusetls
)
589 tmpl
= file(options
.template
).read()
592 tmpl
= templates
.get_template('mailattch.tmpl')
594 tmpl
= templates
.get_template('patchmail.tmpl')
596 raise CmdException
, 'No e-mail template file found'
598 for (p
, patch_nr
) in zip(patches
, range(1, len(patches
) + 1)):
599 msg_id
= email
.Utils
.make_msgid('stgit')
600 msg
= __build_message(tmpl
, p
, patch_nr
, total_nr
, msg_id
, ref_id
,
602 from_addr
, to_addr_list
= __parse_addresses(msg
)
604 msg_string
= msg
.as_string(options
.mbox
)
606 # subsequent e-mails are seen as replies to the first one
607 if not options
.noreply
and not options
.unrelated
and not ref_id
:
611 out
.stdout_raw(msg_string
+ '\n')
613 out
.start('Sending patch "%s"' % p
)
614 __send_message(smtpserver
, from_addr
, to_addr_list
, msg_string
,
615 sleep
, smtpuser
, smtppassword
, smtpusetls
)