在python中,如何通过电子邮件发送变量值

时间:2012-03-15 18:33:34

标签: python email

python脚本中有一个变量x,我想通过电子邮件发送x的值。我的代码是

s=smtplib.SMTP('locaolhost')
s.sendmail(FROM, TO, "the answer is x")

但我总是得到消息the answer is x而不是x才是真正的价值。怎么解决这个问题?

4 个答案:

答案 0 :(得分:5)

您可以在此处使用字符串连接,因为您可以随处使用。

s.sendmail(FROM, TO, "the answer is " + x)

或者您可以使用打印格式语法:

s.sendmail(FROM, TO, "the answer is {}".format(x))

了解详情:http://docs.python.org/tutorial/inputoutput.html#fancier-output-formatting

答案 1 :(得分:3)

s.sendmail(FROM, TO, "the answer is " + str(x))

您首先将x的值转换为str(x)字符串,然后将str(x)追加到"the answer is "字符串+的末尾。

答案 2 :(得分:1)

s=smtplib.SMTP('localhost')
s.sendmail(FROM, TO, "the answer is %s" % x) # here is the change

你忘记了字符串中的%s格式化程序了!

所以:

x = 'hello world'
s.sendmail(FROM, TO, "the answer is x")

输出:the answer is x

并且:

x = 'hello world'
s.sendmail(FROM, TO, "the answer is %s" % x)

输出:the answer is hello world

答案 3 :(得分:1)

您的sendmail行应该是这样的:

s.sendmail(FROM, TO, "The answer is "+x)