代码生成随机数时邮件收不到随机数怎么解决?

How to fix the issue of not receiving any random number on email when random number is being generated in the code?

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

我正在使用 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 邮件格式需要一个空行作为消息 header 和消息 body 之间的分隔符。此外,邮件消息中的 end-of-line 标记是一对字符 '\r\n',而不仅仅是单个字符 '\n'。所以改变这个:

    msg = "Subject: "+subject + '\n' + message

至:

    msg = "Subject: " + subject + '\r\n' + '\r\n' + message

第一个 '\r\n' 标记主题行的结尾,第二个提供将 header 与 body 分开的空行。

Also, the random number on the screen that is displayed after running the code does not match when entered for verification.

那是因为在 Python 3 中,input() 返回的值始终是一个字符串。这一行:

    verify = input("Enter the secure code: ")

verify 设置为一个字符串。然后这一行:

    if verify == secure_code:

verify 字符串与 secure_code 数字进行比较。字符串和数字不匹配,因此比较总是会产生错误的结果。要修复,请将该比较更改为:

    if verify == str(secure_code):