def __ne__(self, other): return not self.__eq__(other) 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 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 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 _isunicode(s) 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 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 _isunicode(ustr) or codec is None: return ustr try: return ustr.encode(codec, 'replace') except LookupError: # Output codec not installed return ustr def get_output_charset(self): """Return the output character set. This is self.output_charset if that is not None, otherwise it is self.input_charset. """ return self.output_charset or self.input_charset 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) 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) 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) else: return s 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.header_encoding is QP: return email.quopriMIME.body_encode(s) else: return s # Copyright (C) 2001,2002 Python Software Foundation # Author: barry@zope.com (Barry Warsaw) """Module containing encoding functions for Image.Image and Text.Text. """ import base64 # Helpers try: from quopri import encodestring as _encodestring def _qencode(s): enc = _encodestring(s, quotetabs=1) # Must encode spaces, which quopri.encodestring() doesn't do return enc.replace(' ', '=20') except ImportError: # Python 2.1 doesn't have quopri.encodestring() from cStringIO import StringIO import quopri as _quopri def _qencode(s): if not s: return s hasnewline = (s[-1] == '\n') infp = StringIO(s) outfp = StringIO() _quopri.encode(infp, outfp, quotetabs=1) # Python 2.x's encode() doesn't encode spaces even when quotetabs==1 value = outfp.getvalue().replace(' ', '=20') if not hasnewline and value[-1] == '\n': return value[:-1] return value def _bencode(s): # We can't quite use base64.encodestring() since it tacks on a "courtesy # newline". Blech! if not s: return s hasnewline = (s[-1] == '\n') value = base64.encodestring(s) if not hasnewline and value[-1] == '\n': return value[:-1] return value 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' 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' 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' def encode_noop(msg): """Do nothing.""" # Copyright (C) 2001,2002 Python Software Foundation # Author: barry@zope.com (Barry Warsaw) """email package exception classes. """ class MessageError(Exception): """Base class for errors in the email package.""" class MessageParseError(MessageError): """Base class for message parsing errors.""" class HeaderParseError(MessageParseError): """Error while parsing headers.""" class BoundaryError(MessageParseError): """Couldn't find terminating boundary.""" class MultipartConversionError(MessageError, TypeError): """Conversion to a multipart is prohibited.""" # Copyright (C) 2001,2002 Python Software Foundation # Author: barry@zope.com (Barry Warsaw) """Classes to generate plain text from a message object tree. """ import time import re import random from types import ListType, StringType from cStringIO import StringIO from email.Header import Header try: from email._compat22 import _isstring except SyntaxError: from email._compat21 import _isstring try: True, False except NameError: True = 1 False = 0 EMPTYSTRING = '' SEMISPACE = '; ' BAR = '|' UNDERSCORE = '_' NL = '\n' NLTAB = '\n\t' SEMINLTAB = ';\n\t' SPACE8 = ' ' * 8 fcre = re.compile(r'^From ', re.MULTILINE) def _is8bitstring(s): if isinstance(s, StringType): try: unicode(s, 'us-ascii') except UnicodeError: return True return False class Generator: """Generates output from a Message object tree. This basic generator writes the message to the given file object as plain text. """ # # Public interface # 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 be broken on semicolons and continued as per RFC 2822. If no semicolon is found, then the header is left alone. Set to zero to disable wrapping headers. Default is 78, as recommended (but not required by RFC 2822. """ self._fp = outfp self._mangle_from_ = mangle_from_ self.__maxheaderlen = maxheaderlen def write(self, s): # Just delegate to the file object self._fp.write(s) def flatten(self, msg, unixfrom=False): """Print the message object tree rooted at msg to the output file specified when the Generator instance was created. unixfrom is a flag that forces the printing of a Unix From_ delimiter before the first object in the message tree. If the original message has no From_ delimiter, a `standard' one is crafted. By default, this is False to inhibit the printing of any From_ delimiter. Note that for subobjects, no From_ line is printed. """ if unixfrom: ufrom = msg.get_unixfrom() if not ufrom: ufrom = 'From nobody ' + time.ctime(time.time()) print >> self._fp, ufrom self._write(msg) # For backwards compatibility, but this is slower __call__ = flatten def clone(self, fp): """Clone this generator with the exact same options.""" return self.__class__(fp, self._mangle_from_, self.__maxheaderlen) # # Protected interface - undocumented ;/ # def _write(self, msg): # We can't write the headers yet because of the following scenario: # say a multipart message includes the boundary string somewhere in # its body. We'd have to calculate the new boundary /before/ we write # the headers so that we can write the correct Content-Type: # parameter. # # The way we do this, so as to make the _handle_*() methods simpler, # is to cache any subpart writes into a StringIO. The we write the # headers and the StringIO contents. That way, subpart handlers can # Do The Right Thing, and can still modify the Content-Type: header if # necessary. oldfp = self._fp try: self._fp = sfp = StringIO() self._dispatch(msg) finally: self._fp = oldfp # Write the headers. First we see if the message object wants to # handle that itself. If not, we'll do it generically. meth = getattr(msg, '_write_headers', None) if meth is None: self._write_headers(msg) else: meth(self) self._fp.write(sfp.getvalue()) def _dispatch(self, msg): # Get the Content-Type: for the message, then try to dispatch to # self._handle__(). If there's no handler for the # full MIME type, then dispatch to self._handle_(). If # that's missing too, then dispatch to self._writeBody(). main = msg.get_content_maintype() sub = msg.get_content_subtype() specific = UNDERSCORE.join((main, sub)).replace('-', '_') meth = getattr(self, '_handle_' + specific, None) if meth is None: generic = main.replace('-', '_') meth = getattr(self, '_handle_' + generic, None) if meth is None: meth = self._writeBody meth(msg) # # Default handlers # def _write_headers(self, msg): for h, v in msg.items(): # RFC 2822 says that lines SHOULD be no more than maxheaderlen # characters wide, so we're well within our rights to split long # headers. text = '%s: %s' % (h, v) if self.__maxheaderlen > 0 and len(text) > self.__maxheaderlen: text = self._split_header(text) print >> self._fp, text # A blank line always separates headers from body print >> self._fp def _split_header(self, text): maxheaderlen = self.__maxheaderlen # Find out whether any lines in the header are really longer than # maxheaderlen characters wide. There could be continuation lines # that actually shorten it. Also, replace hard tabs with 8 spaces. lines = [s.replace('\t', SPACE8) for s in text.splitlines()] for line in lines: if len(line) > maxheaderlen: break else: # No line was actually longer than maxheaderlen characters, so # just return the original unchanged. return text # If we have raw 8bit data in a byte string, we have no idea what the # encoding is. I think there is no safe way to split this string. If # it's ascii-subset, then we could do a normal ascii split, but if # it's multibyte then we could break the string. There's no way to # know so the least harm seems to be to not split the string and risk # it being too long. if _is8bitstring(text): return text # The `text' argument already has the field name prepended, so don't # provide it here or the first line will get folded too short. h = Header(text, maxlinelen=maxheaderlen, # For backwards compatibility, we use a hard tab here continuation_ws='\t') return h.encode() # # Handlers for writing types and subtypes # def _handle_text(self, msg): payload = msg.get_payload() if payload is None: return cset = msg.get_charset() if cset is not None: payload = cset.body_encode(payload) if not _isstring(payload): raise TypeError, 'string payload expected: %s' % type(payload) if self._mangle_from_: payload = fcre.sub('>From ', payload) self._fp.write(payload) # Default body handler _writeBody = _handle_text def _handle_multipart(self, msg): # The trick here is to write out each part separately, merge them all # together, and then make sure that the boundary we've chosen isn't # present in the payload. msgtexts = [] subparts = msg.get_payload() if subparts is None: # Nothing has ever been attached boundary = msg.get_boundary(failobj=_make_boundary()) print >> self._fp, '--' + boundary print >> self._fp, '\n' print >> self._fp, '--' + boundary + '--' return elif _isstring(subparts): # e.g. a non-strict parse of a message with no starting boundary. self._fp.write(subparts) return elif not isinstance(subparts, ListType): # Scalar payload subparts = [subparts] for part in subparts: s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) msgtexts.append(s.getvalue()) # Now make sure the boundary we've selected doesn't appear in any of # the message texts. alltext = NL.join(msgtexts) # BAW: What about boundaries that are wrapped in double-quotes? boundary = msg.get_boundary(failobj=_make_boundary(alltext)) # If we had to calculate a new boundary because the body text # contained that string, set the new boundary. We don't do it # unconditionally because, while set_boundary() preserves order, it # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. if msg.get_boundary() <> boundary: msg.set_boundary(boundary) # Write out any preamble if msg.preamble is not None: self._fp.write(msg.preamble) # First boundary is a bit different; it doesn't have a leading extra # newline. print >> self._fp, '--' + boundary # Join and write the individual parts joiner = '\n--' + boundary + '\n' self._fp.write(joiner.join(msgtexts)) print >> self._fp, '\n--' + boundary + '--', # Write out any epilogue if msg.epilogue is not None: if not msg.epilogue.startswith('\n'): print >> self._fp self._fp.write(msg.epilogue) def _handle_message_delivery_status(self, msg): # We can't just write the headers directly to self's file object # because this will leave an extra newline between the last header # block and the boundary. Sigh. blocks = [] for part in msg.get_payload(): s = StringIO() g = self.clone(s) g.flatten(part, unixfrom=False) text = s.getvalue() lines = text.split('\n') # Strip off the unnecessary trailing empty line if lines and lines[-1] == '': blocks.append(NL.join(lines[:-1])) else: blocks.append(text) # Now join all the blocks with an empty line. This has the lovely # effect of separating each block with an empty line, but not adding # an extra one after the last one. self._fp.write(NL.join(blocks)) def _handle_message(self, msg): s = StringIO() g = self.clone(s) # The payload of a message/rfc822 part should be a multipart sequence # of length 1. The zeroth element of the list should be the Message # object for the subpart. Extract that object, stringify it, and # write it out. g.flatten(msg.get_payload(0), unixfrom=False) self._fp.write(s.getvalue()) class DecodedGenerator(Generator): """Generator a text representation of a message. Like the Generator base class, except that non-text parts are substituted with a format string representing the part. """ def __init__(self, outfp, mangle_from_=True, maxheaderlen=78, fmt=None): """Like Generator.__init__() except that an additional optional argument is allowed. Walks through all subparts of a message. If the subpart is of main type `text', then it prints the decoded payload of the subpart. Otherwise, fmt is a format string that is used instead of the message payload. fmt is expanded with the following keywords (in %(keyword)s format): type : Full MIME type of the non-text part maintype : Main MIME type of the non-text part subtype : Sub-MIME type of the non-text part filename : Filename of the non-text part description: Description associated with the non-text part encoding : Content transfer encoding of the non-text part The default value for fmt is None, meaning [Non-text (%(type)s) part of message omitted, filename %(filename)s] """ Generator.__init__(self, outfp, mangle_from_, maxheaderlen) if fmt is None: fmt = ('[Non-text (%(type)s) part of message omitted, ' 'filename %(filename)s]') self._fmt = fmt def _dispatch(self, msg): for part in msg.walk(): maintype = part.get_main_type('text') if maintype == 'text': print >> self, part.get_payload(decode=True) elif maintype == 'multipart': # Just skip this pass else: print >> self, self._fmt % { 'type' : part.get_type('[no MIME type]'), 'maintype' : part.get_main_type('[no main MIME type]'), 'subtype' : part.get_subtype('[no sub-MIME type]'), 'filename' : part.get_filename('[no filename]'), 'description': part.get('Content-Description', '[no description]'), 'encoding' : part.get('Content-Transfer-Encoding', '[no encoding]'), } # Helper def _make_boundary(text=None): # Craft a random boundary. If text is given, ensure that the chosen # boundary doesn't appear in the text. boundary = ('=' * 15) + repr(random.random()).split('.')[1] + '==' if text is None: return boundary b = boundary counter = 0 while True: cre = re.compile('^--' + re.escape(b) + '(--)?$', re.MULTILINE) if not cre.search(text): break b = boundary + '.' + str(counter) counter += 1 return b ur residence, even if you use it for business. F4835 \ N601Vet, breeding, medicine The costs of veterinary services, medicine and breeding fees. Help F4952 \ H425Form 4952 - investment interest Form 4952 is used to compute the amount of investment interest expense deductible for the current year and the amount, if any, to carry forward to future years. F4952 \ N426Investment interest expense The investment interest paid or accrued during the tax year, regardless of when you incurred the indebtedness. Investment interest is interest paid or accrued on a loan (or part of a loan) that is allocable to property held for investment. Help F6252 \ H427Form 6252 - income from casual sales Form 6252 is used to report income from casual sales of real or personal property when you will receive any payments in a tax year after the year of sale (i.e., installment sale). F6252 \ N432Expenses of sale Enter sales commissions, advertising expenses, attorney and legal fees, etc., in selling the property. Help F8815 \ H441Form 8815 - EE U.S. savings bonds sold for education Form 8815 is used to compute the amount of interest you may exclude if you cashed series EE U.S. savings bonds this year that were issued after 1989 to pay for qualified higher education costs. F8815 \ N442Qualified higher education expenses Qualified higher education expenses include tuition and fees required for the enrollment or attendance of the person(s). Do not include expenses for room and board, or courses involving sports, games, or hobbies that are not part of a degree or certificate granting program. Help F8829 \ H536Form 8829 - business use of your home Form 8829 is used only if you file a Schedule C, Profit or Loss from Business, and you meet specific requirements to deduct expenses for the business use of your home. IRS rules are stringent for this deduction. Refer to IRS Publication 587. F8829 \ N537Deductible mortgage interest The total amount of mortgage interest that would be deductible whether or not you used your home for business (i.e., amounts allowable as itemized deductions on Schedule A, Form 1040). Form 8829 computes the deductible business portion. F8829 \ N539Insurance The total amount of insurance paid for your home, in which an area or room is used regularly and exclusively for business. Form 8829 computes the deductible business portion. F8829 \ N542Other expenses If you rent rather than own your home, include rent paid for your home, in which an area or room is used regularly and exclusively for business. Form 8829 computes the deductible business portion. F8829 \ N538Real estate taxes The total amount of real estate taxes that would be deductible whether or not you used your home for business (i.e., amounts allowable as itemized deductions on Schedule A, Form 1040). Form 8829 computes the deductible business portion. F8829 \ N540Repairs and maintenance The total amount of repairs and maintenance paid for your home, in which an area or room is used regularly and exclusively for business. Form 8829 computes the deductible business portion. F8829 \ N541Utilities The total amount of utilities paid for your home, in which an area or room is used regularly and exclusively for business. Form 8829 computes the deductible business portion. Help F8839 \ H617Form 8839 - adoption expenses Form 8839 is used to report qualified adoption expenses. F8839 \ N618Adoption fees Adoption fees that are reasonable and necessary, directly related to, and for the principal purpose of, the legal adoption of an eligible child. F8839 \ N620Attorney fees Attorney fees that are reasonable and necessary, directly related to, and for the principal purpose of, the legal adoption of an eligible child. F8839 \ N619