code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def verify_metadata(self): ''' Send the metadata to the package index server to be checked. ''' # send the info to the server and report the result (code, result) = self.post_to_server(self.build_post_data('verify')) log.info('Server response (%s): %s' % (code, result))
Send the metadata to the package index server to be checked.
verify_metadata
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/register.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/register.py
MIT
def send_metadata(self): ''' Send the metadata to the package index server. Well, do the following: 1. figure who the user is, and then 2. send the data as a Basic auth'ed POST. First we try to read the username/password from $HOME/.pypirc, which is a ConfigParser-formatted file with a section [distutils] containing username and password entries (both in clear text). Eg: [distutils] index-servers = pypi [pypi] username: fred password: sekrit Otherwise, to figure who the user is, we offer the user three choices: 1. use existing login, 2. register as a new user, or 3. set the password to a random string and email the user. ''' # see if we can short-cut and get the username/password from the # config if self.has_config: choice = '1' username = self.username password = self.password else: choice = 'x' username = password = '' # get the user's login info choices = '1 2 3 4'.split() while choice not in choices: self.announce('''\ We need to know who you are, so please choose either: 1. use your existing login, 2. register as a new user, 3. have the server generate a new password for you (and email it to you), or 4. quit Your selection [default 1]: ''', log.INFO) choice = raw_input() if not choice: choice = '1' elif choice not in choices: print 'Please choose one of the four options!' if choice == '1': # get the username and password while not username: username = raw_input('Username: ') while not password: password = getpass.getpass('Password: ') # set up the authentication auth = urllib2.HTTPPasswordMgr() host = urlparse.urlparse(self.repository)[1] auth.add_password(self.realm, host, username, password) # send the info to the server and report the result code, result = self.post_to_server(self.build_post_data('submit'), auth) self.announce('Server response (%s): %s' % (code, result), log.INFO) # possibly save the login if code == 200: if self.has_config: # sharing the password in the distribution instance # so the upload command can reuse it self.distribution.password = password else: self.announce(('I can store your PyPI login so future ' 'submissions will be faster.'), log.INFO) self.announce('(the login will be stored in %s)' % \ self._get_rc_file(), log.INFO) choice = 'X' while choice.lower() not in 'yn': choice = raw_input('Save your login (y/N)?') if not choice: choice = 'n' if choice.lower() == 'y': self._store_pypirc(username, password) elif choice == '2': data = {':action': 'user'} data['name'] = data['password'] = data['email'] = '' data['confirm'] = None while not data['name']: data['name'] = raw_input('Username: ') while data['password'] != data['confirm']: while not data['password']: data['password'] = getpass.getpass('Password: ') while not data['confirm']: data['confirm'] = getpass.getpass(' Confirm: ') if data['password'] != data['confirm']: data['password'] = '' data['confirm'] = None print "Password and confirm don't match!" while not data['email']: data['email'] = raw_input(' EMail: ') code, result = self.post_to_server(data) if code != 200: log.info('Server response (%s): %s' % (code, result)) else: log.info('You will receive an email shortly.') log.info(('Follow the instructions in it to ' 'complete registration.')) elif choice == '3': data = {':action': 'password_reset'} data['email'] = '' while not data['email']: data['email'] = raw_input('Your email address: ') code, result = self.post_to_server(data) log.info('Server response (%s): %s' % (code, result))
Send the metadata to the package index server. Well, do the following: 1. figure who the user is, and then 2. send the data as a Basic auth'ed POST. First we try to read the username/password from $HOME/.pypirc, which is a ConfigParser-formatted file with a section [distutils] containing username and password entries (both in clear text). Eg: [distutils] index-servers = pypi [pypi] username: fred password: sekrit Otherwise, to figure who the user is, we offer the user three choices: 1. use existing login, 2. register as a new user, or 3. set the password to a random string and email the user.
send_metadata
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/register.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/register.py
MIT
def post_to_server(self, data, auth=None): ''' Post a query to the server, and return a string response. ''' if 'name' in data: self.announce('Registering %s to %s' % (data['name'], self.repository), log.INFO) # Build up the MIME payload for the urllib2 POST data boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' sep_boundary = '\n--' + boundary end_boundary = sep_boundary + '--' chunks = [] for key, value in data.items(): # handle multiple entries for the same name if type(value) not in (type([]), type( () )): value = [value] for value in value: chunks.append(sep_boundary) chunks.append('\nContent-Disposition: form-data; name="%s"'%key) chunks.append("\n\n") chunks.append(value) if value and value[-1] == '\r': chunks.append('\n') # write an extra newline (lurve Macs) chunks.append(end_boundary) chunks.append("\n") # chunks may be bytes (str) or unicode objects that we need to encode body = [] for chunk in chunks: if isinstance(chunk, unicode): body.append(chunk.encode('utf-8')) else: body.append(chunk) body = ''.join(body) # build the Request headers = { 'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'%boundary, 'Content-length': str(len(body)) } req = urllib2.Request(self.repository, body, headers) # handle HTTP and include the Basic Auth handler opener = urllib2.build_opener( urllib2.HTTPBasicAuthHandler(password_mgr=auth) ) data = '' try: result = opener.open(req) except urllib2.HTTPError, e: if self.show_response: data = e.fp.read() result = e.code, e.msg except urllib2.URLError, e: result = 500, str(e) else: if self.show_response: data = result.read() result = 200, 'OK' if self.show_response: dashes = '-' * 75 self.announce('%s%s%s' % (dashes, data, dashes)) return result
Post a query to the server, and return a string response.
post_to_server
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/register.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/register.py
MIT
def show_formats(): """Print all possible values for the 'formats' option (used by the "--help-formats" command-line option). """ from distutils.fancy_getopt import FancyGetopt from distutils.archive_util import ARCHIVE_FORMATS formats = [] for format in ARCHIVE_FORMATS.keys(): formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2])) formats.sort() FancyGetopt(formats).print_help( "List of available source distribution formats:")
Print all possible values for the 'formats' option (used by the "--help-formats" command-line option).
show_formats
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/sdist.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/sdist.py
MIT
def get_file_list(self): """Figure out the list of files to include in the source distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options. """ # new behavior when using a template: # the file list is recalculated every time because # even if MANIFEST.in or setup.py are not changed # the user might have added some files in the tree that # need to be included. # # This makes --force the default and only behavior with templates. template_exists = os.path.isfile(self.template) if not template_exists and self._manifest_is_not_generated(): self.read_manifest() self.filelist.sort() self.filelist.remove_duplicates() return if not template_exists: self.warn(("manifest template '%s' does not exist " + "(using default file list)") % self.template) self.filelist.findall() if self.use_defaults: self.add_defaults() if template_exists: self.read_template() if self.prune: self.prune_file_list() self.filelist.sort() self.filelist.remove_duplicates() self.write_manifest()
Figure out the list of files to include in the source distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options.
get_file_list
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/sdist.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/sdist.py
MIT
def add_defaults(self): """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional. """ standards = [('README', 'README.txt'), self.distribution.script_name] for fn in standards: if isinstance(fn, tuple): alts = fn got_it = 0 for fn in alts: if os.path.exists(fn): got_it = 1 self.filelist.append(fn) break if not got_it: self.warn("standard file not found: should have one of " + string.join(alts, ', ')) else: if os.path.exists(fn): self.filelist.append(fn) else: self.warn("standard file '%s' not found" % fn) optional = ['test/test*.py', 'setup.cfg'] for pattern in optional: files = filter(os.path.isfile, glob(pattern)) if files: self.filelist.extend(files) # build_py is used to get: # - python modules # - files defined in package_data build_py = self.get_finalized_command('build_py') # getting python files if self.distribution.has_pure_modules(): self.filelist.extend(build_py.get_source_files()) # getting package_data files # (computed in build_py.data_files by build_py.finalize_options) for pkg, src_dir, build_dir, filenames in build_py.data_files: for filename in filenames: self.filelist.append(os.path.join(src_dir, filename)) # getting distribution.data_files if self.distribution.has_data_files(): for item in self.distribution.data_files: if isinstance(item, str): # plain file item = convert_path(item) if os.path.isfile(item): self.filelist.append(item) else: # a (dirname, filenames) tuple dirname, filenames = item for f in filenames: f = convert_path(f) if os.path.isfile(f): self.filelist.append(f) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') self.filelist.extend(build_ext.get_source_files()) if self.distribution.has_c_libraries(): build_clib = self.get_finalized_command('build_clib') self.filelist.extend(build_clib.get_source_files()) if self.distribution.has_scripts(): build_scripts = self.get_finalized_command('build_scripts') self.filelist.extend(build_scripts.get_source_files())
Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional.
add_defaults
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/sdist.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/sdist.py
MIT
def read_template(self): """Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by 'self.filelist', which updates itself accordingly. """ log.info("reading manifest template '%s'", self.template) template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1) try: while 1: line = template.readline() if line is None: # end of file break try: self.filelist.process_template_line(line) # the call above can raise a DistutilsTemplateError for # malformed lines, or a ValueError from the lower-level # convert_path function except (DistutilsTemplateError, ValueError) as msg: self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg)) finally: template.close()
Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by 'self.filelist', which updates itself accordingly.
read_template
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/sdist.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/sdist.py
MIT
def prune_file_list(self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.exclude_pattern(None, prefix=build.build_base) self.filelist.exclude_pattern(None, prefix=base_dir) # pruning out vcs directories # both separators are used under win32 if sys.platform == 'win32': seps = r'/|\\' else: seps = '/' vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs'] vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)
Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories
prune_file_list
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/sdist.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/sdist.py
MIT
def write_manifest(self): """Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'. """ if self._manifest_is_not_generated(): log.info("not writing to manually maintained " "manifest file '%s'" % self.manifest) return content = self.filelist.files[:] content.insert(0, '# file GENERATED by distutils, do NOT edit') self.execute(file_util.write_file, (self.manifest, content), "writing manifest file '%s'" % self.manifest)
Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'.
write_manifest
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/sdist.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/sdist.py
MIT
def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest) for line in manifest: # ignore comments and blank lines line = line.strip() if line.startswith('#') or not line: continue self.filelist.append(line) manifest.close()
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
read_manifest
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/sdist.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/sdist.py
MIT
def make_release_tree(self, base_dir, files): """Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer's source tree, but in a directory named after the distribution, containing only the files to be distributed. """ # Create all the directories under 'base_dir' necessary to # put 'files' there; the 'mkpath()' is just so we don't die # if the manifest happens to be empty. self.mkpath(base_dir) dir_util.create_tree(base_dir, files, dry_run=self.dry_run) # And walk over the list of files, either making a hard link (if # os.link exists) to each one that doesn't already exist in its # corresponding location under 'base_dir', or copying each file # that's out-of-date in 'base_dir'. (Usually, all files will be # out-of-date, because by default we blow away 'base_dir' when # we're done making the distribution archives.) if hasattr(os, 'link'): # can make hard links on this system link = 'hard' msg = "making hard links in %s..." % base_dir else: # nope, have to copy link = None msg = "copying files to %s..." % base_dir if not files: log.warn("no files to distribute -- empty manifest?") else: log.info(msg) for file in files: if not os.path.isfile(file): log.warn("'%s' not a regular file -- skipping" % file) else: dest = os.path.join(base_dir, file) self.copy_file(file, dest, link=link) self.distribution.metadata.write_pkg_info(base_dir)
Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer's source tree, but in a directory named after the distribution, containing only the files to be distributed.
make_release_tree
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/sdist.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/sdist.py
MIT
def make_distribution(self): """Create the source distribution(s). First, we create the release tree with 'make_release_tree()'; then, we create all required archive files (according to 'self.formats') from the release tree. Finally, we clean up by blowing away the release tree (unless 'self.keep_temp' is true). The list of archive files created is stored so it can be retrieved later by 'get_archive_files()'. """ # Don't warn about missing meta-data here -- should be (and is!) # done elsewhere. base_dir = self.distribution.get_fullname() base_name = os.path.join(self.dist_dir, base_dir) self.make_release_tree(base_dir, self.filelist.files) archive_files = [] # remember names of files we create # tar archive must be created last to avoid overwrite and remove if 'tar' in self.formats: self.formats.append(self.formats.pop(self.formats.index('tar'))) for fmt in self.formats: file = self.make_archive(base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group) archive_files.append(file) self.distribution.dist_files.append(('sdist', '', file)) self.archive_files = archive_files if not self.keep_temp: dir_util.remove_tree(base_dir, dry_run=self.dry_run)
Create the source distribution(s). First, we create the release tree with 'make_release_tree()'; then, we create all required archive files (according to 'self.formats') from the release tree. Finally, we clean up by blowing away the release tree (unless 'self.keep_temp' is true). The list of archive files created is stored so it can be retrieved later by 'get_archive_files()'.
make_distribution
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/distutils/command/sdist.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/distutils/command/sdist.py
MIT
def base64_len(s): """Return the length of s when it is encoded with base64.""" groups_of_3, leftover = divmod(len(s), 3) # 4 bytes out for each 3 bytes (or nonzero fraction thereof) in. # Thanks, Tim! n = groups_of_3 * 4 if leftover: n += 4 return n
Return the length of s when it is encoded with base64.
base64_len
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/base64mime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/base64mime.py
MIT
def header_encode(header, charset='iso-8859-1', keep_eols=False, maxlinelen=76, eol=NL): """Encode a single header line with Base64 encoding in a given charset. Defined in RFC 2045, this Base64 encoding is identical to normal Base64 encoding, except that each line must be intelligently wrapped (respecting the Base64 encoding), and subsequent lines must start with a space. charset names the character set to use to encode the header. It defaults to iso-8859-1. End-of-line characters (\\r, \\n, \\r\\n) will be automatically converted to the canonical email line separator \\r\\n unless the keep_eols parameter is True (the default is False). Each line of the header will be terminated in the value of eol, which defaults to "\\n". Set this to "\\r\\n" if you are using the result of this function directly in email. The resulting string will be in the form: "=?charset?b?WW/5ciBtYXp66XLrIHf8eiBhIGhhbXBzdGHuciBBIFlv+XIgbWF6euly?=\\n =?charset?b?6yB3/HogYSBoYW1wc3Rh7nIgQkMgWW/5ciBtYXp66XLrIHf8eiBhIGhh?=" with each line wrapped at, at most, maxlinelen characters (defaults to 76 characters). """ # Return empty headers unchanged if not header: return header if not keep_eols: header = fix_eols(header) # Base64 encode each line, in encoded chunks no greater than maxlinelen in # length, after the RFC chrome is added in. base64ed = [] max_encoded = maxlinelen - len(charset) - MISC_LEN max_unencoded = max_encoded * 3 // 4 for i in range(0, len(header), max_unencoded): base64ed.append(b2a_base64(header[i:i+max_unencoded])) # Now add the RFC chrome to each encoded chunk lines = [] for line in base64ed: # Ignore the last character of each line if it is a newline if line.endswith(NL): line = line[:-1] # Add the chrome lines.append('=?%s?b?%s?=' % (charset, line)) # Glue the lines together and return it. BAW: should we be able to # specify the leading whitespace in the joiner? joiner = eol + ' ' return joiner.join(lines)
Encode a single header line with Base64 encoding in a given charset. Defined in RFC 2045, this Base64 encoding is identical to normal Base64 encoding, except that each line must be intelligently wrapped (respecting the Base64 encoding), and subsequent lines must start with a space. charset names the character set to use to encode the header. It defaults to iso-8859-1. End-of-line characters (\r, \n, \r\n) will be automatically converted to the canonical email line separator \r\n unless the keep_eols parameter is True (the default is False). Each line of the header will be terminated in the value of eol, which defaults to "\n". Set this to "\r\n" if you are using the result of this function directly in email. The resulting string will be in the form: "=?charset?b?WW/5ciBtYXp66XLrIHf8eiBhIGhhbXBzdGHuciBBIFlv+XIgbWF6euly?=\n =?charset?b?6yB3/HogYSBoYW1wc3Rh7nIgQkMgWW/5ciBtYXp66XLrIHf8eiBhIGhh?=" with each line wrapped at, at most, maxlinelen characters (defaults to 76 characters).
header_encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/base64mime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/base64mime.py
MIT
def encode(s, binary=True, maxlinelen=76, eol=NL): """Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). If binary is False, end-of-line characters will be converted to the canonical email end-of-line sequence \\r\\n. Otherwise they will be left verbatim (this is the default). Each line of encoded text will end with eol, which defaults to "\\n". Set this to "\\r\\n" if you will be using the result of this function directly in an email. """ if not s: return s if not binary: s = fix_eols(s) encvec = [] max_unencoded = maxlinelen * 3 // 4 for i in range(0, len(s), max_unencoded): # BAW: should encode() inherit b2a_base64()'s dubious behavior in # adding a newline to the encoded string? enc = b2a_base64(s[i:i + max_unencoded]) if enc.endswith(NL) and eol != NL: enc = enc[:-1] + eol encvec.append(enc) return EMPTYSTRING.join(encvec)
Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). If binary is False, end-of-line characters will be converted to the canonical email end-of-line sequence \r\n. Otherwise they will be left verbatim (this is the default). Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this function directly in an email.
encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/base64mime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/base64mime.py
MIT
def decode(s, convert_eols=None): """Decode a raw base64 string. If convert_eols is set to a string value, all canonical email linefeeds, e.g. "\\r\\n", in the decoded text will be converted to the value of convert_eols. os.linesep is a good choice for convert_eols if you are decoding a text attachment. This function does not parse a full MIME header value encoded with base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality. """ if not s: return s dec = a2b_base64(s) if convert_eols: return dec.replace(CRLF, convert_eols) return dec
Decode a raw base64 string. If convert_eols is set to a string value, all canonical email linefeeds, e.g. "\r\n", in the decoded text will be converted to the value of convert_eols. os.linesep is a good choice for convert_eols if you are decoding a text attachment. This function does not parse a full MIME header value encoded with base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high level email.header class for that functionality.
decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/base64mime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/base64mime.py
MIT
def add_charset(charset, header_enc=None, body_enc=None, output_charset=None): """Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information. """ if body_enc == SHORTEST: raise ValueError('SHORTEST not allowed for body_enc') CHARSETS[charset] = (header_enc, body_enc, output_charset)
Add character set properties to the global registry. charset is the input character set, and must be the canonical name of a character set. Optional header_enc and body_enc is either Charset.QP for quoted-printable, Charset.BASE64 for base64 encoding, Charset.SHORTEST for the shortest of qp or base64 encoding, or None for no encoding. SHORTEST is only valid for header_enc. It describes how message headers and message bodies in the input charset are to be encoded. Default is no encoding. Optional output_charset is the character set that the output should be in. Conversions will proceed from input charset, to Unicode, to the output charset when the method Charset.convert() is called. The default is to output in the same character set as the input. Both input_charset and output_charset must have Unicode codec entries in the module's charset-to-codec mapping; use add_codec(charset, codecname) to add codecs the module does not know about. See the codecs module's documentation for more information.
add_charset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/charset.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/charset.py
MIT
def get_body_encoding(self): """Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate. Returns "quoted-printable" if self.body_encoding is QP. Returns "base64" if self.body_encoding is BASE64. Returns "7bit" otherwise. """ assert self.body_encoding != SHORTEST if self.body_encoding == QP: return 'quoted-printable' elif self.body_encoding == BASE64: return 'base64' else: return encode_7or8bit
Return the content-transfer-encoding used for body encoding. This is either the string `quoted-printable' or `base64' depending on the encoding used, or it is a function in which case you should call the function with a single argument, the Message object being encoded. The function should then set the Content-Transfer-Encoding header itself to whatever is appropriate. Returns "quoted-printable" if self.body_encoding is QP. Returns "base64" if self.body_encoding is BASE64. Returns "7bit" otherwise.
get_body_encoding
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/charset.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/charset.py
MIT
def convert(self, s): """Convert a string from the input_codec to the output_codec.""" if self.input_codec != self.output_codec: return unicode(s, self.input_codec).encode(self.output_codec) else: return s
Convert a string from the input_codec to the output_codec.
convert
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/charset.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/charset.py
MIT
def to_splittable(self, s): """Convert a possibly multibyte string to a safely splittable format. Uses the input_codec to try and convert the string to Unicode, so it can be safely split on character boundaries (even for multibyte characters). Returns the string as-is if it isn't known how to convert it to Unicode with the input_charset. Characters that could not be converted to Unicode will be replaced with the Unicode replacement character U+FFFD. """ if isinstance(s, unicode) or self.input_codec is None: return s try: return unicode(s, self.input_codec, 'replace') except LookupError: # Input codec not installed on system, so return the original # string unchanged. return s
Convert a possibly multibyte string to a safely splittable format. Uses the input_codec to try and convert the string to Unicode, so it can be safely split on character boundaries (even for multibyte characters). Returns the string as-is if it isn't known how to convert it to Unicode with the input_charset. Characters that could not be converted to Unicode will be replaced with the Unicode replacement character U+FFFD.
to_splittable
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/charset.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/charset.py
MIT
def from_splittable(self, ustr, to_output=True): """Convert a splittable string back into an encoded string. Uses the proper codec to try and convert the string from Unicode back into an encoded format. Return the string as-is if it is not Unicode, or if it could not be converted from Unicode. Characters that could not be converted from Unicode will be replaced with an appropriate character (usually '?'). If to_output is True (the default), uses output_codec to convert to an encoded format. If to_output is False, uses input_codec. """ if to_output: codec = self.output_codec else: codec = self.input_codec if not isinstance(ustr, unicode) or codec is None: return ustr try: return ustr.encode(codec, 'replace') except LookupError: # Output codec not installed return ustr
Convert a splittable string back into an encoded string. Uses the proper codec to try and convert the string from Unicode back into an encoded format. Return the string as-is if it is not Unicode, or if it could not be converted from Unicode. Characters that could not be converted from Unicode will be replaced with an appropriate character (usually '?'). If to_output is True (the default), uses output_codec to convert to an encoded format. If to_output is False, uses input_codec.
from_splittable
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/charset.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/charset.py
MIT
def encoded_header_len(self, s): """Return the length of the encoded header string.""" cset = self.get_output_charset() # The len(s) of a 7bit encoding is len(s) if self.header_encoding == BASE64: return email.base64mime.base64_len(s) + len(cset) + MISC_LEN elif self.header_encoding == QP: return email.quoprimime.header_quopri_len(s) + len(cset) + MISC_LEN elif self.header_encoding == SHORTEST: lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) return min(lenb64, lenqp) + len(cset) + MISC_LEN else: return len(s)
Return the length of the encoded header string.
encoded_header_len
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/charset.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/charset.py
MIT
def header_encode(self, s, convert=False): """Header-encode a string, optionally converting it to output_charset. If convert is True, the string will be converted from the input charset to the output charset automatically. This is not useful for multibyte character sets, which have line length issues (multibyte characters must be split on a character, not a byte boundary); use the high-level Header class to deal with these issues. convert defaults to False. The type of encoding (base64 or quoted-printable) will be based on self.header_encoding. """ cset = self.get_output_charset() if convert: s = self.convert(s) # 7bit/8bit encodings return the string unchanged (modulo conversions) if self.header_encoding == BASE64: return email.base64mime.header_encode(s, cset) elif self.header_encoding == QP: return email.quoprimime.header_encode(s, cset, maxlinelen=None) elif self.header_encoding == SHORTEST: lenb64 = email.base64mime.base64_len(s) lenqp = email.quoprimime.header_quopri_len(s) if lenb64 < lenqp: return email.base64mime.header_encode(s, cset) else: return email.quoprimime.header_encode(s, cset, maxlinelen=None) else: return s
Header-encode a string, optionally converting it to output_charset. If convert is True, the string will be converted from the input charset to the output charset automatically. This is not useful for multibyte character sets, which have line length issues (multibyte characters must be split on a character, not a byte boundary); use the high-level Header class to deal with these issues. convert defaults to False. The type of encoding (base64 or quoted-printable) will be based on self.header_encoding.
header_encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/charset.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/charset.py
MIT
def body_encode(self, s, convert=True): """Body-encode a string and convert it to output_charset. If convert is True (the default), the string will be converted from the input charset to output charset automatically. Unlike header_encode(), there are no issues with byte boundaries and multibyte charsets in email bodies, so this is usually pretty safe. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding. """ if convert: s = self.convert(s) # 7bit/8bit encodings return the string unchanged (module conversions) if self.body_encoding is BASE64: return email.base64mime.body_encode(s) elif self.body_encoding is QP: return email.quoprimime.body_encode(s) else: return s
Body-encode a string and convert it to output_charset. If convert is True (the default), the string will be converted from the input charset to output charset automatically. Unlike header_encode(), there are no issues with byte boundaries and multibyte charsets in email bodies, so this is usually pretty safe. The type of encoding (base64 or quoted-printable) will be based on self.body_encoding.
body_encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/charset.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/charset.py
MIT
def encode_base64(msg): """Encode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload() encdata = _bencode(orig) msg.set_payload(encdata) msg['Content-Transfer-Encoding'] = 'base64'
Encode the message's payload in Base64. Also, add an appropriate Content-Transfer-Encoding header.
encode_base64
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/encoders.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/encoders.py
MIT
def encode_quopri(msg): """Encode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header. """ orig = msg.get_payload() encdata = _qencode(orig) msg.set_payload(encdata) msg['Content-Transfer-Encoding'] = 'quoted-printable'
Encode the message's payload in quoted-printable. Also, add an appropriate Content-Transfer-Encoding header.
encode_quopri
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/encoders.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/encoders.py
MIT
def encode_7or8bit(msg): """Set the Content-Transfer-Encoding header to 7bit or 8bit.""" orig = msg.get_payload() if orig is None: # There's no payload. For backwards compatibility we use 7bit msg['Content-Transfer-Encoding'] = '7bit' return # We play a trick to make this go fast. If encoding to ASCII succeeds, we # know the data must be 7bit, otherwise treat it as 8bit. try: orig.encode('ascii') except UnicodeError: msg['Content-Transfer-Encoding'] = '8bit' else: msg['Content-Transfer-Encoding'] = '7bit'
Set the Content-Transfer-Encoding header to 7bit or 8bit.
encode_7or8bit
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/encoders.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/encoders.py
MIT
def push(self, data): """Push some new data into this object.""" # Crack into lines, but preserve the linesep characters on the end of each parts = data.splitlines(True) if not parts or not parts[0].endswith(('\n', '\r')): # No new complete lines, so just accumulate partials self._partial += parts return if self._partial: # If there are previous leftovers, complete them now self._partial.append(parts[0]) parts[0:1] = ''.join(self._partial).splitlines(True) del self._partial[:] # If the last element of the list does not end in a newline, then treat # it as a partial line. We only check for '\n' here because a line # ending with '\r' might be a line that was split in the middle of a # '\r\n' sequence (see bugs 1555570 and 1721862). if not parts[-1].endswith('\n'): self._partial = [parts.pop()] self.pushlines(parts)
Push some new data into this object.
push
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/feedparser.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/feedparser.py
MIT
def __init__(self, _factory=message.Message): """_factory is called with no arguments to create a new message obj""" self._factory = _factory self._input = BufferedSubFile() self._msgstack = [] self._parse = self._parsegen().next self._cur = None self._last = None self._headersonly = False
_factory is called with no arguments to create a new message obj
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/feedparser.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/feedparser.py
MIT
def close(self): """Parse all remaining data and return the root message object.""" self._input.close() self._call_parse() root = self._pop_message() assert not self._msgstack # Look for final set of defects if root.get_content_maintype() == 'multipart' \ and not root.is_multipart(): root.defects.append(errors.MultipartInvariantViolationDefect()) return root
Parse all remaining data and return the root message object.
close
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/feedparser.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/feedparser.py
MIT
def __init__(self, outfp, mangle_from_=True, maxheaderlen=78): """Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822. """ self._fp = outfp self._mangle_from_ = mangle_from_ self._maxheaderlen = maxheaderlen
Create the generator for message flattening. outfp is the output file-like object for writing the message to. It must have a write() method. Optional mangle_from_ is a flag that, when True (the default), escapes From_ lines in the body of the message by putting a `>' in front of them. Optional maxheaderlen specifies the longest length for a non-continued header. When a header line is longer (in characters, with tabs expanded to 8 spaces) than maxheaderlen, the header will split as defined in the Header class. Set maxheaderlen to zero to disable header wrapping. The default is 78, as recommended (but not required) by RFC 2822.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/generator.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/generator.py
MIT
def decode_header(header): """Decode a message header value without converting charset. Returns a list of (decoded_string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of the character set specified in the encoded string. An email.errors.HeaderParseError may be raised when certain decoding error occurs (e.g. a base64 decoding exception). """ # If no encoding, just return the header header = str(header) if not ecre.search(header): return [(header, None)] decoded = [] dec = '' for line in header.splitlines(): # This line might not have an encoding in it if not ecre.search(line): decoded.append((line, None)) continue parts = ecre.split(line) while parts: unenc = parts.pop(0).strip() if unenc: # Should we continue a long line? if decoded and decoded[-1][1] is None: decoded[-1] = (decoded[-1][0] + SPACE + unenc, None) else: decoded.append((unenc, None)) if parts: charset, encoding = [s.lower() for s in parts[0:2]] encoded = parts[2] dec = None if encoding == 'q': dec = email.quoprimime.header_decode(encoded) elif encoding == 'b': paderr = len(encoded) % 4 # Postel's law: add missing padding if paderr: encoded += '==='[:4 - paderr] try: dec = email.base64mime.decode(encoded) except binascii.Error: # Turn this into a higher level exception. BAW: Right # now we throw the lower level exception away but # when/if we get exception chaining, we'll preserve it. raise HeaderParseError if dec is None: dec = encoded if decoded and decoded[-1][1] == charset: decoded[-1] = (decoded[-1][0] + dec, decoded[-1][1]) else: decoded.append((dec, charset)) del parts[0:3] return decoded
Decode a message header value without converting charset. Returns a list of (decoded_string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of the character set specified in the encoded string. An email.errors.HeaderParseError may be raised when certain decoding error occurs (e.g. a base64 decoding exception).
decode_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/header.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/header.py
MIT
def make_header(decoded_seq, maxlinelen=None, header_name=None, continuation_ws=' '): """Create a Header from a sequence of pairs as returned by decode_header() decode_header() takes a header value string and returns a sequence of pairs of the format (decoded_string, charset) where charset is the string name of the character set. This function takes one of those sequence of pairs and returns a Header instance. Optional maxlinelen, header_name, and continuation_ws are as in the Header constructor. """ h = Header(maxlinelen=maxlinelen, header_name=header_name, continuation_ws=continuation_ws) for s, charset in decoded_seq: # None means us-ascii but we can simply pass it on to h.append() if charset is not None and not isinstance(charset, Charset): charset = Charset(charset) h.append(s, charset) return h
Create a Header from a sequence of pairs as returned by decode_header() decode_header() takes a header value string and returns a sequence of pairs of the format (decoded_string, charset) where charset is the string name of the character set. This function takes one of those sequence of pairs and returns a Header instance. Optional maxlinelen, header_name, and continuation_ws are as in the Header constructor.
make_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/header.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/header.py
MIT
def __unicode__(self): """Helper for the built-in unicode function.""" uchunks = [] lastcs = None for s, charset in self._chunks: # We must preserve spaces between encoded and non-encoded word # boundaries, which means for us we need to add a space when we go # from a charset to None/us-ascii, or from None/us-ascii to a # charset. Only do this for the second and subsequent chunks. nextcs = charset if uchunks: if lastcs not in (None, 'us-ascii'): if nextcs in (None, 'us-ascii'): uchunks.append(USPACE) nextcs = None elif nextcs not in (None, 'us-ascii'): uchunks.append(USPACE) lastcs = nextcs uchunks.append(unicode(s, str(charset))) return UEMPTYSTRING.join(uchunks)
Helper for the built-in unicode function.
__unicode__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/header.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/header.py
MIT
def append(self, s, charset=None, errors='strict'): """Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is true), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In this case, when producing an RFC 2822 compliant header using RFC 2047 rules, the Unicode string will be encoded using the following charsets in order: us-ascii, the charset hint, utf-8. The first character set not to provoke a UnicodeError is used. Optional `errors' is passed as the third argument to any unicode() or ustr.encode() call. """ if charset is None: charset = self._charset elif not isinstance(charset, Charset): charset = Charset(charset) # If the charset is our faux 8bit charset, leave the string unchanged if charset != '8bit': # We need to test that the string can be converted to unicode and # back to a byte string, given the input and output codecs of the # charset. if isinstance(s, str): # Possibly raise UnicodeError if the byte string can't be # converted to a unicode with the input codec of the charset. incodec = charset.input_codec or 'us-ascii' ustr = unicode(s, incodec, errors) # Now make sure that the unicode could be converted back to a # byte string with the output codec, which may be different # than the iput coded. Still, use the original byte string. outcodec = charset.output_codec or 'us-ascii' ustr.encode(outcodec, errors) elif isinstance(s, unicode): # Now we have to be sure the unicode string can be converted # to a byte string with a reasonable output codec. We want to # use the byte string in the chunk. for charset in USASCII, charset, UTF8: try: outcodec = charset.output_codec or 'us-ascii' s = s.encode(outcodec, errors) break except UnicodeError: pass else: assert False, 'utf-8 conversion failed' self._chunks.append((s, charset))
Append a string to the MIME header. Optional charset, if given, should be a Charset instance or the name of a character set (which will be converted to a Charset instance). A value of None (the default) means that the charset given in the constructor is used. s may be a byte string or a Unicode string. If it is a byte string (i.e. isinstance(s, str) is true), then charset is the encoding of that byte string, and a UnicodeError will be raised if the string cannot be decoded with that charset. If s is a Unicode string, then charset is a hint specifying the character set of the characters in the string. In this case, when producing an RFC 2822 compliant header using RFC 2047 rules, the Unicode string will be encoded using the following charsets in order: us-ascii, the charset hint, utf-8. The first character set not to provoke a UnicodeError is used. Optional `errors' is passed as the third argument to any unicode() or ustr.encode() call.
append
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/header.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/header.py
MIT
def walk(self): """Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. """ yield self if self.is_multipart(): for subpart in self.get_payload(): for subsubpart in subpart.walk(): yield subsubpart
Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator.
walk
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/iterators.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/iterators.py
MIT
def body_line_iterator(msg, decode=False): """Iterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload(). """ for subpart in msg.walk(): payload = subpart.get_payload(decode=decode) if isinstance(payload, basestring): for line in StringIO(payload): yield line
Iterate over the parts, returning string payloads line-by-line. Optional decode (default False) is passed through to .get_payload().
body_line_iterator
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/iterators.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/iterators.py
MIT
def _formatparam(param, value=None, quote=True): """Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules. """ if value is not None and len(value) > 0: # A tuple is used for RFC 2231 encoded parameter values where items # are (charset, language, value). charset is a string, not a Charset # instance. if isinstance(value, tuple): # Encode as per RFC 2231 param += '*' value = utils.encode_rfc2231(value[2], value[0], value[1]) # BAW: Please check this. I think that if quote is set it should # force quoting even if not necessary. if quote or tspecials.search(value): return '%s="%s"' % (param, utils.quote(value)) else: return '%s=%s' % (param, value) else: return param
Convenience function to format and return a key=value pair. This will quote the value if needed or if quote is true. If value is a three tuple (charset, language, value), it will be encoded according to RFC2231 rules.
_formatparam
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def as_string(self, unixfrom=False): """Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This is a convenience method and may not generate the message exactly as you intend because by default it mangles lines that begin with "From ". For more flexibility, use the flatten() method of a Generator instance. """ from email.generator import Generator fp = StringIO() g = Generator(fp) g.flatten(self, unixfrom=unixfrom) return fp.getvalue()
Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This is a convenience method and may not generate the message exactly as you intend because by default it mangles lines that begin with "From ". For more flexibility, use the flatten() method of a Generator instance.
as_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def attach(self, payload): """Add the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead. """ if self._payload is None: self._payload = [payload] else: self._payload.append(payload)
Add the given payload to the current payload. The current payload will always be a list of objects after this method is called. If you want to set the payload to a scalar object, use set_payload() instead.
attach
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def get_payload(self, i=None, decode=False): """Return a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned. """ if i is None: payload = self._payload elif not isinstance(self._payload, list): raise TypeError('Expected list, got %s' % type(self._payload)) else: payload = self._payload[i] if decode: if self.is_multipart(): return None cte = self.get('content-transfer-encoding', '').lower() if cte == 'quoted-printable': return utils._qdecode(payload) elif cte == 'base64': try: return utils._bdecode(payload) except binascii.Error: # Incorrect padding return payload elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'): sfp = StringIO() try: uu.decode(StringIO(payload+'\n'), sfp, quiet=True) payload = sfp.getvalue() except uu.Error: # Some decoding problem return payload # Everything else, including encodings with 8bit or 7bit are returned # unchanged. return payload
Return a reference to the payload. The payload will either be a list object or a string. If you mutate the list object, you modify the message's payload in place. Optional i returns that index into the payload. Optional decode is a flag indicating whether the payload should be decoded or not, according to the Content-Transfer-Encoding header (default is False). When True and the message is not a multipart, the payload will be decoded if this header's value is `quoted-printable' or `base64'. If some other encoding is used, or the header is missing, or if the payload has bogus data (i.e. bogus base64 or uuencoded data), the payload is returned as-is. If the message is a multipart and the decode flag is True, then None is returned.
get_payload
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def set_payload(self, payload, charset=None): """Set the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details. """ self._payload = payload if charset is not None: self.set_charset(charset)
Set the payload to the given value. Optional charset sets the message's default character set. See set_charset() for details.
set_payload
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def set_charset(self, charset): """Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed. """ if charset is None: self.del_param('charset') self._charset = None return if isinstance(charset, basestring): charset = email.charset.Charset(charset) if not isinstance(charset, email.charset.Charset): raise TypeError(charset) # BAW: should we accept strings that can serve as arguments to the # Charset constructor? self._charset = charset if 'MIME-Version' not in self: self.add_header('MIME-Version', '1.0') if 'Content-Type' not in self: self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) if isinstance(self._payload, unicode): self._payload = self._payload.encode(charset.output_charset) if str(charset) != charset.get_output_charset(): self._payload = charset.body_encode(self._payload) if 'Content-Transfer-Encoding' not in self: cte = charset.get_body_encoding() try: cte(self) except TypeError: self._payload = charset.body_encode(self._payload) self.add_header('Content-Transfer-Encoding', cte)
Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be removed from the Content-Type field. Anything else will generate a TypeError. The message will be assumed to be of type text/* encoded with charset.input_charset. It will be converted to charset.output_charset and encoded properly, if needed, when generating the plain text representation of the message. MIME headers (MIME-Version, Content-Type, Content-Transfer-Encoding) will be added as needed.
set_charset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def __delitem__(self, name): """Delete all occurrences of a header, if present. Does not raise an exception if the header is missing. """ name = name.lower() newheaders = [] for k, v in self._headers: if k.lower() != name: newheaders.append((k, v)) self._headers = newheaders
Delete all occurrences of a header, if present. Does not raise an exception if the header is missing.
__delitem__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def has_key(self, name): """Return true if the message contains the header.""" missing = object() return self.get(name, missing) is not missing
Return true if the message contains the header.
has_key
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def get(self, name, failobj=None): """Get a header value. Like __getitem__() but return failobj instead of None when the field is missing. """ name = name.lower() for k, v in self._headers: if k.lower() == name: return v return failobj
Get a header value. Like __getitem__() but return failobj instead of None when the field is missing.
get
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def get_all(self, name, failobj=None): """Return a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None). """ values = [] name = name.lower() for k, v in self._headers: if k.lower() == name: values.append(v) if not values: return failobj return values
Return a list of all the values for the named field. These will be sorted in the order they appeared in the original message, and may contain duplicates. Any fields deleted and re-inserted are always appended to the header list. If no such fields exist, failobj is returned (defaults to None).
get_all
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def add_header(self, _name, _value, **_params): """Extended header setting. name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. If a parameter value contains non-ASCII characters it must be specified as a three-tuple of (charset, language, value), in which case it will be encoded according to RFC2231 rules. Example: msg.add_header('content-disposition', 'attachment', filename='bud.gif') """ parts = [] for k, v in _params.items(): if v is None: parts.append(k.replace('_', '-')) else: parts.append(_formatparam(k.replace('_', '-'), v)) if _value is not None: parts.insert(0, _value) self._headers.append((_name, SEMISPACE.join(parts)))
Extended header setting. name is the header field to add. keyword arguments can be used to set additional parameters for the header field, with underscores converted to dashes. Normally the parameter will be added as key="value" unless value is None, in which case only the key will be added. If a parameter value contains non-ASCII characters it must be specified as a three-tuple of (charset, language, value), in which case it will be encoded according to RFC2231 rules. Example: msg.add_header('content-disposition', 'attachment', filename='bud.gif')
add_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def replace_header(self, _name, _value): """Replace a header. Replace the first matching header found in the message, retaining header order and case. If no matching header was found, a KeyError is raised. """ _name = _name.lower() for i, (k, v) in zip(range(len(self._headers)), self._headers): if k.lower() == _name: self._headers[i] = (k, _value) break else: raise KeyError(_name)
Replace a header. Replace the first matching header found in the message, retaining header order and case. If no matching header was found, a KeyError is raised.
replace_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def get_content_type(self): """Return the message's content type. The returned string is coerced to lower case of the form `maintype/subtype'. If there was no Content-Type header in the message, the default type as given by get_default_type() will be returned. Since according to RFC 2045, messages always have a default type this will always return a value. RFC 2045 defines a message's default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822. """ missing = object() value = self.get('content-type', missing) if value is missing: # This should have no parameters return self.get_default_type() ctype = _splitparam(value)[0].lower() # RFC 2045, section 5.2 says if its invalid, use text/plain if ctype.count('/') != 1: return 'text/plain' return ctype
Return the message's content type. The returned string is coerced to lower case of the form `maintype/subtype'. If there was no Content-Type header in the message, the default type as given by get_default_type() will be returned. Since according to RFC 2045, messages always have a default type this will always return a value. RFC 2045 defines a message's default type to be text/plain unless it appears inside a multipart/digest container, in which case it would be message/rfc822.
get_content_type
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def get_params(self, failobj=None, header='content-type', unquote=True): """Return the message's Content-Type parameters, as a list. The elements of the returned list are 2-tuples of key/value pairs, as split on the `=' sign. The left hand side of the `=' is the key, while the right hand side is the value. If there is no `=' sign in the parameter the value is the empty string. The value is as described in the get_param() method. Optional failobj is the object to return if there is no Content-Type header. Optional header is the header to search instead of Content-Type. If unquote is True, the value is unquoted. """ missing = object() params = self._get_params_preserve(missing, header) if params is missing: return failobj if unquote: return [(k, _unquotevalue(v)) for k, v in params] else: return params
Return the message's Content-Type parameters, as a list. The elements of the returned list are 2-tuples of key/value pairs, as split on the `=' sign. The left hand side of the `=' is the key, while the right hand side is the value. If there is no `=' sign in the parameter the value is the empty string. The value is as described in the get_param() method. Optional failobj is the object to return if there is no Content-Type header. Optional header is the header to search instead of Content-Type. If unquote is True, the value is unquoted.
get_params
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def get_param(self, param, failobj=None, header='content-type', unquote=True): """Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 encoded. When it's a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE. Your application should be prepared to deal with 3-tuple return values, and can convert the parameter to a Unicode string like so: param = msg.get_param('foo') if isinstance(param, tuple): param = unicode(param[2], param[0] or 'us-ascii') In any case, the parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False. """ if header not in self: return failobj for k, v in self._get_params_preserve(failobj, header): if k.lower() == param.lower(): if unquote: return _unquotevalue(v) else: return v return failobj
Return the parameter value if found in the Content-Type header. Optional failobj is the object to return if there is no Content-Type header, or the Content-Type header has no such parameter. Optional header is the header to search instead of Content-Type. Parameter keys are always compared case insensitively. The return value can either be a string, or a 3-tuple if the parameter was RFC 2231 encoded. When it's a 3-tuple, the elements of the value are of the form (CHARSET, LANGUAGE, VALUE). Note that both CHARSET and LANGUAGE can be None, in which case you should consider VALUE to be encoded in the us-ascii charset. You can usually ignore LANGUAGE. Your application should be prepared to deal with 3-tuple return values, and can convert the parameter to a Unicode string like so: param = msg.get_param('foo') if isinstance(param, tuple): param = unicode(param[2], param[0] or 'us-ascii') In any case, the parameter value (either the returned string, or the VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False.
get_param
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def set_param(self, param, value, header='Content-Type', requote=True, charset=None, language=''): """Set a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with the new value. If header is Content-Type and has not yet been defined for this message, it will be set to "text/plain" and the new parameter and value will be appended as per RFC 2045. An alternate header can be specified in the header argument, and all parameters will be quoted as necessary unless requote is False. If charset is specified, the parameter will be encoded according to RFC 2231. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings. """ if not isinstance(value, tuple) and charset: value = (charset, language, value) if header not in self and header.lower() == 'content-type': ctype = 'text/plain' else: ctype = self.get(header) if not self.get_param(param, header=header): if not ctype: ctype = _formatparam(param, value, requote) else: ctype = SEMISPACE.join( [ctype, _formatparam(param, value, requote)]) else: ctype = '' for old_param, old_value in self.get_params(header=header, unquote=requote): append_param = '' if old_param.lower() == param.lower(): append_param = _formatparam(param, value, requote) else: append_param = _formatparam(old_param, old_value, requote) if not ctype: ctype = append_param else: ctype = SEMISPACE.join([ctype, append_param]) if ctype != self.get(header): del self[header] self[header] = ctype
Set a parameter in the Content-Type header. If the parameter already exists in the header, its value will be replaced with the new value. If header is Content-Type and has not yet been defined for this message, it will be set to "text/plain" and the new parameter and value will be appended as per RFC 2045. An alternate header can be specified in the header argument, and all parameters will be quoted as necessary unless requote is False. If charset is specified, the parameter will be encoded according to RFC 2231. Optional language specifies the RFC 2231 language, defaulting to the empty string. Both charset and language should be strings.
set_param
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def del_param(self, param, header='content-type', requote=True): """Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header. """ if header not in self: return new_ctype = '' for p, v in self.get_params(header=header, unquote=requote): if p.lower() != param.lower(): if not new_ctype: new_ctype = _formatparam(p, v, requote) else: new_ctype = SEMISPACE.join([new_ctype, _formatparam(p, v, requote)]) if new_ctype != self.get(header): del self[header] self[header] = new_ctype
Remove the given parameter completely from the Content-Type header. The header will be re-written in place without the parameter or its value. All values will be quoted as necessary unless requote is False. Optional header specifies an alternative to the Content-Type header.
del_param
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def set_type(self, type, header='Content-Type', requote=True): """Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. This method replaces the Content-Type header, keeping all the parameters in place. If requote is False, this leaves the existing header's quoting as is. Otherwise, the parameters will be quoted (the default). An alternative header can be specified in the header argument. When the Content-Type header is set, we'll always also add a MIME-Version header. """ # BAW: should we be strict? if not type.count('/') == 1: raise ValueError # Set the Content-Type, you get a MIME-Version if header.lower() == 'content-type': del self['mime-version'] self['MIME-Version'] = '1.0' if header not in self: self[header] = type return params = self.get_params(header=header, unquote=requote) del self[header] self[header] = type # Skip the first param; it's the old type. for p, v in params[1:]: self.set_param(p, v, header, requote)
Set the main type and subtype for the Content-Type header. type must be a string in the form "maintype/subtype", otherwise a ValueError is raised. This method replaces the Content-Type header, keeping all the parameters in place. If requote is False, this leaves the existing header's quoting as is. Otherwise, the parameters will be quoted (the default). An alternative header can be specified in the header argument. When the Content-Type header is set, we'll always also add a MIME-Version header.
set_type
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def get_filename(self, failobj=None): """Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header's `filename' parameter, and it is unquoted. If that header is missing the `filename' parameter, this method falls back to looking for the `name' parameter. """ missing = object() filename = self.get_param('filename', missing, 'content-disposition') if filename is missing: filename = self.get_param('name', missing, 'content-type') if filename is missing: return failobj return utils.collapse_rfc2231_value(filename).strip()
Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header's `filename' parameter, and it is unquoted. If that header is missing the `filename' parameter, this method falls back to looking for the `name' parameter.
get_filename
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def get_boundary(self, failobj=None): """Return the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted. """ missing = object() boundary = self.get_param('boundary', missing) if boundary is missing: return failobj # RFC 2046 says that boundaries may begin but not end in w/s return utils.collapse_rfc2231_value(boundary).rstrip()
Return the boundary associated with the payload if present. The boundary is extracted from the Content-Type header's `boundary' parameter, and it is unquoted.
get_boundary
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def set_boundary(self, boundary): """Set the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header. """ missing = object() params = self._get_params_preserve(missing, 'content-type') if params is missing: # There was no Content-Type header, and we don't know what type # to set it to, so raise an exception. raise errors.HeaderParseError('No Content-Type header found') newparams = [] foundp = False for pk, pv in params: if pk.lower() == 'boundary': newparams.append(('boundary', '"%s"' % boundary)) foundp = True else: newparams.append((pk, pv)) if not foundp: # The original Content-Type header had no boundary attribute. # Tack one on the end. BAW: should we raise an exception # instead??? newparams.append(('boundary', '"%s"' % boundary)) # Replace the existing Content-Type header with the new value newheaders = [] for h, v in self._headers: if h.lower() == 'content-type': parts = [] for k, v in newparams: if v == '': parts.append(k) else: parts.append('%s=%s' % (k, v)) newheaders.append((h, SEMISPACE.join(parts))) else: newheaders.append((h, v)) self._headers = newheaders
Set the boundary parameter in Content-Type to 'boundary'. This is subtly different than deleting the Content-Type header and adding a new one with a new boundary parameter via add_header(). The main difference is that using the set_boundary() method preserves the order of the Content-Type header in the original message. HeaderParseError is raised if the message has no Content-Type header.
set_boundary
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def get_content_charset(self, failobj=None): """Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned. """ missing = object() charset = self.get_param('charset', missing) if charset is missing: return failobj if isinstance(charset, tuple): # RFC 2231 encoded, so decode it, and it better end up as ascii. pcharset = charset[0] or 'us-ascii' try: # LookupError will be raised if the charset isn't known to # Python. UnicodeError will be raised if the encoded text # contains a character not in the charset. charset = unicode(charset[2], pcharset).encode('us-ascii') except (LookupError, UnicodeError): charset = charset[2] # charset character must be in us-ascii range try: if isinstance(charset, str): charset = unicode(charset, 'us-ascii') charset = charset.encode('us-ascii') except UnicodeError: return failobj # RFC 2046, $4.1.2 says charsets are not case sensitive return charset.lower()
Return the charset parameter of the Content-Type header. The returned string is always coerced to lower case. If there is no Content-Type header, or if that header has no charset parameter, failobj is returned.
get_content_charset
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/message.py
MIT
def __init__(self, *args, **kws): """Parser of RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The string must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from' header. The header block is terminated either by the end of the string or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message. """ if len(args) >= 1: if '_class' in kws: raise TypeError("Multiple values for keyword arg '_class'") kws['_class'] = args[0] if len(args) == 2: if 'strict' in kws: raise TypeError("Multiple values for keyword arg 'strict'") kws['strict'] = args[1] if len(args) > 2: raise TypeError('Too many arguments') if '_class' in kws: self._class = kws['_class'] del kws['_class'] else: self._class = Message if 'strict' in kws: warnings.warn("'strict' argument is deprecated (and ignored)", DeprecationWarning, 2) del kws['strict'] if kws: raise TypeError('Unexpected keyword arguments')
Parser of RFC 2822 and MIME email messages. Creates an in-memory object tree representing the email message, which can then be manipulated and turned over to a Generator to return the textual representation of the message. The string must be formatted as a block of RFC 2822 headers and header continuation lines, optionally preceded by a `Unix-from' header. The header block is terminated either by the end of the string or by a blank line. _class is the class to instantiate for new message objects when they must be created. This class must have a constructor that can take zero arguments. Default is Message.Message.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/parser.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/parser.py
MIT
def parse(self, fp, headersonly=False): """Create a message structure from the data in a file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file. """ feedparser = FeedParser(self._class) if headersonly: feedparser._set_headersonly() while True: data = fp.read(8192) if not data: break feedparser.feed(data) return feedparser.close()
Create a message structure from the data in a file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the entire contents of the file.
parse
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/parser.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/parser.py
MIT
def header_quopri_len(s): """Return the length of str when it is encoded with header quopri.""" count = 0 for c in s: if hqre.match(c): count += 3 else: count += 1 return count
Return the length of str when it is encoded with header quopri.
header_quopri_len
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/quoprimime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/quoprimime.py
MIT
def body_quopri_len(str): """Return the length of str when it is encoded with body quopri.""" count = 0 for c in str: if bqre.match(c): count += 3 else: count += 1 return count
Return the length of str when it is encoded with body quopri.
body_quopri_len
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/quoprimime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/quoprimime.py
MIT
def header_encode(header, charset="iso-8859-1", keep_eols=False, maxlinelen=76, eol=NL): """Encode a single header line with quoted-printable (like) encoding. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but used specifically for email header fields to allow charsets with mostly 7 bit characters (and some 8 bit) to remain more or less readable in non-RFC 2045 aware mail clients. charset names the character set to use to encode the header. It defaults to iso-8859-1. The resulting string will be in the form: "=?charset?q?I_f=E2rt_in_your_g=E8n=E8ral_dire=E7tion?\\n =?charset?q?Silly_=C8nglish_Kn=EEghts?=" with each line wrapped safely at, at most, maxlinelen characters (defaults to 76 characters). If maxlinelen is None, the entire string is encoded in one chunk with no splitting. End-of-line characters (\\r, \\n, \\r\\n) will be automatically converted to the canonical email line separator \\r\\n unless the keep_eols parameter is True (the default is False). Each line of the header will be terminated in the value of eol, which defaults to "\\n". Set this to "\\r\\n" if you are using the result of this function directly in email. """ # Return empty headers unchanged if not header: return header if not keep_eols: header = fix_eols(header) # Quopri encode each line, in encoded chunks no greater than maxlinelen in # length, after the RFC chrome is added in. quoted = [] if maxlinelen is None: # An obnoxiously large number that's good enough max_encoded = 100000 else: max_encoded = maxlinelen - len(charset) - MISC_LEN - 1 for c in header: # Space may be represented as _ instead of =20 for readability if c == ' ': _max_append(quoted, '_', max_encoded) # These characters can be included verbatim elif not hqre.match(c): _max_append(quoted, c, max_encoded) # Otherwise, replace with hex value like =E2 else: _max_append(quoted, "=%02X" % ord(c), max_encoded) # Now add the RFC chrome to each encoded chunk and glue the chunks # together. BAW: should we be able to specify the leading whitespace in # the joiner? joiner = eol + ' ' return joiner.join(['=?%s?q?%s?=' % (charset, line) for line in quoted])
Encode a single header line with quoted-printable (like) encoding. Defined in RFC 2045, this `Q' encoding is similar to quoted-printable, but used specifically for email header fields to allow charsets with mostly 7 bit characters (and some 8 bit) to remain more or less readable in non-RFC 2045 aware mail clients. charset names the character set to use to encode the header. It defaults to iso-8859-1. The resulting string will be in the form: "=?charset?q?I_f=E2rt_in_your_g=E8n=E8ral_dire=E7tion?\n =?charset?q?Silly_=C8nglish_Kn=EEghts?=" with each line wrapped safely at, at most, maxlinelen characters (defaults to 76 characters). If maxlinelen is None, the entire string is encoded in one chunk with no splitting. End-of-line characters (\r, \n, \r\n) will be automatically converted to the canonical email line separator \r\n unless the keep_eols parameter is True (the default is False). Each line of the header will be terminated in the value of eol, which defaults to "\n". Set this to "\r\n" if you are using the result of this function directly in email.
header_encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/quoprimime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/quoprimime.py
MIT
def encode(body, binary=False, maxlinelen=76, eol=NL): """Encode with quoted-printable, wrapping at maxlinelen characters. If binary is False (the default), end-of-line characters will be converted to the canonical email end-of-line sequence \\r\\n. Otherwise they will be left verbatim. Each line of encoded text will end with eol, which defaults to "\\n". Set this to "\\r\\n" if you will be using the result of this function directly in an email. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Long lines will have the `soft linefeed' quoted-printable character "=" appended to them, so the decoded text will be identical to the original text. """ if not body: return body if not binary: body = fix_eols(body) # BAW: We're accumulating the body text by string concatenation. That # can't be very efficient, but I don't have time now to rewrite it. It # just feels like this algorithm could be more efficient. encoded_body = '' lineno = -1 # Preserve line endings here so we can check later to see an eol needs to # be added to the output later. lines = body.splitlines(1) for line in lines: # But strip off line-endings for processing this line. if line.endswith(CRLF): line = line[:-2] elif line[-1] in CRLF: line = line[:-1] lineno += 1 encoded_line = '' prev = None linelen = len(line) # Now we need to examine every character to see if it needs to be # quopri encoded. BAW: again, string concatenation is inefficient. for j in range(linelen): c = line[j] prev = c if bqre.match(c): c = quote(c) elif j+1 == linelen: # Check for whitespace at end of line; special case if c not in ' \t': encoded_line += c prev = c continue # Check to see to see if the line has reached its maximum length if len(encoded_line) + len(c) >= maxlinelen: encoded_body += encoded_line + '=' + eol encoded_line = '' encoded_line += c # Now at end of line.. if prev and prev in ' \t': # Special case for whitespace at end of file if lineno + 1 == len(lines): prev = quote(prev) if len(encoded_line) + len(prev) > maxlinelen: encoded_body += encoded_line + '=' + eol + prev else: encoded_body += encoded_line + prev # Just normal whitespace at end of line else: encoded_body += encoded_line + prev + '=' + eol encoded_line = '' # Now look at the line we just finished and it has a line ending, we # need to add eol to the end of the line. if lines[lineno].endswith(CRLF) or lines[lineno][-1] in CRLF: encoded_body += encoded_line + eol else: encoded_body += encoded_line encoded_line = '' return encoded_body
Encode with quoted-printable, wrapping at maxlinelen characters. If binary is False (the default), end-of-line characters will be converted to the canonical email end-of-line sequence \r\n. Otherwise they will be left verbatim. Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this function directly in an email. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Long lines will have the `soft linefeed' quoted-printable character "=" appended to them, so the decoded text will be identical to the original text.
encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/quoprimime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/quoprimime.py
MIT
def decode(encoded, eol=NL): """Decode a quoted-printable string. Lines are separated with eol, which defaults to \\n. """ if not encoded: return encoded # BAW: see comment in encode() above. Again, we're building up the # decoded string with string concatenation, which could be done much more # efficiently. decoded = '' for line in encoded.splitlines(): line = line.rstrip() if not line: decoded += eol continue i = 0 n = len(line) while i < n: c = line[i] if c != '=': decoded += c i += 1 # Otherwise, c == "=". Are we at the end of the line? If so, add # a soft line break. elif i+1 == n: i += 1 continue # Decode if in form =AB elif i+2 < n and line[i+1] in hexdigits and line[i+2] in hexdigits: decoded += unquote(line[i:i+3]) i += 3 # Otherwise, not in form =AB, pass literally else: decoded += c i += 1 if i == n: decoded += eol # Special case if original string did not end with eol if not encoded.endswith(eol) and decoded.endswith(eol): decoded = decoded[:-1] return decoded
Decode a quoted-printable string. Lines are separated with eol, which defaults to \n.
decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/quoprimime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/quoprimime.py
MIT
def header_decode(s): """Decode a string encoded with RFC 2045 MIME header `Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use the high level email.header class for that functionality. """ s = s.replace('_', ' ') return re.sub(r'=[a-fA-F0-9]{2}', _unquote_match, s)
Decode a string encoded with RFC 2045 MIME header `Q' encoding. This function does not parse a full MIME header value encoded with quoted-printable (like =?iso-8895-1?q?Hello_World?=) -- please use the high level email.header class for that functionality.
header_decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/quoprimime.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/quoprimime.py
MIT
def _bdecode(s): """Decodes a base64 string. This function is equivalent to base64.decodestring and it's retained only for backward compatibility. It used to remove the last \\n of the decoded string, if it had any (see issue 7143). """ if not s: return s return base64.decodestring(s)
Decodes a base64 string. This function is equivalent to base64.decodestring and it's retained only for backward compatibility. It used to remove the last \n of the decoded string, if it had any (see issue 7143).
_bdecode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/utils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py
MIT
def fix_eols(s): """Replace all line-ending characters with \\r\\n.""" # Fix newlines with no preceding carriage return s = re.sub(r'(?<!\r)\n', CRLF, s) # Fix carriage returns with no following newline s = re.sub(r'\r(?!\n)', CRLF, s) return s
Replace all line-ending characters with \r\n.
fix_eols
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/utils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py
MIT
def formataddr(pair): """The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for an RFC 2822 From, To or Cc header. If the first element of pair is false, then the second element is returned unmodified. """ name, address = pair if name: quotes = '' if specialsre.search(name): quotes = '"' name = escapesre.sub(r'\\\g<0>', name) return '%s%s%s <%s>' % (quotes, name, quotes, address) return address
The inverse of parseaddr(), this takes a 2-tuple of the form (realname, email_address) and returns the string value suitable for an RFC 2822 From, To or Cc header. If the first element of pair is false, then the second element is returned unmodified.
formataddr
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/utils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py
MIT
def getaddresses(fieldvalues): """Return a list of (REALNAME, EMAIL) for each fieldvalue.""" all = COMMASPACE.join(fieldvalues) a = _AddressList(all) return a.addresslist
Return a list of (REALNAME, EMAIL) for each fieldvalue.
getaddresses
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/utils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py
MIT
def formatdate(timeval=None, localtime=False, usegmt=False): """Returns a date string as specified by RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by gmtime() and localtime(), otherwise the current time is used. Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead of UTC, properly taking daylight savings time into account. Optional argument usegmt means that the timezone is written out as an ascii string, not numeric one (so "GMT" instead of "+0000"). This is needed for HTTP, and is only used when localtime==False. """ # Note: we cannot use strftime() because that honors the locale and RFC # 2822 requires that day and month names be the English abbreviations. if timeval is None: timeval = time.time() if localtime: now = time.localtime(timeval) # Calculate timezone offset, based on whether the local zone has # daylight savings time, and whether DST is in effect. if time.daylight and now[-1]: offset = time.altzone else: offset = time.timezone hours, minutes = divmod(abs(offset), 3600) # Remember offset is in seconds west of UTC, but the timezone is in # minutes east of UTC, so the signs differ. if offset > 0: sign = '-' else: sign = '+' zone = '%s%02d%02d' % (sign, hours, minutes // 60) else: now = time.gmtime(timeval) # Timezone offset is always -0000 if usegmt: zone = 'GMT' else: zone = '-0000' return '%s, %02d %s %04d %02d:%02d:%02d %s' % ( ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]], now[2], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1], now[0], now[3], now[4], now[5], zone)
Returns a date string as specified by RFC 2822, e.g.: Fri, 09 Nov 2001 01:08:47 -0000 Optional timeval if given is a floating point time value as accepted by gmtime() and localtime(), otherwise the current time is used. Optional localtime is a flag that when True, interprets timeval, and returns a date relative to the local timezone instead of UTC, properly taking daylight savings time into account. Optional argument usegmt means that the timezone is written out as an ascii string, not numeric one (so "GMT" instead of "+0000"). This is needed for HTTP, and is only used when localtime==False.
formatdate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/utils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py
MIT
def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. """ timeval = int(time.time()*100) pid = os.getpid() randint = random.getrandbits(64) if idstring is None: idstring = '' else: idstring = '.' + idstring idhost = socket.getfqdn() msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, idhost) return msgid
Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id.
make_msgid
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/utils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py
MIT
def encode_rfc2231(s, charset=None, language=None): """Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language. """ import urllib s = urllib.quote(s, safe='') if charset is None and language is None: return s if language is None: language = '' return "%s'%s'%s" % (charset, language, s)
Encode string according to RFC 2231. If neither charset nor language is given, then s is returned as-is. If charset is given but not language, the string is encoded using the empty string for language.
encode_rfc2231
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/utils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py
MIT
def decode_params(params): """Decode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value). """ # Copy params so we don't mess with the original params = params[:] new_params = [] # Map parameter's name to a list of continuations. The values are a # 3-tuple of the continuation number, the string value, and a flag # specifying whether a particular segment is %-encoded. rfc2231_params = {} name, value = params.pop(0) new_params.append((name, value)) while params: name, value = params.pop(0) if name.endswith('*'): encoded = True else: encoded = False value = unquote(value) mo = rfc2231_continuation.match(name) if mo: name, num = mo.group('name', 'num') if num is not None: num = int(num) rfc2231_params.setdefault(name, []).append((num, value, encoded)) else: new_params.append((name, '"%s"' % quote(value))) if rfc2231_params: for name, continuations in rfc2231_params.items(): value = [] extended = False # Sort by number continuations.sort() # And now append all values in numerical order, converting # %-encodings for the encoded segments. If any of the # continuation names ends in a *, then the entire string, after # decoding segments and concatenating, must have the charset and # language specifiers at the beginning of the string. for num, s, encoded in continuations: if encoded: s = urllib.unquote(s) extended = True value.append(s) value = quote(EMPTYSTRING.join(value)) if extended: charset, language, value = decode_rfc2231(value) new_params.append((name, (charset, language, '"%s"' % value))) else: new_params.append((name, '"%s"' % value)) return new_params
Decode parameters list according to RFC 2231. params is a sequence of 2-tuples containing (param name, string value).
decode_params
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/utils.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/utils.py
MIT
def parsedate_tz(data): """Convert a date string to a time tuple. Accounts for military timezones. """ data = data.split() # The FWS after the comma after the day-of-week is optional, so search and # adjust for this. if data[0].endswith(',') or data[0].lower() in _daynames: # There's a dayname here. Skip it del data[0] else: i = data[0].rfind(',') if i >= 0: data[0] = data[0][i+1:] if len(data) == 3: # RFC 850 date, deprecated stuff = data[0].split('-') if len(stuff) == 3: data = stuff + data[1:] if len(data) == 4: s = data[3] i = s.find('+') if i > 0: data[3:] = [s[:i], s[i+1:]] else: data.append('') # Dummy tz if len(data) < 5: return None data = data[:5] [dd, mm, yy, tm, tz] = data mm = mm.lower() if mm not in _monthnames: dd, mm = mm, dd.lower() if mm not in _monthnames: return None mm = _monthnames.index(mm) + 1 if mm > 12: mm -= 12 if dd[-1] == ',': dd = dd[:-1] i = yy.find(':') if i > 0: yy, tm = tm, yy if yy[-1] == ',': yy = yy[:-1] if not yy[0].isdigit(): yy, tz = tz, yy if tm[-1] == ',': tm = tm[:-1] tm = tm.split(':') if len(tm) == 2: [thh, tmm] = tm tss = '0' elif len(tm) == 3: [thh, tmm, tss] = tm else: return None try: yy = int(yy) dd = int(dd) thh = int(thh) tmm = int(tmm) tss = int(tss) except ValueError: return None # Check for a yy specified in two-digit format, then convert it to the # appropriate four-digit format, according to the POSIX standard. RFC 822 # calls for a two-digit yy, but RFC 2822 (which obsoletes RFC 822) # mandates a 4-digit yy. For more information, see the documentation for # the time module. if yy < 100: # The year is between 1969 and 1999 (inclusive). if yy > 68: yy += 1900 # The year is between 2000 and 2068 (inclusive). else: yy += 2000 tzoffset = None tz = tz.upper() if tz in _timezones: tzoffset = _timezones[tz] else: try: tzoffset = int(tz) except ValueError: pass # Convert a timezone offset into seconds ; -0500 -> -18000 if tzoffset: if tzoffset < 0: tzsign = -1 tzoffset = -tzoffset else: tzsign = 1 tzoffset = tzsign * ( (tzoffset//100)*3600 + (tzoffset % 100)*60) # Daylight Saving Time flag is set to -1, since DST is unknown. return yy, mm, dd, thh, tmm, tss, 0, 1, -1, tzoffset
Convert a date string to a time tuple. Accounts for military timezones.
parsedate_tz
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/_parseaddr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/_parseaddr.py
MIT
def parsedate(data): """Convert a time string to a time tuple.""" t = parsedate_tz(data) if isinstance(t, tuple): return t[:9] else: return t
Convert a time string to a time tuple.
parsedate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/_parseaddr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/_parseaddr.py
MIT
def mktime_tz(data): """Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.""" if data[9] is None: # No zone info, so localtime is better assumption than GMT return time.mktime(data[:8] + (-1,)) else: t = calendar.timegm(data) return t - data[9]
Turn a 10-tuple as returned by parsedate_tz() into a POSIX timestamp.
mktime_tz
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/_parseaddr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/_parseaddr.py
MIT
def __init__(self, field): """Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses. """ self.specials = '()<>@,:;.\"[]' self.pos = 0 self.LWS = ' \t' self.CR = '\r\n' self.FWS = self.LWS + self.CR self.atomends = self.specials + self.LWS + self.CR # Note that RFC 2822 now specifies `.' as obs-phrase, meaning that it # is obsolete syntax. RFC 2822 requires that we recognize obsolete # syntax, so allow dots in phrases. self.phraseends = self.atomends.replace('.', '') self.field = field self.commentlist = []
Initialize a new instance. `field' is an unparsed address header field, containing one or more addresses.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/_parseaddr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/_parseaddr.py
MIT
def gotonext(self): """Parse up to the start of the next address.""" while self.pos < len(self.field): if self.field[self.pos] in self.LWS + '\n\r': self.pos += 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) else: break
Parse up to the start of the next address.
gotonext
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/_parseaddr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/_parseaddr.py
MIT
def getaddrlist(self): """Parse all addresses. Returns a list containing all of the addresses. """ result = [] while self.pos < len(self.field): ad = self.getaddress() if ad: result += ad else: result.append(('', '')) return result
Parse all addresses. Returns a list containing all of the addresses.
getaddrlist
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/_parseaddr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/_parseaddr.py
MIT
def getrouteaddr(self): """Parse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec. """ if self.field[self.pos] != '<': return expectroute = False self.pos += 1 self.gotonext() adlist = '' while self.pos < len(self.field): if expectroute: self.getdomain() expectroute = False elif self.field[self.pos] == '>': self.pos += 1 break elif self.field[self.pos] == '@': self.pos += 1 expectroute = True elif self.field[self.pos] == ':': self.pos += 1 else: adlist = self.getaddrspec() self.pos += 1 break self.gotonext() return adlist
Parse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec.
getrouteaddr
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/_parseaddr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/_parseaddr.py
MIT
def getdomain(self): """Get the complete domain name from an address.""" sdlist = [] while self.pos < len(self.field): if self.field[self.pos] in self.LWS: self.pos += 1 elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) elif self.field[self.pos] == '[': sdlist.append(self.getdomainliteral()) elif self.field[self.pos] == '.': self.pos += 1 sdlist.append('.') elif self.field[self.pos] in self.atomends: break else: sdlist.append(self.getatom()) return EMPTYSTRING.join(sdlist)
Get the complete domain name from an address.
getdomain
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/_parseaddr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/_parseaddr.py
MIT
def getphraselist(self): """Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space. """ plist = [] while self.pos < len(self.field): if self.field[self.pos] in self.FWS: self.pos += 1 elif self.field[self.pos] == '"': plist.append(self.getquote()) elif self.field[self.pos] == '(': self.commentlist.append(self.getcomment()) elif self.field[self.pos] in self.phraseends: break else: plist.append(self.getatom(self.phraseends)) return plist
Parse a sequence of RFC 2822 phrases. A phrase is a sequence of words, which are in turn either RFC 2822 atoms or quoted-strings. Phrases are canonicalized by squeezing all runs of continuous whitespace into one space.
getphraselist
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/_parseaddr.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/_parseaddr.py
MIT
def message_from_string(s, *args, **kws): """Parse a string into a Message object model. Optional _class and strict are passed to the Parser constructor. """ from email.parser import Parser return Parser(*args, **kws).parsestr(s)
Parse a string into a Message object model. Optional _class and strict are passed to the Parser constructor.
message_from_string
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/__init__.py
MIT
def message_from_file(fp, *args, **kws): """Read a file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor. """ from email.parser import Parser return Parser(*args, **kws).parse(fp)
Read a file and parse its contents into a Message object model. Optional _class and strict are passed to the Parser constructor.
message_from_file
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/__init__.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/__init__.py
MIT
def __init__(self, _data, _subtype='octet-stream', _encoder=encoders.encode_base64, **_params): """Create an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: raise TypeError('Invalid application MIME subtype') MIMENonMultipart.__init__(self, 'application', _subtype, **_params) self.set_payload(_data) _encoder(self)
Create an application/* type MIME document. _data is a string containing the raw application data. _subtype is the MIME content type subtype, defaulting to 'octet-stream'. _encoder is a function which will perform the actual encoding for transport of the application data, defaulting to base64 encoding. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/mime/application.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/mime/application.py
MIT
def _whatsnd(data): """Try to identify a sound file type. sndhdr.what() has a pretty cruddy interface, unfortunately. This is why we re-do it here. It would be easier to reverse engineer the Unix 'file' command and use the standard 'magic' file, as shipped with a modern Unix. """ hdr = data[:512] fakefile = StringIO(hdr) for testfn in sndhdr.tests: res = testfn(hdr, fakefile) if res is not None: return _sndhdr_MIMEmap.get(res[0]) return None
Try to identify a sound file type. sndhdr.what() has a pretty cruddy interface, unfortunately. This is why we re-do it here. It would be easier to reverse engineer the Unix 'file' command and use the standard 'magic' file, as shipped with a modern Unix.
_whatsnd
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/mime/audio.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/mime/audio.py
MIT
def __init__(self, _audiodata, _subtype=None, _encoder=encoders.encode_base64, **_params): """Create an audio/* type MIME document. _audiodata is a string containing the raw audio data. If this data can be decoded by the standard Python `sndhdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter. If _subtype is not given, and no subtype can be guessed, a TypeError is raised. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: _subtype = _whatsnd(_audiodata) if _subtype is None: raise TypeError('Could not find audio MIME subtype') MIMENonMultipart.__init__(self, 'audio', _subtype, **_params) self.set_payload(_audiodata) _encoder(self)
Create an audio/* type MIME document. _audiodata is a string containing the raw audio data. If this data can be decoded by the standard Python `sndhdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific audio subtype via the _subtype parameter. If _subtype is not given, and no subtype can be guessed, a TypeError is raised. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/mime/audio.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/mime/audio.py
MIT
def __init__(self, _maintype, _subtype, **_params): """This constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the keyword arguments. """ message.Message.__init__(self) ctype = '%s/%s' % (_maintype, _subtype) self.add_header('Content-Type', ctype, **_params) self['MIME-Version'] = '1.0'
This constructor adds a Content-Type: and a MIME-Version: header. The Content-Type: header is taken from the _maintype and _subtype arguments. Additional parameters for this header are taken from the keyword arguments.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/mime/base.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/mime/base.py
MIT
def __init__(self, _imagedata, _subtype=None, _encoder=encoders.encode_base64, **_params): """Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: _subtype = imghdr.what(None, _imagedata) if _subtype is None: raise TypeError('Could not guess image MIME subtype') MIMENonMultipart.__init__(self, 'image', _subtype, **_params) self.set_payload(_imagedata) _encoder(self)
Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/mime/image.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/mime/image.py
MIT
def __init__(self, _msg, _subtype='rfc822'): """Create a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822). """ MIMENonMultipart.__init__(self, 'message', _subtype) if not isinstance(_msg, message.Message): raise TypeError('Argument is not an instance of Message') # It's convenient to use this base class method. We need to do it # this way or we'll get an exception message.Message.attach(self, _msg) # And be sure our default type is set correctly self.set_default_type('message/rfc822')
Create a message/* type MIME document. _msg is a message object and must be an instance of Message, or a derived class of Message, otherwise a TypeError is raised. Optional _subtype defines the subtype of the contained message. The default is "rfc822" (this is defined by the MIME standard, even though the term "rfc822" is technically outdated by RFC 2822).
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/mime/message.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/mime/message.py
MIT
def __init__(self, _subtype='mixed', boundary=None, _subparts=None, **_params): """Creates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument). """ MIMEBase.__init__(self, 'multipart', _subtype, **_params) # Initialise _payload to an empty list as the Message superclass's # implementation of is_multipart assumes that _payload is a list for # multipart messages. self._payload = [] if _subparts: for p in _subparts: self.attach(p) if boundary: self.set_boundary(boundary)
Creates a multipart/* type message. By default, creates a multipart/mixed message, with proper Content-Type and MIME-Version headers. _subtype is the subtype of the multipart content type, defaulting to `mixed'. boundary is the multipart boundary string. By default it is calculated as needed. _subparts is a sequence of initial subparts for the payload. It must be an iterable object, such as a list. You can always attach new subparts to the message by using the attach() method. Additional parameters for the Content-Type header are taken from the keyword arguments (or passed into the _params argument).
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/mime/multipart.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/mime/multipart.py
MIT
def __init__(self, _text, _subtype='plain', _charset='us-ascii'): """Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will also be set. """ MIMENonMultipart.__init__(self, 'text', _subtype, **{'charset': _charset}) self.set_payload(_text, _charset)
Create a text/* type MIME document. _text is the string for this message object. _subtype is the MIME sub content type, defaulting to "plain". _charset is the character set parameter added to the Content-Type header. This defaults to "us-ascii". Note that as a side-effect, the Content-Transfer-Encoding header will also be set.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/email/mime/text.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/email/mime/text.py
MIT
def base64_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = base64.encodestring(input) return (output, len(input))
Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec.
base64_encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/encodings/base64_codec.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/encodings/base64_codec.py
MIT
def base64_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = base64.decodestring(input) return (output, len(input))
Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec.
base64_decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/encodings/base64_codec.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/encodings/base64_codec.py
MIT
def bz2_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = bz2.compress(input) return (output, len(input))
Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec.
bz2_encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/encodings/bz2_codec.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/encodings/bz2_codec.py
MIT
def bz2_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = bz2.decompress(input) return (output, len(input))
Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec.
bz2_decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/encodings/bz2_codec.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/encodings/bz2_codec.py
MIT
def hex_encode(input,errors='strict'): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = binascii.b2a_hex(input) return (output, len(input))
Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec.
hex_encode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/encodings/hex_codec.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/encodings/hex_codec.py
MIT
def hex_decode(input,errors='strict'): """ Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' output = binascii.a2b_hex(input) return (output, len(input))
Decodes the object input and returns a tuple (output object, length consumed). input must be an object which provides the bf_getreadbuf buffer slot. Python strings, buffer objects and memory mapped files are examples of objects providing this slot. errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec.
hex_decode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/encodings/hex_codec.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/encodings/hex_codec.py
MIT