Exemplo n.º 1
0
    def apply(self, ui):
        envelope = ui.current_buffer.envelope

        # determine account to use
        sname, saddr = email.Utils.parseaddr(envelope.get('From'))
        account = settings.get_account_by_address(saddr)
        if account is None:
            if not settings.get_accounts():
                ui.notify('no accounts set.', priority='error')
                return
            else:
                account = settings.get_accounts()[0]

        if account.draft_box is None:
            ui.notify('abort: account <%s> has no draft_box set.' % saddr,
                      priority='error')
            return

        mail = envelope.construct_mail()
        # store mail locally
        # add Date header
        mail['Date'] = email.Utils.formatdate(localtime=True)
        path = account.store_draft_mail(crypto.email_as_string(mail))
        ui.notify('draft saved successfully')

        # add mail to index if maildir path available
        if path is not None:
            logging.debug('adding new mail to index')
            ui.dbman.add_message(path, account.draft_tags)
            ui.apply_command(globals.FlushCommand())
        ui.apply_command(commands.globals.BufferCloseCommand())
Exemplo n.º 2
0
    def apply(self, ui):
        envelope = ui.current_buffer.envelope

        # determine account to use
        sname, saddr = email.Utils.parseaddr(envelope.get('From'))
        account = settings.get_account_by_address(saddr)
        if account is None:
            if not settings.get_accounts():
                ui.notify('no accounts set.', priority='error')
                return
            else:
                account = settings.get_accounts()[0]

        if account.draft_box is None:
            ui.notify('abort: account <%s> has no draft_box set.' % saddr,
                      priority='error')
            return

        mail = envelope.construct_mail()
        # store mail locally
        # add Date header
        mail['Date'] = email.Utils.formatdate(localtime=True)
        path = account.store_draft_mail(crypto.email_as_string(mail))
        ui.notify('draft saved successfully')

        # add mail to index if maildir path available
        if path is not None:
            logging.debug('adding new mail to index')
            ui.dbman.add_message(path, account.draft_tags)
            ui.apply_command(globals.FlushCommand())
        ui.apply_command(commands.globals.BufferCloseCommand())
Exemplo n.º 3
0
    def apply(self, ui):
        currentbuffer = ui.current_buffer  # needed to close later
        envelope = currentbuffer.envelope

        # This is to warn the user before re-sending
        # an already sent message in case the envelope buffer
        # was not closed because it was the last remaining buffer.
        if envelope.sent_time:
            warning = 'A modified version of ' * envelope.modified_since_sent
            warning += 'this message has been sent at %s.' % envelope.sent_time
            warning += ' Do you want to resend?'
            if (yield ui.choice(warning, cancel='no',
                                msg_position='left')) == 'no':
                return

        # don't do anything if another SendCommand is in the middle of sending
        # the message and we were triggered accidentally
        if envelope.sending:
            msg = 'sending this message already!'
            logging.debug(msg)
            return

        frm = envelope.get('From')
        sname, saddr = email.Utils.parseaddr(frm)

        # determine account to use for sending
        account = settings.get_account_by_address(saddr)
        if account is None:
            if not settings.get_accounts():
                ui.notify('no accounts set', priority='error')
                return
            else:
                account = settings.get_accounts()[0]

        clearme = ui.notify(u'constructing mail (GPG, attachments)\u2026',
                            timeout=-1)

        try:
            mail = envelope.construct_mail()
            mail['Date'] = email.Utils.formatdate(localtime=True)
            mail = crypto.email_as_string(mail)
        except GPGProblem, e:
            ui.clear_notify([clearme])
            ui.notify(e.message, priority='error')
            return
Exemplo n.º 4
0
    def apply(self, ui):
        currentbuffer = ui.current_buffer  # needed to close later
        envelope = currentbuffer.envelope

        # This is to warn the user before re-sending
        # an already sent message in case the envelope buffer
        # was not closed because it was the last remaining buffer.
        if envelope.sent_time:
            warning = 'A modified version of ' * envelope.modified_since_sent
            warning += 'this message has been sent at %s.' % envelope.sent_time
            warning += ' Do you want to resend?'
            if (yield ui.choice(warning, cancel='no',
                                msg_position='left')) == 'no':
                return

        # don't do anything if another SendCommand is in the middle of sending
        # the message and we were triggered accidentally
        if envelope.sending:
            msg = 'sending this message already!'
            logging.debug(msg)
            return

        frm = envelope.get('From')
        sname, saddr = email.Utils.parseaddr(frm)

        # determine account to use for sending
        account = settings.get_account_by_address(saddr)
        if account is None:
            if not settings.get_accounts():
                ui.notify('no accounts set', priority='error')
                return
            else:
                account = settings.get_accounts()[0]

        clearme = ui.notify(u'constructing mail (GPG, attachments)\u2026',
                            timeout=-1)

        try:
            mail = envelope.construct_mail()
            mail['Date'] = email.Utils.formatdate(localtime=True)
            mail = crypto.email_as_string(mail)
        except GPGProblem, e:
            ui.clear_notify([clearme])
            ui.notify(e.message, priority='error')
            return
Exemplo n.º 5
0
    def send_mail(self, mail):
        mail['Date'] = email.utils.formatdate(time.time(), True)
        cmdlist = split_commandstring(self.cmd)

        def cb(out):
            logging.info('sent mail successfully')
            logging.info(out)

        def errb(failure):
            termobj = failure.value
            errmsg = '%s\nsendmail_cmd set to: %s' % (str(termobj), self.cmd)
            logging.error(errmsg)
            logging.error(failure.getTraceback())
            logging.error(failure.value.stderr)
            raise SendingMailFailed(errmsg)

        d = call_cmd_async(cmdlist, stdin=crypto.email_as_string(mail))
        d.addCallback(cb)
        d.addErrback(errb)
        return d
Exemplo n.º 6
0
    def send_mail(self, mail):
        mail['Date'] = email.utils.formatdate(time.time(), True)
        cmdlist = split_commandstring(self.cmd)

        def cb(out):
            logging.info('sent mail successfully')
            logging.info(out)

        def errb(failure):
            termobj = failure.value
            errmsg = '%s\nsendmail_cmd set to: %s' % (str(termobj), self.cmd)
            logging.error(errmsg)
            logging.error(failure.getTraceback())
            logging.error(failure.value.stderr)
            raise SendingMailFailed(errmsg)

        d = call_cmd_async(cmdlist, stdin=crypto.email_as_string(mail))
        d.addCallback(cb)
        d.addErrback(errb)
        return d
Exemplo n.º 7
0
    def apply(self, ui):
        if self.mail is None:
            if self.envelope is None:
                # needed to close later
                self.envelope_buffer = ui.current_buffer
                self.envelope = self.envelope_buffer.envelope

            # This is to warn the user before re-sending
            # an already sent message in case the envelope buffer
            # was not closed because it was the last remaining buffer.
            if self.envelope.sent_time:
                mod = self.envelope.modified_since_sent
                when = self.envelope.sent_time
                warning = 'A modified version of ' * mod
                warning += 'this message has been sent at %s.' % when
                warning += ' Do you want to resend?'
                if (yield ui.choice(warning, cancel='no',
                                    msg_position='left')) == 'no':
                    return

            # don't do anything if another SendCommand is in the middle of
            # sending the message and we were triggered accidentally
            if self.envelope.sending:
                msg = 'sending this message already!'
                logging.debug(msg)
                return

            clearme = ui.notify(u'constructing mail (GPG, attachments)\u2026',
                                timeout=-1)

            try:
                self.mail = self.envelope.construct_mail()
                self.mail['Date'] = email.Utils.formatdate(localtime=True)
                self.mail = crypto.email_as_string(self.mail)
            except GPGProblem, e:
                ui.clear_notify([clearme])
                ui.notify(e.message, priority='error')
                return

            ui.clear_notify([clearme])
Exemplo n.º 8
0
    def apply(self, ui):
        if self.mail is None:
            if self.envelope is None:
                # needed to close later
                self.envelope_buffer = ui.current_buffer
                self.envelope = self.envelope_buffer.envelope

            # This is to warn the user before re-sending
            # an already sent message in case the envelope buffer
            # was not closed because it was the last remaining buffer.
            if self.envelope.sent_time:
                mod = self.envelope.modified_since_sent
                when = self.envelope.sent_time
                warning = 'A modified version of ' * mod
                warning += 'this message has been sent at %s.' % when
                warning += ' Do you want to resend?'
                if (yield ui.choice(warning, cancel='no',
                                    msg_position='left')) == 'no':
                    return

            # don't do anything if another SendCommand is in the middle of
            # sending the message and we were triggered accidentally
            if self.envelope.sending:
                msg = 'sending this message already!'
                logging.debug(msg)
                return

            clearme = ui.notify(u'constructing mail (GPG, attachments)\u2026',
                                timeout=-1)

            try:
                self.mail = self.envelope.construct_mail()
                self.mail['Date'] = email.Utils.formatdate(localtime=True)
                self.mail = crypto.email_as_string(self.mail)
            except GPGProblem, e:
                ui.clear_notify([clearme])
                ui.notify(e.message, priority='error')
                return

            ui.clear_notify([clearme])
Exemplo n.º 9
0
    def construct_mail(self):
        """
        compiles the information contained in this envelope into a
        :class:`email.Message`.
        """
        # Build body text part. To properly sign/encrypt messages later on, we
        # convert the text to its canonical format (as per RFC 2015).
        canonical_format = self.body.encode('utf-8')
        canonical_format = canonical_format.replace('\\t', ' ' * 4)
        textpart = MIMEText(canonical_format, 'plain', 'utf-8')

        # wrap it in a multipart container if necessary
        if self.attachments:
            inner_msg = MIMEMultipart()
            inner_msg.attach(textpart)
            # add attachments
            for a in self.attachments:
                inner_msg.attach(a.get_mime_representation())
        else:
            inner_msg = textpart

        if self.sign:
            plaintext = crypto.email_as_string(inner_msg)
            logging.debug('signing plaintext: ' + plaintext)

            try:
                signatures, signature_str = crypto.detached_signature_for(
                    plaintext, self.sign_key)
                if len(signatures) != 1:
                    raise GPGProblem(("Could not sign message "
                                      "(GPGME did not return a signature)"))
            except gpgme.GpgmeError as e:
                if e.code == gpgme.ERR_BAD_PASSPHRASE:
                    # If GPG_AGENT_INFO is unset or empty, the user just does
                    # not have gpg-agent running (properly).
                    if os.environ.get('GPG_AGENT_INFO', '').strip() == '':
                        msg = "Got invalid passphrase and GPG_AGENT_INFO\
                                not set. Please set up gpg-agent."
                        raise GPGProblem(msg)
                    else:
                        raise GPGProblem(("Bad passphrase. Is "
                                          "gpg-agent running?"))
                raise GPGProblem(str(e))

            micalg = crypto.RFC3156_micalg_from_algo(signatures[0].hash_algo)
            unencrypted_msg = MIMEMultipart('signed', micalg=micalg,
                                            protocol=
                                            'application/pgp-signature')

            # wrap signature in MIMEcontainter
            stype = 'pgp-signature; name="signature.asc"'
            signature_mime = MIMEApplication(_data=signature_str,
                                             _subtype=stype,
                                             _encoder=encode_7or8bit)
            signature_mime['Content-Description'] = 'signature'
            signature_mime.set_charset('us-ascii')

            # add signed message and signature to outer message
            unencrypted_msg.attach(inner_msg)
            unencrypted_msg.attach(signature_mime)
            unencrypted_msg['Content-Disposition'] = 'inline'
        else:
            unencrypted_msg = inner_msg

        if self.encrypt:
            plaintext = crypto.email_as_string(unencrypted_msg)
            logging.debug('encrypting plaintext: ' + plaintext)

            try:
                encrypted_str = crypto.encrypt(plaintext,
                                               self.encrypt_keys.values())
            except gpgme.GpgmeError as e:
                raise GPGProblem(str(e))

            outer_msg = MIMEMultipart('encrypted',
                                      protocol='application/pgp-encrypted')

            version_str = 'Version: 1'
            encryption_mime = MIMEApplication(_data=version_str,
                                              _subtype='pgp-encrypted',
                                              _encoder=encode_7or8bit)
            encryption_mime.set_charset('us-ascii')

            encrypted_mime = MIMEApplication(_data=encrypted_str,
                                             _subtype='octet-stream',
                                             _encoder=encode_7or8bit)
            encrypted_mime.set_charset('us-ascii')
            outer_msg.attach(encryption_mime)
            outer_msg.attach(encrypted_mime)

        else:
            outer_msg = unencrypted_msg

        headers = self.headers.copy()
        # add Message-ID
        if 'Message-ID' not in headers:
            headers['Message-ID'] = [email.Utils.make_msgid()]

        if 'User-Agent' in headers:
            uastring_format = headers['User-Agent'][0]
        else:
            uastring_format = settings.get('user_agent').strip()
        uastring = uastring_format.format(version=__version__)
        if uastring:
            headers['User-Agent'] = [uastring]

        # copy headers from envelope to mail
        for k, vlist in headers.items():
            for v in vlist:
                outer_msg[k] = encode_header(k, v)

        return outer_msg
Exemplo n.º 10
0
    def construct_mail(self):
        """
        compiles the information contained in this envelope into a
        :class:`email.Message`.
        """
        # Build body text part. To properly sign/encrypt messages later on, we
        # convert the text to its canonical format (as per RFC 2015).
        canonical_format = self.body.encode("utf-8")
        canonical_format = canonical_format.replace("\\t", " " * 4)
        textpart = MIMEText(canonical_format, "plain", "utf-8")

        # wrap it in a multipart container if necessary
        if self.attachments:
            inner_msg = MIMEMultipart()
            inner_msg.attach(textpart)
            # add attachments
            for a in self.attachments:
                inner_msg.attach(a.get_mime_representation())
        else:
            inner_msg = textpart

        if self.sign:
            plaintext = crypto.email_as_string(inner_msg)
            logging.debug("signing plaintext: " + plaintext)

            try:
                signatures, signature_str = crypto.detached_signature_for(plaintext, self.sign_key)
                if len(signatures) != 1:
                    raise GPGProblem(("Could not sign message " "(GPGME did not return a signature)"))
            except gpgme.GpgmeError as e:
                if e.code == gpgme.ERR_BAD_PASSPHRASE:
                    # If GPG_AGENT_INFO is unset or empty, the user just does
                    # not have gpg-agent running (properly).
                    if os.environ.get("GPG_AGENT_INFO", "").strip() == "":
                        raise GPGProblem(("Bad passphrase and " "GPG_AGENT_INFO not set. Please setup " "gpg-agent."))
                    else:
                        raise GPGProblem(("Bad passphrase. Is " "gpg-agent running?"))
                raise GPGProblem(str(e))

            micalg = crypto.RFC3156_micalg_from_algo(signatures[0].hash_algo)
            outer_msg = MIMEMultipart("signed", micalg=micalg, protocol="application/pgp-signature")

            # wrap signature in MIMEcontainter
            signature_mime = MIMEApplication(
                _data=signature_str, _subtype='pgp-signature; name="signature.asc"', _encoder=encode_7or8bit
            )
            signature_mime["Content-Description"] = "signature"
            signature_mime.set_charset("us-ascii")

            # add signed message and signature to outer message
            outer_msg.attach(inner_msg)
            outer_msg.attach(signature_mime)
            outer_msg["Content-Disposition"] = "inline"
        else:
            outer_msg = inner_msg

        headers = self.headers.copy()
        # add Message-ID
        if "Message-ID" not in headers:
            headers["Message-ID"] = [email.Utils.make_msgid()]

        if "User-Agent" in headers:
            uastring_format = headers["User-Agent"][0]
        else:
            uastring_format = settings.get("user_agent").strip()
        uastring = uastring_format.format(version=__version__)
        if uastring:
            headers["User-Agent"] = [uastring]

        # copy headers from envelope to mail
        for k, vlist in headers.items():
            for v in vlist:
                outer_msg[k] = encode_header(k, v)

        return outer_msg
Exemplo n.º 11
0
    def construct_mail(self):
        """
        compiles the information contained in this envelope into a
        :class:`email.Message`.
        """
        # Build body text part. To properly sign/encrypt messages later on, we
        # convert the text to its canonical format (as per RFC 2015).
        canonical_format = self.body.encode('utf-8')
        canonical_format = canonical_format.replace('\\t', ' ' * 4)
        textpart = MIMEText(canonical_format, 'plain', 'utf-8')

        # wrap it in a multipart container if necessary
        if self.attachments:
            inner_msg = MIMEMultipart()
            inner_msg.attach(textpart)
            # add attachments
            for a in self.attachments:
                inner_msg.attach(a.get_mime_representation())
        else:
            inner_msg = textpart

        if self.sign:
            plaintext = crypto.email_as_string(inner_msg)
            logging.info('signing plaintext: ' + plaintext)

            try:
                signatures, signature_str = crypto.detached_signature_for(
                    plaintext, self.sign_key)
                if len(signatures) != 1:
                    raise GPGProblem(("Could not sign message "
                                      "(GPGME did not return a signature)"))
            except gpgme.GpgmeError as e:
                if e.code == gpgme.ERR_BAD_PASSPHRASE:
                    # If GPG_AGENT_INFO is unset or empty, the user just does
                    # not have gpg-agent running (properly).
                    if os.environ.get('GPG_AGENT_INFO', '').strip() == '':
                        raise GPGProblem(
                            ("Bad passphrase and "
                             "GPG_AGENT_INFO not set. Please setup "
                             "gpg-agent."))
                    else:
                        raise GPGProblem(("Bad passphrase. Is "
                                          "gpg-agent running?"))
                raise GPGProblem(str(e))

            micalg = crypto.RFC3156_micalg_from_algo(signatures[0].hash_algo)
            outer_msg = MIMEMultipart('signed',
                                      micalg=micalg,
                                      protocol='application/pgp-signature')

            # wrap signature in MIMEcontainter
            signature_mime = MIMEApplication(
                _data=signature_str,
                _subtype='pgp-signature; name="signature.asc"',
                _encoder=encode_7or8bit)
            signature_mime['Content-Description'] = 'signature'
            signature_mime.set_charset('us-ascii')

            # add signed message and signature to outer message
            outer_msg.attach(inner_msg)
            outer_msg.attach(signature_mime)
            outer_msg['Content-Disposition'] = 'inline'
        else:
            outer_msg = inner_msg

        headers = self.headers.copy()
        # add Message-ID
        if 'Message-ID' not in headers:
            headers['Message-ID'] = [email.Utils.make_msgid()]

        if 'User-Agent' in headers:
            uastring_format = headers['User-Agent'][0]
        else:
            uastring_format = settings.get('user_agent').strip()
        uastring = uastring_format.format(version=__version__)
        if uastring:
            headers['User-Agent'] = [uastring]

        # copy headers from envelope to mail
        for k, vlist in headers.items():
            for v in vlist:
                outer_msg[k] = encode_header(k, v)

        return outer_msg