Save a message file out, without mangling the headers
18611
def save_file(fullpath, entry):
    
    with tempfile.NamedTemporaryFile('w', delete=False) as file:
        tmpfile = file.name
        # we can't just use file.write(str(entry)) because otherwise the
        # headers "helpfully" do MIME encoding normalization.
        # str(val) is necessary to get around email.header's encoding
        # shenanigans
        for key, val in entry.items():
            print('{}: {}'.format(key, str(val)), file=file)
        print('', file=file)
        file.write(entry.get_payload())
    shutil.move(tmpfile, fullpath)
9118
def save(self, outfile):
        """"""
        if isinstance(outfile, compat.string_type):
            outfile = open(outfile, 'wb')
        assert hasattr(outfile, 'write') and callable(outfile.write), \
            "Expect a file or file-like object with a .write() method"
        outfile.write(self.data)
360584
def save_to_file(destination_filename, append=False):
    

    def decorator_fn(f):
        @wraps(f)
        def wrapper_fn(*args, **kwargs):
            res = f(*args, **kwargs)

            makedirs(os.path.dirname(destination_filename))
            mode = "a" if append else "w"
            with open(destination_filename, mode) as text_file:
                text_file.write(res)

            return res

        return wrapper_fn

    return decorator_fn
1038030
def from_httplib(cls, message):  # Python 2
        """"""
        # python2.7 does not expose a proper API for exporting multiheaders
        # efficiently. This function re-reads raw lines from the message
        # object and extracts the multiheaders properly.
        headers = []

        for line in message.headers:
            if line.startswith((' ', '\t')):
                key, value = headers[-1]
                headers[-1] = (key, value + '\r\n' + line.rstrip())
                continue

            key, value = line.split(':', 1)
            headers.append((key, value.strip()))

        return cls(headers)
819190
def write_source(self, filename):
        '''
        
        '''
        with open(filename, 'w') as fp:
            return json.dump(self.message._elem, fp, indent=4, sort_keys=True)
177980
def save(self, outfile):
        """"""
        if isinstance(outfile, compat.string_type):
            outfile = open(outfile, 'wb')
        outfile.write(compat.urllib2.urlopen(self.href).read())
374011
def prepare_message(user, useralias, addresses, subject, contents, attachments, headers, encoding, newline_to_break=True):
    # check if closed!!!!!! XXX
    
    if isinstance(contents, text_type):
        contents = [contents]
    if isinstance(attachments, text_type):
        attachments = [attachments]

    # merge contents and attachments for now.
    if attachments is not None:
        for a in attachments:
            if not os.path.isfile(a):
                raise TypeError("'{0}' is not a valid filepath".format(a))
        contents = attachments if contents is None else contents + attachments

    has_included_images, content_objects = prepare_contents(contents, encoding)
    msg = MIMEMultipart()
    if headers is not None:
        # Strangely, msg does not have an update method, so then manually.
        for k, v in headers.items():
            msg[k] = v
    if headers is None or "Date" not in headers:
        msg["Date"] = formatdate()

    msg_alternative = MIMEMultipart("alternative")
    msg_related = MIMEMultipart("related")
    msg_related.attach("-- HTML goes here --")
    msg.attach(msg_alternative)
    add_subject(msg, subject)
    add_recipients_headers(user, useralias, msg, addresses)
    htmlstr = ""
    altstr = []
    if has_included_images:
        msg.preamble = "This message is best displayed using a MIME capable email reader."

    if contents is not None:
        for content_object, content_string in zip(content_objects, contents):
            if content_object["main_type"] == "image":
                # all image objects need base64 encoding, so do it now
                email.encoders.encode_base64(content_object["mime_object"])
                # aliased image {'path' : 'alias'}
                if isinstance(content_string, dict) and len(content_string) == 1:
                    for key in content_string:
                        hashed_ref = str(abs(hash(key)))
                        alias = content_string[key]
                    # pylint: disable=undefined-loop-variable
                    content_string = key
                else:
                    alias = os.path.basename(str(content_string))
                    hashed_ref = str(abs(hash(alias)))

                # TODO: I should probably remove inline now that there is "attachments"
                # if string is `inline`, inline, else, attach
                # pylint: disable=unidiomatic-typecheck
                if type(content_string) == inline:
                    htmlstr += '<img src="cid:{0}" title="{1}"/>'.format(hashed_ref, alias)
                    content_object["mime_object"].add_header(
                        "Content-ID", "<{0}>".format(hashed_ref)
                    )
                    altstr.append("-- img {0} should be here -- ".format(alias))
                    # inline images should be in related MIME block
                    msg_related.attach(content_object["mime_object"])
                else:
                    # non-inline images get attached like any other attachment
                    msg.attach(content_object["mime_object"])

            else:
                if content_object["encoding"] == "base64":
                    email.encoders.encode_base64(content_object["mime_object"])
                    msg.attach(content_object["mime_object"])
                elif content_object["sub_type"] not in ["html", "plain"]:
                    msg.attach(content_object["mime_object"])
                else:
                    if newline_to_break:
                        content_string = content_string.replace("\n", "<br>")
                    try:
                        htmlstr += "<div>{0}</div>".format(content_string)
                    except UnicodeEncodeError:
                        htmlstr += u"<div>{0}</div>".format(content_string)
                    altstr.append(content_string)

    msg_related.get_payload()[0] = MIMEText(htmlstr, "html", _charset=encoding)
    msg_alternative.attach(MIMEText("\n".join(altstr), _charset=encoding))
    msg_alternative.attach(msg_related)
    return msg
1044127
def save(self, *args):
        
        with open(self.file_root + '.pkl', "wb") as f:
            pickle.dump(args, f, protocol=pickle.HIGHEST_PROTOCOL)
819323
def dump(cls, message):
        
        if cls.verbose > 2:
            msg = '[DUMP] %s' % message
            cls.echo(msg)
1032697
def save(self, outfile):
        """"""
        if isinstance(outfile, compat.string_type):
            outfile = open(outfile, 'wb')
        outfile.write(self._contents)
1289657
def _verbose_message(message, *args, **kwargs):
    """"""
    verbosity = kwargs.pop('verbosity', 1)
    if sys.flags.verbose >= verbosity:
        if not message.startswith(('#', 'import ')):
            message = '# ' + message
        print(message.format(*args), file=sys.stderr)
807829
def on_message(self, headers, body):
        
        self.__sysout('')
        if 'filename' in headers:
            content = base64.b64decode(body.encode())
            if os.path.exists(headers['filename']):
                fname = '%s.%s' % (headers['filename'], int(time.time()))
            else:
                fname = headers['filename']
            with open(fname, 'wb') as f:
                f.write(content)
            self.__print_async("MESSAGE", headers, "Saved file: %s" % fname)
        else:
            self.__print_async("MESSAGE", headers, body)
400302
def save_as_header(self, response, **kwargs):
        
        save_as = kwargs.get('save_as', None)
        if save_as is False:
            return
        file_obj = kwargs.get('file_obj', None)
        if save_as is True or save_as is None:
            filename = os.path.basename(file_obj.path)
        else:
            filename = save_as
        response['Content-Disposition'] = smart_str(
            'attachment; filename=%s' % filename)
981751
def save(self):
        """"""
        with open(self.file_name, 'w') as fp:
            self.parser.write(fp)
        return self
1168283
def dump(self, msg):
        '''
        
        '''
        msg_size = len(msg)

        # We start a new batch if the resulting batch file is larger than the
        # max batch file size. However, if the current batch file size is zero
        # then that means the message alone is larger than the max batch file
        # size. In this case instead of splitting up the message across files
        # which would greatly increase complexity we simply dump that message
        # into a file of its own even though it will be larger than the max
        # batch file size.
        if self._batch_size + msg_size > self._max_batch_file_size \
                and self._batch_size > 0:
            self._startNewBatch()

        # Write the time stamp and information on how to retrieve the message
        # from the batch files (batch filename, byte offset, and byte size)
        global getTime
        index_file_entry = '{:},{:09d},{:},{:}\n'.format(
            getTime(), self._batch_index, self._batch_size, msg_size)
        if sys.version_info >= (3,):
            self._index_file.write(index_file_entry.encode('utf-8'))
        else:
            self._index_file.write(index_file_entry)

        # Dump the message itself to the current batch file
        self._batch_file.write(msg)
        self._batch_size += msg_size

        # Increment message count
        self._message_count += 1
1067126
def save_tsv(p, vs):
    ''
    delim = options.get('delimiter', vs)
    trdict = tsv_trdict(vs)

    save_tsv_header(p, vs)

    with p.open_text(mode='a') as fp:
        for dispvals in genAllValues(vs.rows, vs.visibleCols, trdict, format=True):
            fp.write(delim.join(dispvals))
            fp.write('\n')

    status('%s save finished' % p)
1023268
def dump(self, f, name):
        """"""
        # print the header line
        value = self.get()
        kind = self.get_kind(value)
        print("% 40s  kind=%s  value=%s" % (name, kind, value), file=f)