我只想在我的电子邮件中收到随机数,然后在我的代码中验证它是真的。
我使用Python 3.5使用“import random”和“random.randint(x,y)”生成一个随机数。虽然随机数在我的代码中生成并且也显示在屏幕上,但是当我使用smtp将其发送到我的电子邮件时,邮件将被收到空,没有生成随机数。此外,输入验证后,运行代码后显示的屏幕上的随机数也不匹配。
import smtplib
import getpass
import random
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
email = input("Enter you email address: ")
password = getpass.getpass("Enter your password: ")
server.login(email, password)
from_address = email
to_address = input('Enter the email you want the message to be sent to: ')
subject = input('Enter the subject: ')
secure_code = random.randint(1000, 9999)
print(f'The secure code received on the mail is {secure_code}')
message = f'Secure Code: {secure_code}'
msg = "Subject: "+subject + '\n' + message
print(msg)
server.sendmail(from_address, to_address, msg)
verify = input("Enter the secure code: ")
if verify == secure_code:
print('Transaction accepted.')
else:
print('Attention! The code entered is not correct!')
break
输入所有必需的详细信息后,应收到带有显示的随机数的邮件,然后输入的数字应该得到验证。
Internet邮件格式需要一个空行作为邮件头和邮件正文之间的分隔符。此外,邮件消息中的行尾标记是一对字符'\r\n'
,而不仅仅是单个字符'\n'
。所以改变这个:
msg = "Subject: "+subject + '\n' + message
至:
msg = "Subject: " + subject + '\r\n' + '\r\n' + message
第一个'\r\n'
标记主题行的结尾,第二个提供将标题与正文分开的空行。
此外,输入验证后,运行代码后显示的屏幕上的随机数也不匹配。
那是因为在Python 3中,input()
返回的值总是一个字符串。这一行:
verify = input("Enter the secure code: ")
将verify
设置为字符串。那么这一行:
if verify == secure_code:
将verify
字符串与secure_code
数字进行比较。字符串和数字不匹配,因此比较总是产生错误结果。要修复,请将此比较更改为:
if verify == str(secure_code):