如何解决代码中生成随机数时未在电子邮件中收到任何随机数的问题?

问题描述 投票:0回答:1

我只想在我的电子邮件中收到随机数,然后在我的代码中验证它是真的。

我使用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

输入所有必需的详细信息后,应收到带有显示的随机数的邮件,然后输入的数字应该得到验证。

python-3.x sockets mail-server
1个回答
0
投票

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):
© www.soinside.com 2019 - 2024. All rights reserved.