我正在尝试设置一个电子邮件功能,它将用 python 发送 results.txt 文件的最后 15 行。我不确定该怎么做,并询问我是否必须连接到电子邮件服务器,或者 python 是否有其他发送电子邮件的方式。下面的代码是我到目前为止所得到的,我们将不胜感激。谢谢
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
# Open a plain text file for reading. For this example, assume that
# the text file contains only ASCII characters.
fp = open('/home/build/result.txt', 'r')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
me = 'name@server.com'
you = 'name@server.com'
msg['Subject'] = 'The contents of %s' % '/home/build/result.txt'
msg['From'] = me
msg['To'] = you
# Send the message via our own SMTP server, but don't include the
# envelope header.
s = smtplib.SMTP()
s.sendmail(me, [you], msg.as_string())
s.quit()
你好,
当我尝试连接时,服务器无法连接。我知道我不应该输入电子邮件地址。任何人都可以建议以何种方式编写主机信息。谢谢
smtplib.SMTPServerDisconnected: please run connect() first
请您参考如下方法:
如果不连接到服务器,您的机器将无法发送邮件(否则邮件将如何从您的机器中获取?)。大多数人都有一个随时可用的 SMTP 服务器,由他们的公司(如果这是在内部网上)或他们的 ISP(如果是家庭用户)提供。您需要主机名(通常类似于 smtp1.myispdomain.com,当然 myispdomain 对您来说是其他名称)和端口号,通常是 25。有时主机以数字 IP 地址的形式提供,例如 192.168.0.1。
SMTP() 调用可以使用这些参数并将自动连接到服务器。如果您在创建 SMTP 对象时未提供参数,则稍后必须对其调用 connect(),并提供相同的信息。查看documentation了解更多。
请注意,默认连接到 localhost 和端口 25。如果您在运行自己的邮件转发器(例如 Postfix、Sendmail、Exim)的 Linux 机器上,这是可行的,但如果您在 Windows 机器上,通常您必须使用您的 ISP 提供的地址。
