Search code examples
python-3.xsocketsmail-server

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


I just want to receive the random number in my email and then get it verified in my code to be True.

I am using Python 3.5 to generate a random number using the "import random" and 'random.randint(x,y)'. Although the random number is being generated in my code and also being displayed on the screen however, when I send the same to my email using smtp, the mail is received empty with no generated random number. Also, the random number on the screen that is displayed after running the code does not match when entered for verification.

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

After entering all the required details, the mail should be received with a displayed random number and then the number when entered should get verified.


Solution

  • The Internet mail format requires a blank line as the separator between the message headers and the message body. Also, the end-of-line marker in a mail message is the pair of characters '\r\n', not just the single character '\n'. So change this:

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

    to:

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

    The first '\r\n' marks the end of the subject line and the second provides the empty line that separates the header from the body.

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

    That's because in Python 3 the value returned by input() is always a string. This line:

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

    sets verify to a string. Then this line:

        if verify == secure_code:
    

    compares the verify string to the secure_code number. A string and a number do not match, so that comparison always produces a false result. To fix, change that comparison to this:

        if verify == str(secure_code):