发送带有整数主题/验证码的电子邮件:Python

问题描述

我正在处理一个个人项目,您在其中输入凭据(以模拟网站注册),并将其存储在Google表格文档中。我使用smtplib发送带有验证码的电子邮件。我在执行此操作时遇到了两个问题:1.我有一个变量verification_code,已将其设置为验证代码(我计划将来将其随机化)。问题是当我尝试将其作为整数发送时,出现此错误:

Traceback (most recent call last):
  File "/Users/user/PycharmProjects/sign-up test enviroment/main.py",line 92,in <module>
    verify_email()
  File "/Users/user/PycharmProjects/sign-up test enviroment/main.py",line 62,in verify_email
    msg.attach(MIMEText(message,'plain'))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/email/mime/text.py",line 34,in __init__
    _text.encode('us-ascii')
AttributeError: 'int' object has no attribute 'encode'

但是,当我使用''将整数设置为字符串时,它发送得很好。问题是我无法执行此操作,因为我尝试检查entred变量entered_code(通过用户输入输入)是否与设置为变量verification_code的预定义整数匹配。这是我的代码,用于检查用户输入的代码是否与预先定义的代码(verification_code)相匹配:

def enter_verification_code():
    global verification_code,entered_code
    entered_code = int(input("Please enter the verification code sent to " + user_email + ': '))
    if verification_code == entered_code:
        print('Thank you for verifying your account!')
        store_info()
        exit()
    elif verification_code != entered_code:
        entered_code = int(input("Please enter the verification code sent to " + user_email + ': '))
        enter_verification_code()

我想知道的是,是否可以通过电子邮件将变量作为整数发送,或者是否有更好的方法来验证输入的代码与我在项目开始时定义的代码匹配。谢谢!

解决方法

您可以使用str(),以便用户可以粘贴代码,然后使用int()对其进行转换以在您的代码中进行验证

def enter_verification_code():
    global verification_code,entered_code
    entered_code = input("Please enter the verification code sent to " + user_email + ': ')
    if verification_code == int(entered_code):
        print('Thank you for verifying your account!')
        store_info()
        exit()
    elif verification_code != entered_code:
        entered_code = int(input("Please enter the verification code sent to " + user_email + ': '))
        enter_verification_code()

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...