0

我尝试在 python 中创建简单的电子邮件发件人,我编写了以下代码:

import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders

def send_mail(send_from, send_to, subject, text, files=[], server="smtp.gmail.com", port=587, username='username', password='passwordd', isTls=True):
    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = send_to
    msg['Date'] = formatdate(localtime = True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read() )
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f)))
        msg.attach(part)

    smtp = smtplib.SMTP(server, port)
    if isTls: smtp.starttls()
    smtp.login(username,password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.quit()

send_mail('username@gmail.com', 'to@gmail.com', 'test python send', 'hello', files=['smtp.py'] )

并且脚本 smtp.py 工作,问题是在 py2exe 中编译脚本后,设置 py2exe 的代码是这样的:

from distutils.core import setup
import py2exe
import sys

if len(sys.argv) == 1:
    sys.argv.append("py2exe")

setup( options = {"py2exe": {"compressed": 1, "optimize": 2,"dll_excludes": "w9xpopen.exe", "ascii": 1, "bundle_files": 1}},
       zipfile = None,
       console = [
        {
            "script": "smtp.py",
            "icon_resources": [(0, "icon.ico")]
        }
    ],)

如果尝试运行 smtp.exe 给我这个错误:

C:\Users\Lavoro\Desktop\Desktop>smtp.exe
Traceback (most recent call last):
  File "smtp.py", line 30, in <module>
    send_mail('username@gmail.com', 'to@gmail.com', 'test python send',
'hello', files=['smtp.py'] )
  File "smtp.py", line 15, in send_mail
    msg.attach( MIMEText(text) )
  File "email\mime\text.pyo", line 30, in __init__
  File "email\message.pyo", line 226, in set_payload
  File "email\message.pyo", line 248, in set_charset
  File "email\charset.pyo", line 212, in __init__
LookupError: unknown encoding: ascii

如何解决这个问题?谢谢大家

4

1 回答 1

1

您应该将选项"ascii": 1中的选项更改为"ascii": 0. "ascii": 1意味着您的程序应该只使用 ascii 字符串。在这种情况下,编码不包含在 exe 中(请参阅此)

于 2013-10-18T12:55:40.867 回答