我正在尝试通过电子邮件发送随机数,但我一直收到错误

时间:2015-02-01 12:13:06

标签: python

我的代码是通过电子邮件发送的生成号码的电子邮件代码

msg = ('The number is',random.randrange(300,400),'Enjoy')

但是我收到了这个错误:

Traceback (most recent call last):
   line 30, in <module>
    server.sendmail(fromaddr, toaddrs, msg)
  File "C:\Python34\lib\smtplib.py", line 793, in sendmail
    (code, resp) = self.data(msg)
  File "C:\Python34\lib\smtplib.py", line 532, in data
    q = _quote_periods(msg)
  File "C:\Python34\lib\smtplib.py", line 168, in _quote_periods
    return re.sub(br'(?m)^\.', b'..', bindata)
  File "C:\Python34\lib\re.py", line 175, in sub
    return _compile(pattern, flags).sub(repl, string, count)
TypeError: expected string or buffer

2 个答案:

答案 0 :(得分:2)

你的msg是一个元组,你可以用format()字符串来定义一个msg:

>>> import random
>>> msg = ('The number is',random.randrange(300,400),'Enjoy')
>>> print msg
('The number is', 300, 'Enjoy')
>>> msg = 'The number is {0}, Enjoy'.format(random.randrange(300, 400))
>>> msg
'The number is 325, Enjoy'

答案 1 :(得分:0)

您需要将msg转换为字符串,例如使用字符串格式化运算符:

msg =  'The number is %d. Enjoy!' % random.randrange(300, 400)

目前,msg是一个元组。