My app works fine when its a .py file, however as soon as I compile it with py2exe 0.6.9 I get LookupErrors when using the email MIME library. I tried including the "packages": ["encodings"] option in py2exe but to no avail. I'll post the relevant code and traceback.

(note: not an original script)

EMAILER:

# -*- coding: utf-8 -*-
from os.path import exists, basename
import smtplib
import mimetypes
##from email import *
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.encoders import encode_base64



def sendMail(gmailUser, gmailPassword, recipient, subject, text, *attachmentFilePaths):


   msg = MIMEMultipart()
   msg['From'] = gmailUser
   msg['To'] = recipient
   msg['Subject'] = subject
   msg.attach( MIMEText(text) )

   for attachmentFilePath in attachmentFilePaths:
      if exists( attachmentFilePath ):
         msg.attach(getAttachment(attachmentFilePath))

   mailServer = smtplib.SMTP('smtp.gmail.com', 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmailUser, gmailPassword)
   mailServer.sendmail(gmailUser, recipient, msg.as_string())
   mailServer.close()

   print('Sent email to %s' % recipient)

def getAttachment(attachmentFilePath):
   contentType, encoding = mimetypes.guess_type(attachmentFilePath)

   if contentType is None or encoding is not None:
      contentType = 'application/octet-stream'

   mainType, subType = contentType.split('/', 1)
   file = open(attachmentFilePath, 'rb')


   fileText = file.read()
   if mainType == 'text':
      attachment = MIMEText(fileText)
   elif mainType == 'message':
      attachment = email.message_from_file(file)
   elif mainType == 'image':
      attachment = MIMEImage(fileText,_subType=subType)
   elif mainType == 'audio':
      attachment = MIMEAudio(fileText,_subType=subType)
   else:
      attachment = MIMEBase(mainType, subType)
   attachment = MIMEBase(mainType, subType)
   attachment.set_payload(fileText)




   encode_base64(attachment)

   file.close()

   attachment.add_header('Content-Disposition', 'attachment',   filename=basename(attachmentFilePath))
   return attachment

PY2EXE script:

#!/usr/bin/env python
#
import sys, time, py2exe
from distutils.core import setup
from os import listdir
from os.path import realpath, basename


# tried this as a last ditch effort, no luck....
if raw_input("would you like to include the encodings package?\n") == 'yes':
    try:
        # if this doesn't work, try import modulefinder
        import py2exe.mf as modulefinder
        import encodings
        for p in encodings.__path__[1:]:
            modulefinder.AddPackagePath("encodings", p)
        for extra in ["encodings"]:
            __import__(extra)
            m = sys.modules[extra]
            for p in m.__path__[1:]:
                modulefinder.AddPackagePath(extra, p)
    except ImportError:
        # no build path setup, no worries.
        pass



progdir = realpath('')
progname= basename(progdir)

def GetPythonFiles():
    return [ x for x in listdir('') if IsPy( x ) and x != progname ]

def IsPy( name ):
    name = name.lower()
    return name.endswith('.pyw') or name.endswith('.py')


for eachfile in GetPythonFiles():
    if raw_input("use "+eachfile+'  ') == 'yes':
        
        entry_point = eachfile
        sys.argv.pop()
        sys.argv.append(eachfile)
        sys.argv.append('py2exe')
        sys.argv.append('-q')

        

        opts = {
            'py2exe': {
                'compressed': 1,
                'optimize': 2,
                # 'ascii': 1,
                'bundle_files': 1,
                'packages': ['encodings', 'codecs']
            }
        }


        setup(console=[entry_point], options=opts, zipfile=None)
        print eachfile, "has been compiled."
        break
raw_input("program completed...")

TRACEBACK:

Traceback (most recent call last):
File "Courier.py", line 46, in SubmitStatusReport
File "googlemail.pyo", line 49, in Send
File "googlemail.pyo", line 64, in sendMail
File "googlemail.pyo", line 87, in getAttachment
File "email\mime\text.pyo", line 30, in __init__
File "email\message.pyo", line 220, in set_payload
File "email\message.pyo", line 260, in set_charset
File "email\encoders.pyo", line 73, in encode_7or8bit
LookupError: unknown encoding: ascii ## ascii unknown ???? wth

yeahaha. Found a solution:

added the "includes" option in the py2exe script. Posted is the new opts variable in the py2exe script to reflect the working change.

opts = {
            'py2exe': {
                'compressed': 1,
                'optimize': 2,
##                 'ascii': 1,
                'bundle_files': 1,
                "includes" : ["encodings","encodings.*"],
                "packages" : ["encodings"]
            }
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.