gpt4 book ai didi

Python,在 smtplib 参数中添加逗号会导致错误

转载 作者:太空宇宙 更新时间:2023-11-03 17:18:42 24 4
gpt4 key购买 nike

使用 smtplib 发送电子邮件并尝试使用以下代码将变量插入消息中:

smtpObj.sendmail('my email', 'my email', "Subject: Info for today.  \nToday's weather is:",con) 

(其中 con 是从互联网上抓取的天气)

抛出以下错误:

File "C:\Python27\lib\smtplib.py", line 731, in sendmail
raise SMTPSenderRefused(code, resp, from_addr)
smtplib.SMTPSenderRefused: (501, '5.5.4 Invalid arguments', 'my email here')

但是,当我简单地使用“+”而不是逗号连接两个字符串时,它可以工作,但格式不正确,显示为“..weather is:rain”而不是“..weather is:”雨”

我做错了什么,还是这根本不可能?

最佳答案

However, when I simply use "+" to concatenate the two strings, rather than a comma, it works, but does not format properly, displaying as "..weather is:rain" rather than "..weather is: rain"

您只是错误地构造了此处以“Subject”开头的字符串:

smtpObj.sendmail('my email', 'my email', "Subject: Info for today.  \nToday's weather is:",con) 

当你像这里一样用逗号附加 con 时,Python 认为你将 conn 作为 mail_options 参数传递sendmail()调用,与该函数的其他参数相同。它不明白您正在尝试将 con 塞进“主题:...”字符串中。

However, when I simply use "+" to concatenate the two strings, rather than a comma, it works, but does not format properly, displaying as "..weather is:rain" rather than "..weather is: rain"

所以你只需要在“..weather is:”位后面有一个额外的空格?只需在字符串中添加额外的空格即可。我建议您通过以下方式之一使用 con 参数编写消息:

msg = "Subject: Info for today.  \nToday's weather is: " + con
# or like this:
msg = "Subject: Info for today. \nToday's weather is: %s" % (con,)

然后发送您的电子邮件:

smtpObj.sendmail('my email', 'my email', msg)

关于Python,在 smtplib 参数中添加逗号会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33401370/

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