转换字符串参数以发送电子邮件可以帮助我 (python)

convert string arguments to send e-mail can help me please (python)

import smtplib
import sys
if(len(sys.argv) > 1):
 smtp = smtplib.SMTP_SSL('smtp.gmail.com', 465)
 smtp.login('gmail.com', 'password')
 de = '@gmail.com'
 para = ['@gmail.com']
 msg2=str(sys.argv[1])
 msg = """From: %s
To: %s
Subject: SMATIJ
server"""+msg2+"""""" % (de, ', '.join(para))

我有这个错误:类型错误:在 msg2

中的字符串格式化期间,并非所有参数都已转换
 smtp.sendmail(de, para, msg)
 smtp.close()
 print "sending message"

我认为问题在于 Python 正在尝试将您的字符串分组为 -

msg = """From: %s
To: %s
Subject: SMATIJ
server"""+msg2+("""""" % (de, ', '.join(para)))

因此,它试图将字符串应用于末尾的空字符串(甚至不确定为什么需要空字符串),这就是导致问题的原因。您应该手动将字符串连接组合在一起。例子-

msg = ("""From: %s
To: %s
Subject: SMATIJ
server"""+msg2) % (de, ', '.join(para))

或者更好的是,使用更强大的 str.format ,示例 -

msg = """From: {0}
To: {1}
Subject: SMATIJ
server{2}""".format(de, ', '.join(para), msg2)

这是真正崩溃的部分

msg = """From: %s
To: %s
Subject: SMATIJ
server"""+msg2+"""""" % (de, ', '.join(para))

如果我们将其分解,您告诉 python 要做的是:

"""first string %s %s """ +\    # a string of text with 2 placeholders
 msg2 +\                        # a string
 """""" % (de, ', '.join(para)) # empty string of text with no placeholders
                                # (formatted with 2 variables)

你真正想要的可能是这样的:

msg = """From: %s
To: %s
Subject: SMATIJ
server""" % (de, ', '.join(para)) + msg2