Search code examples
pythonpython-3.xvariablessmtpemail-verification

Sending Emails with Integer Subjects/Verifying Numbers: Python


I am working on a personal project which you you enter credentials (to simulate signing-up to a website) and it stores them in a Google Sheets Document. I use smtplib to send an email with a verification code. I have faced two problems while doing this: 1. I have a variable, verification_code, which I set to my verification code (which I plan to be random in the future). The problem is that when I try to send it as an integer, I get this error:

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'

But, when I set the integer to a string using '', it sends just fine. The problem is that I cannot do that since I try checking to see if the entred variable, entered_code, (which is entered through user input), matched the pre-defined integer set to the variable verification_code. Here is my code which I use to check to see if the code entered by the user matches the code that was pre-defined (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()

What I am wondering is if there is a way to send my variable as an integer through the email, or if there is a better way to verify that the entered code matches the code that I defined at the start of my project. Thanks!


Solution

  • You can use str() so the user can paste the code then convert it using int() to verify it in your code

    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()