2012-03-15 92 views
0

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

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

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

+1

您使用复杂的库,但然后不知道如何格式化字符串?我强烈建议你在问你之前学习最低限度... – 2012-03-15 18:43:55

回答

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

你首先x值转换为字符串由str(x),然后通过+追加str(x)字符串"the answer is "结束。

+0

非常感谢!它现在有效! – user1224398 2012-03-15 18:40:44

+0

另一个问题,如何使电子邮件的主题?现在没有题目。 – user1224398 2012-03-15 18:42:33

+0

您必须在邮件的开头添加主题:例如http://effbot.org/pyfaq/how-do-i-send-mail-from-a-python-script.htm – 2012-03-15 18:45:24

3

你可以在这里使用字符串连接,就像你在任何地方都可以。

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

+0

避免将x作为str()那样转换,但使用%s格式化程序就像在我的答案中一样。 – 2012-03-15 18:38:59

+0

我编辑了%操作。从I/O手册:“由于str.format()是很新的,很多Python代码仍然使用%运算符。但是,由于这种旧式的格式最终会从语言中删除,所以str.format()通常应该使用。“ – mikaelb 2012-03-15 18:44:11

+0

谢谢您的快速回复。问题解决了。 – user1224398 2012-03-15 18:51:44

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

1

你的sendmail的线应该是这样的:

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

感谢您的回复〜 – user1224398 2012-03-15 21:50:30