0

我正在使用以下代码:

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='email@email.com'):
    myzip = open('file.zip', 'rb')


    # 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(myzip.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.gmail.com", "587")
    smtp.connect()
    smtp.sendmail(sender, recipients, themsg)
    smtp.close()

#running this
send_file_zipped('file.zip', 'email@email.edu')

我尝试了不同的变体来尝试让它在这里成功连接,但我在这里不知所措。我得到的错误是:

Traceback (most recent call last):
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 99, in <module>
send_file_zipped('file.zip', 'email@email.com')
File "/Users/Zeroe/Documents/python_hw/cgi-bin/zip_it.py", line 40, in send_file_zipped
smtp.connect()
File "/usr/local/lib/python3.2/smtplib.py", line 319, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python3.2/smtplib.py", line 294, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/local/lib/python3.2/socket.py", line 404, in create_connection
raise err
File "/usr/local/lib/python3.2/socket.py", line 395, in create_connection
sock.connect(sa)
socket.error: [Errno 61] Connection refused

我将假设我的问题在于与 smtp 服务器的连接,但我不知道我错过了什么。任何帮助将不胜感激!!

4

2 回答 2

1

smtp.connect()错误/冗余。初始化时的smtplib.SMTP(...)调用。没有任何参数.connect的裸调用意味着连接到,如果您的机器上没有运行 SMTP 服务器,您将收到错误消息。.connectlocalhost

但是,您的目标是通过 GMail 发送邮件。请注意,GMail 的 SMTP需要身份验证,而您没有这样做。

你的最后几行应该是相应的:

# send the message
smtp = smtplib.SMTP("smtp.gmail.com",  587)
smtp.helo()
smtp.starttls()                 # Encrypted connection
smtp.ehlo()
smtp.login(username, password)  # Give your credentials
smtp.sendmail(sender, recipients, themsg)
smtp.quit()
于 2012-05-07T03:17:54.663 回答
0

这可能不是您的问题,但您将端口号指定为字符串,这可能行不通。

于 2012-05-07T02:41:19.957 回答