7ed5c2799ec56b24cffc0687df49b467e47ff233
[stgit] / stgit / commands / mail.py
1 __copyright__ = """
2 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
3
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.
7
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.
12
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
16 """
17
18 import sys, os, re, time, datetime, socket, smtplib
19 import email, email.Utils, email.Header
20 from optparse import OptionParser, make_option
21
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
26
27
28 help = 'send a patch or series of patches by e-mail'
29 usage = """%prog [options] [<patch1>] [<patch2>] [<patch3>..<patch4>]
30
31 Send a patch or a range of patches by e-mail using the 'smtpserver'
32 configuration option. The From address and the e-mail format are
33 generated from the template file passed as argument to '--template'
34 (defaulting to '.git/patchmail.tmpl' or
35 '~/.stgit/templates/patchmail.tmpl' or
36 '/usr/share/stgit/templates/patchmail.tmpl').
37
38 The To/Cc/Bcc addresses can either be added to the template file or
39 passed via the corresponding command line options. They can be e-mail
40 addresses or aliases which are automatically expanded to the values
41 stored in the [mail "alias"] section of GIT configuration files.
42
43 A preamble e-mail can be sent using the '--cover' and/or
44 '--edit-cover' options. The first allows the user to specify a file to
45 be used as a template. The latter option will invoke the editor on the
46 specified file (defaulting to '.git/covermail.tmpl' or
47 '~/.stgit/templates/covermail.tmpl' or
48 '/usr/share/stgit/templates/covermail.tmpl').
49
50 All the subsequent e-mails appear as replies to the first e-mail sent
51 (either the preamble or the first patch). E-mails can be seen as
52 replies to a different e-mail by using the '--refid' option.
53
54 SMTP authentication is also possible with '--smtp-user' and
55 '--smtp-password' options, also available as configuration settings:
56 'smtpuser' and 'smtppassword'. TLS encryption can be enabled by
57 '--smtp-tls' option and 'smtptls' setting.
58
59 The patch e-mail template accepts the following variables:
60
61 %(patch)s - patch name
62 %(sender)s - 'sender' or 'authname <authemail>' as per the config file
63 %(shortdescr)s - the first line of the patch description
64 %(longdescr)s - the rest of the patch description, after the first line
65 %(diff)s - unified diff of the patch
66 %(diffstat)s - diff statistics
67 %(version)s - ' version' string passed on the command line (or empty)
68 %(prefix)s - 'prefix ' string passed on the command line
69 %(patchnr)s - patch number
70 %(totalnr)s - total number of patches to be sent
71 %(number)s - empty if only one patch is sent or ' patchnr/totalnr'
72 %(fromauth)s - 'From: author\\n\\n' if different from sender
73 %(authname)s - author's name
74 %(authemail)s - author's email
75 %(authdate)s - patch creation date
76 %(commname)s - committer's name
77 %(commemail)s - committer's e-mail
78
79 For the preamble e-mail template, only the %(sender)s, %(version)s,
80 %(patchnr)s, %(totalnr)s and %(number)s variables are supported."""
81
82 options = [make_option('-a', '--all',
83 help = 'e-mail all the applied patches',
84 action = 'store_true'),
85 make_option('--to',
86 help = 'add TO to the To: list',
87 action = 'append'),
88 make_option('--cc',
89 help = 'add CC to the Cc: list',
90 action = 'append'),
91 make_option('--bcc',
92 help = 'add BCC to the Bcc: list',
93 action = 'append'),
94 make_option('--auto',
95 help = 'automatically cc the patch signers',
96 action = 'store_true'),
97 make_option('--noreply',
98 help = 'do not send subsequent messages as replies',
99 action = 'store_true'),
100 make_option('--unrelated',
101 help = 'send patches without sequence numbering',
102 action = 'store_true'),
103 make_option('-v', '--version', metavar = 'VERSION',
104 help = 'add VERSION to the [PATCH ...] prefix'),
105 make_option('--prefix', metavar = 'PREFIX',
106 help = 'add PREFIX to the [... PATCH ...] prefix'),
107 make_option('-t', '--template', metavar = 'FILE',
108 help = 'use FILE as the message template'),
109 make_option('-c', '--cover', metavar = 'FILE',
110 help = 'send FILE as the cover message'),
111 make_option('-e', '--edit-cover',
112 help = 'edit the cover message before sending',
113 action = 'store_true'),
114 make_option('-E', '--edit-patches',
115 help = 'edit each patch before sending',
116 action = 'store_true'),
117 make_option('-s', '--sleep', type = 'int', metavar = 'SECONDS',
118 help = 'sleep for SECONDS between e-mails sending'),
119 make_option('--refid',
120 help = 'use REFID as the reference id'),
121 make_option('-u', '--smtp-user', metavar = 'USER',
122 help = 'username for SMTP authentication'),
123 make_option('-p', '--smtp-password', metavar = 'PASSWORD',
124 help = 'username for SMTP authentication'),
125 make_option('-T', '--smtp-tls',
126 help = 'use SMTP with TLS encryption',
127 action = 'store_true'),
128 make_option('-b', '--branch',
129 help = 'use BRANCH instead of the default one'),
130 make_option('-O', '--diff-opts',
131 help = 'options to pass to git-diff'),
132 make_option('-m', '--mbox',
133 help = 'generate an mbox file instead of sending',
134 action = 'store_true')]
135
136
137 def __get_sender():
138 """Return the 'authname <authemail>' string as read from the
139 configuration file
140 """
141 sender=config.get('stgit.sender')
142 if not sender:
143 try:
144 sender = str(git.user())
145 except git.GitException:
146 sender = str(git.author())
147
148 if not sender:
149 raise CmdException, 'unknown sender details'
150
151 return address_or_alias(sender)
152
153 def __parse_addresses(msg):
154 """Return a two elements tuple: (from, [to])
155 """
156 def __addr_list(msg, header):
157 return [name_addr[1] for name_addr in
158 email.Utils.getaddresses(msg.get_all(header, []))]
159
160 from_addr_list = __addr_list(msg, 'From')
161 if len(from_addr_list) == 0:
162 raise CmdException, 'No "From" address'
163
164 to_addr_list = __addr_list(msg, 'To') + __addr_list(msg, 'Cc') \
165 + __addr_list(msg, 'Bcc')
166 if len(to_addr_list) == 0:
167 raise CmdException, 'No "To/Cc/Bcc" addresses'
168
169 return (from_addr_list[0], to_addr_list)
170
171 def __send_message(smtpserver, from_addr, to_addr_list, msg, sleep,
172 smtpuser, smtppassword, use_tls):
173 """Send the message using the given SMTP server
174 """
175 try:
176 s = smtplib.SMTP(smtpserver)
177 except Exception, err:
178 raise CmdException, str(err)
179
180 s.set_debuglevel(0)
181 try:
182 if smtpuser and smtppassword:
183 s.ehlo()
184 if use_tls:
185 if not hasattr(socket, 'ssl'):
186 raise CmdException, "cannot use TLS - no SSL support in Python"
187 s.starttls()
188 s.ehlo()
189 s.login(smtpuser, smtppassword)
190
191 result = s.sendmail(from_addr, to_addr_list, msg)
192 if len(result):
193 print "mail server refused delivery for the following recipients: %s" % result
194 # give recipients a chance of receiving patches in the correct order
195 time.sleep(sleep)
196 except Exception, err:
197 raise CmdException, str(err)
198
199 s.quit()
200
201 def __build_address_headers(msg, options, extra_cc = []):
202 """Build the address headers and check existing headers in the
203 template.
204 """
205 def __replace_header(header, addr):
206 if addr:
207 crt_addr = msg[header]
208 del msg[header]
209
210 if crt_addr:
211 msg[header] = address_or_alias(', '.join([crt_addr, addr]))
212 else:
213 msg[header] = address_or_alias(addr)
214
215 to_addr = ''
216 cc_addr = ''
217 bcc_addr = ''
218
219 autobcc = config.get('stgit.autobcc') or ''
220
221 if options.to:
222 to_addr = ', '.join(options.to)
223 if options.cc:
224 cc_addr = ', '.join(options.cc + extra_cc)
225 elif extra_cc:
226 cc_addr = ', '.join(extra_cc)
227 if options.bcc:
228 bcc_addr = ', '.join(options.bcc + [autobcc])
229 elif autobcc:
230 bcc_addr = autobcc
231
232 __replace_header('To', to_addr)
233 __replace_header('Cc', cc_addr)
234 __replace_header('Bcc', bcc_addr)
235
236 def __get_signers_list(msg):
237 """Return the address list generated from signed-off-by and
238 acked-by lines in the message.
239 """
240 addr_list = []
241
242 r = re.compile('^(signed-off-by|acked-by|cc):\s+(.+)$', re.I)
243 for line in msg.split('\n'):
244 m = r.match(line)
245 if m:
246 addr_list.append(m.expand('\g<2>'))
247
248 return addr_list
249
250 def __build_extra_headers(msg, msg_id, ref_id = None):
251 """Build extra email headers and encoding
252 """
253 del msg['Date']
254 msg['Date'] = email.Utils.formatdate(localtime = True)
255 msg['Message-ID'] = msg_id
256 if ref_id:
257 msg['In-Reply-To'] = ref_id
258 msg['References'] = ref_id
259 msg['User-Agent'] = 'StGIT/%s' % version.version
260
261 def __encode_message(msg):
262 # 7 or 8 bit encoding
263 charset = email.Charset.Charset('utf-8')
264 charset.body_encoding = None
265
266 # encode headers
267 for header, value in msg.items():
268 words = []
269 for word in value.split(' '):
270 try:
271 uword = unicode(word, 'utf-8')
272 except UnicodeDecodeError:
273 # maybe we should try a different encoding or report
274 # the error. At the moment, we just ignore it
275 pass
276 words.append(email.Header.Header(uword).encode())
277 new_val = ' '.join(words)
278 msg.replace_header(header, new_val)
279
280 # encode the body and set the MIME and encoding headers
281 msg.set_charset(charset)
282
283 def __edit_message(msg):
284 fname = '.stgitmail.txt'
285
286 # create the initial file
287 f = file(fname, 'w')
288 f.write(msg)
289 f.close()
290
291 call_editor(fname)
292
293 # read the message back
294 f = file(fname)
295 msg = f.read()
296 f.close()
297
298 return msg
299
300 def __build_cover(tmpl, total_nr, msg_id, options):
301 """Build the cover message (series description) to be sent via SMTP
302 """
303 sender = __get_sender()
304
305 if options.version:
306 version_str = ' %s' % options.version
307 else:
308 version_str = ''
309
310 if options.prefix:
311 prefix_str = options.prefix + ' '
312 else:
313 confprefix = config.get('stgit.mail.prefix')
314 if confprefix:
315 prefix_str = confprefix + ' '
316 else:
317 prefix_str = ''
318
319 total_nr_str = str(total_nr)
320 patch_nr_str = '0'.zfill(len(total_nr_str))
321 if total_nr > 1:
322 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
323 else:
324 number_str = ''
325
326 tmpl_dict = {'sender': sender,
327 # for backward template compatibility
328 'maintainer': sender,
329 # for backward template compatibility
330 'endofheaders': '',
331 # for backward template compatibility
332 'date': '',
333 'version': version_str,
334 'prefix': prefix_str,
335 'patchnr': patch_nr_str,
336 'totalnr': total_nr_str,
337 'number': number_str}
338
339 try:
340 msg_string = tmpl % tmpl_dict
341 except KeyError, err:
342 raise CmdException, 'Unknown patch template variable: %s' \
343 % err
344 except TypeError:
345 raise CmdException, 'Only "%(name)s" variables are ' \
346 'supported in the patch template'
347
348 if options.edit_cover:
349 msg_string = __edit_message(msg_string)
350
351 # The Python email message
352 try:
353 msg = email.message_from_string(msg_string)
354 except Exception, ex:
355 raise CmdException, 'template parsing error: %s' % str(ex)
356
357 __build_address_headers(msg, options)
358 __build_extra_headers(msg, msg_id, options.refid)
359 __encode_message(msg)
360
361 return msg
362
363 def __build_message(tmpl, patch, patch_nr, total_nr, msg_id, ref_id, options):
364 """Build the message to be sent via SMTP
365 """
366 p = crt_series.get_patch(patch)
367
368 descr = p.get_description().strip()
369 descr_lines = descr.split('\n')
370
371 short_descr = descr_lines[0].rstrip()
372 long_descr = '\n'.join(descr_lines[1:]).lstrip()
373
374 authname = p.get_authname();
375 authemail = p.get_authemail();
376 commname = p.get_commname();
377 commemail = p.get_commemail();
378
379 sender = __get_sender()
380
381 fromauth = '%s <%s>' % (authname, authemail)
382 if fromauth != sender:
383 fromauth = 'From: %s\n\n' % fromauth
384 else:
385 fromauth = ''
386
387 if options.version:
388 version_str = ' %s' % options.version
389 else:
390 version_str = ''
391
392 if options.prefix:
393 prefix_str = options.prefix + ' '
394 else:
395 confprefix = config.get('stgit.mail.prefix')
396 if confprefix:
397 prefix_str = confprefix + ' '
398 else:
399 prefix_str = ''
400
401 if options.diff_opts:
402 diff_flags = options.diff_opts.split()
403 else:
404 diff_flags = []
405
406 total_nr_str = str(total_nr)
407 patch_nr_str = str(patch_nr).zfill(len(total_nr_str))
408 if not options.unrelated and total_nr > 1:
409 number_str = ' %s/%s' % (patch_nr_str, total_nr_str)
410 else:
411 number_str = ''
412
413 tmpl_dict = {'patch': patch,
414 'sender': sender,
415 # for backward template compatibility
416 'maintainer': sender,
417 'shortdescr': short_descr,
418 'longdescr': long_descr,
419 # for backward template compatibility
420 'endofheaders': '',
421 'diff': git.diff(rev1 = git_id('%s//bottom' % patch),
422 rev2 = git_id('%s//top' % patch),
423 diff_flags = diff_flags ),
424 'diffstat': git.diffstat(rev1 = git_id('%s//bottom'%patch),
425 rev2 = git_id('%s//top' % patch)),
426 # for backward template compatibility
427 'date': '',
428 'version': version_str,
429 'prefix': prefix_str,
430 'patchnr': patch_nr_str,
431 'totalnr': total_nr_str,
432 'number': number_str,
433 'fromauth': fromauth,
434 'authname': authname,
435 'authemail': authemail,
436 'authdate': p.get_authdate(),
437 'commname': commname,
438 'commemail': commemail}
439 # change None to ''
440 for key in tmpl_dict:
441 if not tmpl_dict[key]:
442 tmpl_dict[key] = ''
443
444 try:
445 msg_string = tmpl % tmpl_dict
446 except KeyError, err:
447 raise CmdException, 'Unknown patch template variable: %s' \
448 % err
449 except TypeError:
450 raise CmdException, 'Only "%(name)s" variables are ' \
451 'supported in the patch template'
452
453 if options.edit_patches:
454 msg_string = __edit_message(msg_string)
455
456 # The Python email message
457 try:
458 msg = email.message_from_string(msg_string)
459 except Exception, ex:
460 raise CmdException, 'template parsing error: %s' % str(ex)
461
462 if options.auto:
463 extra_cc = __get_signers_list(descr)
464 else:
465 extra_cc = []
466
467 __build_address_headers(msg, options, extra_cc)
468 __build_extra_headers(msg, msg_id, ref_id)
469 __encode_message(msg)
470
471 return msg
472
473 def func(parser, options, args):
474 """Send the patches by e-mail using the patchmail.tmpl file as
475 a template
476 """
477 smtpserver = config.get('stgit.smtpserver')
478
479 applied = crt_series.get_applied()
480
481 if options.all:
482 patches = applied
483 elif len(args) >= 1:
484 unapplied = crt_series.get_unapplied()
485 patches = parse_patches(args, applied + unapplied, len(applied))
486 else:
487 raise CmdException, 'Incorrect options. Unknown patches to send'
488
489 smtppassword = options.smtp_password or config.get('stgit.smtppassword')
490 smtpuser = options.smtp_user or config.get('stgit.smtpuser')
491 smtpusetls = options.smtp_tls or config.get('stgit.smtptls') == 'yes'
492
493 if (smtppassword and not smtpuser):
494 raise CmdException, 'SMTP password supplied, username needed'
495 if (smtpuser and not smtppassword):
496 raise CmdException, 'SMTP username supplied, password needed'
497 if (smtpusetls and not smtpuser):
498 raise CmdException, 'SMTP over TLS requested, username needed'
499
500 total_nr = len(patches)
501 if total_nr == 0:
502 raise CmdException, 'No patches to send'
503
504 if options.refid:
505 if options.noreply or options.unrelated:
506 raise CmdException, \
507 '--refid option not allowed with --noreply or --unrelated'
508 ref_id = options.refid
509 else:
510 ref_id = None
511
512 sleep = options.sleep or config.getint('stgit.smtpdelay')
513
514 # send the cover message (if any)
515 if options.cover or options.edit_cover:
516 if options.unrelated:
517 raise CmdException, 'cover sending not allowed with --unrelated'
518
519 # find the template file
520 if options.cover:
521 tmpl = file(options.cover).read()
522 else:
523 tmpl = templates.get_template('covermail.tmpl')
524 if not tmpl:
525 raise CmdException, 'No cover message template file found'
526
527 msg_id = email.Utils.make_msgid('stgit')
528 msg = __build_cover(tmpl, total_nr, msg_id, options)
529 from_addr, to_addr_list = __parse_addresses(msg)
530
531 msg_string = msg.as_string(options.mbox)
532
533 # subsequent e-mails are seen as replies to the first one
534 if not options.noreply:
535 ref_id = msg_id
536
537 if options.mbox:
538 out.stdout_raw(msg_string + '\n')
539 else:
540 out.start('Sending the cover message')
541 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
542 sleep, smtpuser, smtppassword, smtpusetls)
543 out.done()
544
545 # send the patches
546 if options.template:
547 tmpl = file(options.template).read()
548 else:
549 tmpl = templates.get_template('patchmail.tmpl')
550 if not tmpl:
551 raise CmdException, 'No e-mail template file found'
552
553 for (p, patch_nr) in zip(patches, range(1, len(patches) + 1)):
554 msg_id = email.Utils.make_msgid('stgit')
555 msg = __build_message(tmpl, p, patch_nr, total_nr, msg_id, ref_id,
556 options)
557 from_addr, to_addr_list = __parse_addresses(msg)
558
559 msg_string = msg.as_string(options.mbox)
560
561 # subsequent e-mails are seen as replies to the first one
562 if not options.noreply and not options.unrelated and not ref_id:
563 ref_id = msg_id
564
565 if options.mbox:
566 out.stdout_raw(msg_string + '\n')
567 else:
568 out.start('Sending patch "%s"' % p)
569 __send_message(smtpserver, from_addr, to_addr_list, msg_string,
570 sleep, smtpuser, smtppassword, smtpusetls)
571 out.done()