summaryrefslogtreecommitdiff
path: root/bzrlib/mail_client.py
blob: 686f5244edd04cffe8e0ef38a7f7a8091894a0b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
# Copyright (C) 2007-2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

from __future__ import absolute_import

import errno
import os
import subprocess
import sys
import tempfile

import bzrlib
from bzrlib import (
    config as _mod_config,
    email_message,
    errors,
    msgeditor,
    osutils,
    urlutils,
    registry
    )

mail_client_registry = registry.Registry()


class MailClient(object):
    """A mail client that can send messages with attachements."""

    def __init__(self, config):
        self.config = config

    def compose(self, prompt, to, subject, attachment, mime_subtype,
                extension, basename=None, body=None):
        """Compose (and possibly send) an email message

        Must be implemented by subclasses.

        :param prompt: A message to tell the user what to do.  Supported by
            the Editor client, but ignored by others
        :param to: The address to send the message to
        :param subject: The contents of the subject line
        :param attachment: An email attachment, as a bytestring
        :param mime_subtype: The attachment is assumed to be a subtype of
            Text.  This allows the precise subtype to be specified, e.g.
            "plain", "x-patch", etc.
        :param extension: The file extension associated with the attachment
            type, e.g. ".patch"
        :param basename: The name to use for the attachment, e.g.
            "send-nick-3252"
        """
        raise NotImplementedError

    def compose_merge_request(self, to, subject, directive, basename=None,
                              body=None):
        """Compose (and possibly send) a merge request

        :param to: The address to send the request to
        :param subject: The subject line to use for the request
        :param directive: A merge directive representing the merge request, as
            a bytestring.
        :param basename: The name to use for the attachment, e.g.
            "send-nick-3252"
        """
        prompt = self._get_merge_prompt("Please describe these changes:", to,
                                        subject, directive)
        self.compose(prompt, to, subject, directive,
            'x-patch', '.patch', basename, body)

    def _get_merge_prompt(self, prompt, to, subject, attachment):
        """Generate a prompt string.  Overridden by Editor.

        :param prompt: A string suggesting what user should do
        :param to: The address the mail will be sent to
        :param subject: The subject line of the mail
        :param attachment: The attachment that will be used
        """
        return ''


class Editor(MailClient):
    __doc__ = """DIY mail client that uses commit message editor"""

    supports_body = True

    def _get_merge_prompt(self, prompt, to, subject, attachment):
        """See MailClient._get_merge_prompt"""
        return (u"%s\n\n"
                u"To: %s\n"
                u"Subject: %s\n\n"
                u"%s" % (prompt, to, subject,
                         attachment.decode('utf-8', 'replace')))

    def compose(self, prompt, to, subject, attachment, mime_subtype,
                extension, basename=None, body=None):
        """See MailClient.compose"""
        if not to:
            raise errors.NoMailAddressSpecified()
        body = msgeditor.edit_commit_message(prompt, start_message=body)
        if body == '':
            raise errors.NoMessageSupplied()
        email_message.EmailMessage.send(self.config,
                                        self.config.get('email'),
                                        to,
                                        subject,
                                        body,
                                        attachment,
                                        attachment_mime_subtype=mime_subtype)
mail_client_registry.register('editor', Editor,
                              help=Editor.__doc__)


class BodyExternalMailClient(MailClient):

    supports_body = True

    def _get_client_commands(self):
        """Provide a list of commands that may invoke the mail client"""
        if sys.platform == 'win32':
            import win32utils
            return [win32utils.get_app_path(i) for i in self._client_commands]
        else:
            return self._client_commands

    def compose(self, prompt, to, subject, attachment, mime_subtype,
                extension, basename=None, body=None):
        """See MailClient.compose.

        Writes the attachment to a temporary file, invokes _compose.
        """
        if basename is None:
            basename = 'attachment'
        pathname = osutils.mkdtemp(prefix='bzr-mail-')
        attach_path = osutils.pathjoin(pathname, basename + extension)
        outfile = open(attach_path, 'wb')
        try:
            outfile.write(attachment)
        finally:
            outfile.close()
        if body is not None:
            kwargs = {'body': body}
        else:
            kwargs = {}
        self._compose(prompt, to, subject, attach_path, mime_subtype,
                      extension, **kwargs)

    def _compose(self, prompt, to, subject, attach_path, mime_subtype,
                 extension, body=None, from_=None):
        """Invoke a mail client as a commandline process.

        Overridden by MAPIClient.
        :param to: The address to send the mail to
        :param subject: The subject line for the mail
        :param pathname: The path to the attachment
        :param mime_subtype: The attachment is assumed to have a major type of
            "text", but the precise subtype can be specified here
        :param extension: A file extension (including period) associated with
            the attachment type.
        :param body: Optional body text.
        :param from_: Optional From: header.
        """
        for name in self._get_client_commands():
            cmdline = [self._encode_path(name, 'executable')]
            if body is not None:
                kwargs = {'body': body}
            else:
                kwargs = {}
            if from_ is not None:
                kwargs['from_'] = from_
            cmdline.extend(self._get_compose_commandline(to, subject,
                                                         attach_path,
                                                         **kwargs))
            try:
                subprocess.call(cmdline)
            except OSError, e:
                if e.errno != errno.ENOENT:
                    raise
            else:
                break
        else:
            raise errors.MailClientNotFound(self._client_commands)

    def _get_compose_commandline(self, to, subject, attach_path, body):
        """Determine the commandline to use for composing a message

        Implemented by various subclasses
        :param to: The address to send the mail to
        :param subject: The subject line for the mail
        :param attach_path: The path to the attachment
        """
        raise NotImplementedError

    def _encode_safe(self, u):
        """Encode possible unicode string argument to 8-bit string
        in user_encoding. Unencodable characters will be replaced
        with '?'.

        :param  u:  possible unicode string.
        :return:    encoded string if u is unicode, u itself otherwise.
        """
        if isinstance(u, unicode):
            return u.encode(osutils.get_user_encoding(), 'replace')
        return u

    def _encode_path(self, path, kind):
        """Encode unicode path in user encoding.

        :param  path:   possible unicode path.
        :param  kind:   path kind ('executable' or 'attachment').
        :return:        encoded path if path is unicode,
                        path itself otherwise.
        :raise:         UnableEncodePath.
        """
        if isinstance(path, unicode):
            try:
                return path.encode(osutils.get_user_encoding())
            except UnicodeEncodeError:
                raise errors.UnableEncodePath(path, kind)
        return path


class ExternalMailClient(BodyExternalMailClient):
    __doc__ = """An external mail client."""

    supports_body = False


class Evolution(BodyExternalMailClient):
    __doc__ = """Evolution mail client."""

    _client_commands = ['evolution']

    def _get_compose_commandline(self, to, subject, attach_path, body=None):
        """See ExternalMailClient._get_compose_commandline"""
        message_options = {}
        if subject is not None:
            message_options['subject'] = subject
        if attach_path is not None:
            message_options['attach'] = attach_path
        if body is not None:
            message_options['body'] = body
        options_list = ['%s=%s' % (k, urlutils.escape(v)) for (k, v) in
                        sorted(message_options.iteritems())]
        return ['mailto:%s?%s' % (self._encode_safe(to or ''),
            '&'.join(options_list))]
mail_client_registry.register('evolution', Evolution,
                              help=Evolution.__doc__)


class Mutt(BodyExternalMailClient):
    __doc__ = """Mutt mail client."""

    _client_commands = ['mutt']

    def _get_compose_commandline(self, to, subject, attach_path, body=None):
        """See ExternalMailClient._get_compose_commandline"""
        message_options = []
        if subject is not None:
            message_options.extend(['-s', self._encode_safe(subject)])
        if attach_path is not None:
            message_options.extend(['-a',
                self._encode_path(attach_path, 'attachment')])
        if body is not None:
            # Store the temp file object in self, so that it does not get
            # garbage collected and delete the file before mutt can read it.
            self._temp_file = tempfile.NamedTemporaryFile(
                prefix="mutt-body-", suffix=".txt")
            self._temp_file.write(body)
            self._temp_file.flush()
            message_options.extend(['-i', self._temp_file.name])
        if to is not None:
            message_options.extend(['--', self._encode_safe(to)])
        return message_options
mail_client_registry.register('mutt', Mutt,
                              help=Mutt.__doc__)


class Thunderbird(BodyExternalMailClient):
    __doc__ = """Mozilla Thunderbird (or Icedove)

    Note that Thunderbird 1.5 is buggy and does not support setting
    "to" simultaneously with including a attachment.

    There is a workaround if no attachment is present, but we always need to
    send attachments.
    """

    _client_commands = ['thunderbird', 'mozilla-thunderbird', 'icedove',
        '/Applications/Mozilla/Thunderbird.app/Contents/MacOS/thunderbird-bin',
        '/Applications/Thunderbird.app/Contents/MacOS/thunderbird-bin']

    def _get_compose_commandline(self, to, subject, attach_path, body=None):
        """See ExternalMailClient._get_compose_commandline"""
        message_options = {}
        if to is not None:
            message_options['to'] = self._encode_safe(to)
        if subject is not None:
            message_options['subject'] = self._encode_safe(subject)
        if attach_path is not None:
            message_options['attachment'] = urlutils.local_path_to_url(
                attach_path)
        if body is not None:
            options_list = ['body=%s' % urlutils.quote(self._encode_safe(body))]
        else:
            options_list = []
        options_list.extend(["%s='%s'" % (k, v) for k, v in
                        sorted(message_options.iteritems())])
        return ['-compose', ','.join(options_list)]
mail_client_registry.register('thunderbird', Thunderbird,
                              help=Thunderbird.__doc__)


class KMail(ExternalMailClient):
    __doc__ = """KDE mail client."""

    _client_commands = ['kmail']

    def _get_compose_commandline(self, to, subject, attach_path):
        """See ExternalMailClient._get_compose_commandline"""
        message_options = []
        if subject is not None:
            message_options.extend(['-s', self._encode_safe(subject)])
        if attach_path is not None:
            message_options.extend(['--attach',
                self._encode_path(attach_path, 'attachment')])
        if to is not None:
            message_options.extend([self._encode_safe(to)])
        return message_options
mail_client_registry.register('kmail', KMail,
                              help=KMail.__doc__)


class Claws(ExternalMailClient):
    __doc__ = """Claws mail client."""

    supports_body = True

    _client_commands = ['claws-mail']

    def _get_compose_commandline(self, to, subject, attach_path, body=None,
                                 from_=None):
        """See ExternalMailClient._get_compose_commandline"""
        compose_url = []
        if from_ is not None:
            compose_url.append('from=' + urlutils.quote(from_))
        if subject is not None:
            # Don't use urlutils.quote_plus because Claws doesn't seem
            # to recognise spaces encoded as "+".
            compose_url.append(
                'subject=' + urlutils.quote(self._encode_safe(subject)))
        if body is not None:
            compose_url.append(
                'body=' + urlutils.quote(self._encode_safe(body)))
        # to must be supplied for the claws-mail --compose syntax to work.
        if to is None:
            raise errors.NoMailAddressSpecified()
        compose_url = 'mailto:%s?%s' % (
            self._encode_safe(to), '&'.join(compose_url))
        # Collect command-line options.
        message_options = ['--compose', compose_url]
        if attach_path is not None:
            message_options.extend(
                ['--attach', self._encode_path(attach_path, 'attachment')])
        return message_options

    def _compose(self, prompt, to, subject, attach_path, mime_subtype,
                 extension, body=None, from_=None):
        """See ExternalMailClient._compose"""
        if from_ is None:
            from_ = self.config.get('email')
        super(Claws, self)._compose(prompt, to, subject, attach_path,
                                    mime_subtype, extension, body, from_)


mail_client_registry.register('claws', Claws,
                              help=Claws.__doc__)


class XDGEmail(BodyExternalMailClient):
    __doc__ = """xdg-email attempts to invoke the user's preferred mail client"""

    _client_commands = ['xdg-email']

    def _get_compose_commandline(self, to, subject, attach_path, body=None):
        """See ExternalMailClient._get_compose_commandline"""
        if not to:
            raise errors.NoMailAddressSpecified()
        commandline = [self._encode_safe(to)]
        if subject is not None:
            commandline.extend(['--subject', self._encode_safe(subject)])
        if attach_path is not None:
            commandline.extend(['--attach',
                self._encode_path(attach_path, 'attachment')])
        if body is not None:
            commandline.extend(['--body', self._encode_safe(body)])
        return commandline
mail_client_registry.register('xdg-email', XDGEmail,
                              help=XDGEmail.__doc__)


class EmacsMail(ExternalMailClient):
    __doc__ = """Call emacsclient to have a mail buffer.

    This only work for emacs >= 22.1 due to recent -e/--eval support.

    The good news is that this implementation will work with all mail
    agents registered against ``mail-user-agent``. So there is no need
    to instantiate ExternalMailClient for each and every GNU Emacs
    MUA.

    Users just have to ensure that ``mail-user-agent`` is set according
    to their tastes.
    """

    _client_commands = ['emacsclient']

    def __init__(self, config):
        super(EmacsMail, self).__init__(config)
        self.elisp_tmp_file = None

    def _prepare_send_function(self):
        """Write our wrapper function into a temporary file.

        This temporary file will be loaded at runtime in
        _get_compose_commandline function.

        This function does not remove the file.  That's a wanted
        behaviour since _get_compose_commandline won't run the send
        mail function directly but return the eligible command line.
        Removing our temporary file here would prevent our sendmail
        function to work.  (The file is deleted by some elisp code
        after being read by Emacs.)
        """

        _defun = r"""(defun bzr-add-mime-att (file)
  "Attach FILE to a mail buffer as a MIME attachment."
  (let ((agent mail-user-agent))
    (if (and file (file-exists-p file))
        (cond
         ((eq agent 'sendmail-user-agent)
          (progn
            (mail-text)
            (newline)
            (if (functionp 'etach-attach)
              (etach-attach file)
              (mail-attach-file file))))
         ((or (eq agent 'message-user-agent)
              (eq agent 'gnus-user-agent)
              (eq agent 'mh-e-user-agent))
          (progn
            (mml-attach-file file "text/x-patch" "BZR merge" "inline")))
         ((eq agent 'mew-user-agent)
          (progn
            (mew-draft-prepare-attachments)
            (mew-attach-link file (file-name-nondirectory file))
            (let* ((nums (mew-syntax-nums))
                   (syntax (mew-syntax-get-entry mew-encode-syntax nums)))
              (mew-syntax-set-cd syntax "BZR merge")
              (mew-encode-syntax-print mew-encode-syntax))
            (mew-header-goto-body)))
         (t
          (message "Unhandled MUA, report it on bazaar@lists.canonical.com")))
      (error "File %s does not exist." file))))
"""

        fd, temp_file = tempfile.mkstemp(prefix="emacs-bzr-send-",
                                         suffix=".el")
        try:
            os.write(fd, _defun)
        finally:
            os.close(fd) # Just close the handle but do not remove the file.
        return temp_file

    def _get_compose_commandline(self, to, subject, attach_path):
        commandline = ["--eval"]

        _to = "nil"
        _subject = "nil"

        if to is not None:
            _to = ("\"%s\"" % self._encode_safe(to).replace('"', '\\"'))
        if subject is not None:
            _subject = ("\"%s\"" %
                        self._encode_safe(subject).replace('"', '\\"'))

        # Funcall the default mail composition function
        # This will work with any mail mode including default mail-mode
        # User must tweak mail-user-agent variable to tell what function
        # will be called inside compose-mail.
        mail_cmd = "(compose-mail %s %s)" % (_to, _subject)
        commandline.append(mail_cmd)

        # Try to attach a MIME attachment using our wrapper function
        if attach_path is not None:
            # Do not create a file if there is no attachment
            elisp = self._prepare_send_function()
            self.elisp_tmp_file = elisp
            lmmform = '(load "%s")' % elisp
            mmform  = '(bzr-add-mime-att "%s")' % \
                self._encode_path(attach_path, 'attachment')
            rmform = '(delete-file "%s")' % elisp
            commandline.append(lmmform)
            commandline.append(mmform)
            commandline.append(rmform)

        return commandline
mail_client_registry.register('emacsclient', EmacsMail,
                              help=EmacsMail.__doc__)


class MAPIClient(BodyExternalMailClient):
    __doc__ = """Default Windows mail client launched using MAPI."""

    def _compose(self, prompt, to, subject, attach_path, mime_subtype,
                 extension, body=None):
        """See ExternalMailClient._compose.

        This implementation uses MAPI via the simplemapi ctypes wrapper
        """
        from bzrlib.util import simplemapi
        try:
            simplemapi.SendMail(to or '', subject or '', body or '',
                                attach_path)
        except simplemapi.MAPIError, e:
            if e.code != simplemapi.MAPI_USER_ABORT:
                raise errors.MailClientNotFound(['MAPI supported mail client'
                                                 ' (error %d)' % (e.code,)])
mail_client_registry.register('mapi', MAPIClient,
                              help=MAPIClient.__doc__)


class MailApp(BodyExternalMailClient):
    __doc__ = """Use MacOS X's Mail.app for sending email messages.

    Although it would be nice to use appscript, it's not installed
    with the shipped Python installations.  We instead build an
    AppleScript and invoke the script using osascript(1).  We don't
    use the _encode_safe() routines as it's not clear what encoding
    osascript expects the script to be in.
    """

    _client_commands = ['osascript']

    def _get_compose_commandline(self, to, subject, attach_path, body=None,
                                from_=None):
       """See ExternalMailClient._get_compose_commandline"""

       fd, self.temp_file = tempfile.mkstemp(prefix="bzr-send-",
                                         suffix=".scpt")
       try:
           os.write(fd, 'tell application "Mail"\n')
           os.write(fd, 'set newMessage to make new outgoing message\n')
           os.write(fd, 'tell newMessage\n')
           if to is not None:
               os.write(fd, 'make new to recipient with properties'
                   ' {address:"%s"}\n' % to)
           if from_ is not None:
               # though from_ doesn't actually seem to be used
               os.write(fd, 'set sender to "%s"\n'
                   % sender.replace('"', '\\"'))
           if subject is not None:
               os.write(fd, 'set subject to "%s"\n'
                   % subject.replace('"', '\\"'))
           if body is not None:
               # FIXME: would be nice to prepend the body to the
               # existing content (e.g., preserve signature), but
               # can't seem to figure out the right applescript
               # incantation.
               os.write(fd, 'set content to "%s\\n\n"\n' %
                   body.replace('"', '\\"').replace('\n', '\\n'))

           if attach_path is not None:
               # FIXME: would be nice to first append a newline to
               # ensure the attachment is on a new paragraph, but
               # can't seem to figure out the right applescript
               # incantation.
               os.write(fd, 'tell content to make new attachment'
                   ' with properties {file name:"%s"}'
                   ' at after the last paragraph\n'
                   % self._encode_path(attach_path, 'attachment'))
           os.write(fd, 'set visible to true\n')
           os.write(fd, 'end tell\n')
           os.write(fd, 'end tell\n')
       finally:
           os.close(fd) # Just close the handle but do not remove the file.
       return [self.temp_file]
mail_client_registry.register('mail.app', MailApp,
                              help=MailApp.__doc__)


class DefaultMail(MailClient):
    __doc__ = """Default mail handling.  Tries XDGEmail (or MAPIClient on Windows),
    falls back to Editor"""

    supports_body = True

    def _mail_client(self):
        """Determine the preferred mail client for this platform"""
        if osutils.supports_mapi():
            return MAPIClient(self.config)
        else:
            return XDGEmail(self.config)

    def compose(self, prompt, to, subject, attachment, mime_subtype,
                extension, basename=None, body=None):
        """See MailClient.compose"""
        try:
            return self._mail_client().compose(prompt, to, subject,
                                               attachment, mime_subtype,
                                               extension, basename, body)
        except errors.MailClientNotFound:
            return Editor(self.config).compose(prompt, to, subject,
                          attachment, mime_subtype, extension, body)

    def compose_merge_request(self, to, subject, directive, basename=None,
                              body=None):
        """See MailClient.compose_merge_request"""
        try:
            return self._mail_client().compose_merge_request(to, subject,
                    directive, basename=basename, body=body)
        except errors.MailClientNotFound:
            return Editor(self.config).compose_merge_request(to, subject,
                          directive, basename=basename, body=body)
mail_client_registry.register('default', DefaultMail,
                              help=DefaultMail.__doc__)
mail_client_registry.default_key = 'default'

opt_mail_client = _mod_config.RegistryOption('mail_client',
        mail_client_registry, help='E-mail client to use.', invalid='error')