我是否需要添加特定信息才能通过python发送邮件?

时间:2012-05-07 02:26:26

标签: python sendmail

我使用以下代码:

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服务器连接,但我不知道我错过了什么。任何帮助将不胜感激!!

2 个答案:

答案 0 :(得分:1)

smtp.connect()错误/多余。初始化时smtplib.SMTP(...)调用.connect。没有任何参数的裸.connect电话意味着与localhost的连接,如果您的计算机上没有运行SMTP服务器,则会收到错误消息。

但是你的目标是通过GMail发送邮件。请注意GMail的SMTP requires authentication,您没有这样做。

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

# 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()

答案 1 :(得分:0)

这可能不是您的问题,但您将端口号指定为字符串,这可能不会起作用。

相关问题