gpt4 book ai didi

Python server.sendmail() 返回 {}。电子邮件未发送

转载 作者:行者123 更新时间:2023-12-05 03:14:08 27 4
gpt4 key购买 nike

我有一个包含很多行的 file.txt 文件。我希望随机选择任何一行并通过电子邮件发送。这是循环三次。

import smtplib,datetime,random

def mail(em):
#print "yo"
fromAddress = "atadmorecouth@gmail.com"
toAddress = "atadmorecouth@gmail.com"
subject = "WOW " + str(datetime.datetime.now())
#print subject
msg = em
server=smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
password = "mypassword"
server.login(fromAddress, password)
server.sendmail(fromAddress, toAddress, msg)
#print server.sendmail(fromAddress, toAddress, msg)


for i in range(0,3):
em=str(random.choice(list(open('file.txt'))))
mail(em)

此代码无效。登录和一切都很好。我注意到的唯一问题是 server.sendmail(fromAddress, toAddress, msg) 返回一个空的 {}可能的解决方法是什么?首先是什么问题?我在终端中运行了 mail() 函数,它似乎工作正常。所有文件都托管 here

最佳答案

首先,作为the docs说:

If this method does not raise an exception, it returns a dictionary, with one entry for each recipient that was refused.

因此,您返回 {} 不是问题;这意味着您没有错误。


其次,您发送的不是有效消息。消息必须包含标题,然后是空行,然后是正文。 header 应至少包含 From:To:

smtplib 库不会为您做这些;如 the example 中所述:

Note that the headers to be included with the message must be included in the message as entered; this example doesn’t do any processing of the RFC 822 headers. In particular, the ‘To’ and ‘From’ addresses must be included in the message headers explicitly.

...

Note: In general, you will want to use the email package’s features to construct an email message, which you can then convert to a string and send via sendmail(); see email: Examples.

或者,在 sendmail文档:

Note: The from_addr and to_addrs parameters are used to construct the message envelope used by the transport agents. The SMTP does not modify the message headers in any way.

在这种情况下(如示例中所示),只需手动制作消息就足够简单了:

msg = "From: {}\r\nTo: {}\r\n\r\n{}\r\n".format(fromAddress, toAddress, em)

最后,你真的应该调用 server.quit()mail 函数的末尾。虽然(至少在 CPython 中)server 对象将在函数结束后立即销毁,但与 Python 中的许多其他对象不同,SMTP 对象不会调用 close 销毁时,更不用说 quit 了。所以,从服务器的角度来看,你突然断开了连接。虽然 RFC 建议服务器应该在没有 QUIT 的情况下也能正常工作,并且大多数 RFC 都这样做,但他们还建议客户端应该始终发送它并等待响应,那么……为什么不这样做呢?

关于Python server.sendmail() 返回 {}。电子邮件未发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940208/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com