Python 邮件错误

3 投票
1 回答
9024 浏览
提问于 2025-04-15 17:17

我正在尝试发送一个结果文件的邮件。但是我遇到了一个导入错误:

Traceback (most recent call last):  
  File "email_results.py", line 5, in ?  
    from email import encoders  
ImportError: cannot import name encoders  

我也不太确定怎么才能连接到服务器。有没有人能帮帮我?谢谢!

#!/home/build/test/Python-2.6.4
import smtplib
import zipfile
import tempfile
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

def send_file_zipped(the_file, recipients, sender='myname@myname.com'):
 zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip')
 zip = zipfile.ZipFile(zf, 'w')
 zip.write(the_file)
 zip.close()
 zf.seek(0)

 # Create the message
 themsg = MIMEMultipart()
 themsg['Subject'] = 'File %s' % the_file
 themsg['To'] = ', '.join(recipients)
 themsg['From'] = sender
 themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
 msg = MIMEBase('application', 'zip')
 msg.set_payload(zf.read())
 encoders.encode_base64(msg)
 msg.add_header('Content-Disposition', 'attachment',filename=the_file + '.zip')

 themsg.attach(msg)
 themsg = themsg.as_string()

 # send the message
 smtp = smtplib.SMTP()
 smtp.connect()
 smtp.sendmail(sender, recipients, themsg)
 smtp.close()

1 个回答

10

问题不是你无法连接到服务器,而是你出于某种原因无法导入email.encoders。你有没有一个叫做email.py或email.pyc的文件呢?

撰写回答