Python OTP - How do I send OTP Mail using Python
Published February 07, 2022Sending OTP mail is one of the most common security mechanisms implemented in different applications and devices. When you attempt to authenticate into a system or use a device, an OTP message is sent to the registered email address to confirm the user. In this post, we are going to learn how to send an OTP mail using Python.
To send the OTP mails in Python, we use the SMTPib module. Let's take a look at how we can send an OTP mail in Python.
Step 1: First, import all the required libraries. To do so, we are going to add the following code:
from tkinter import * from tkinter import messagebox import smtplib import random |
Because SMTPib module is an inbuilt Python module, we will not need to install it using our console.
Step 2: With the Tkinter module, we will create the application interface which contains an email input field and a button for sending the OTP. To do so, add the code below:
root = Tk() root.title("Send OTP Mail using Python") root.geometry("600x300") email_label = Label(root, text="Enter Email: ", font=("ariel 15 bold"), relief=FLAT) email_label.grid(row=0, column=0, padx=15, pady=60) email_entry = Entry(root, font=("ariel 15 bold"), width=25, relief=GROOVE, bd=2) email_entry.grid(row=0, column=1, padx=12, pady=60) email_entry.focus() send_button = Button(root, text="Send OTP Mail", font=("ariel 15 bold"), bd=3, command=send) send_button.place(x=210, y=150) root.mainloop() |
Step 3: Next, create the function that will send the OTP mail to the email address the user entered. To do so, add the following code.
def send(): try: s = smtplib.SMTP("smtp.gmail.com", 587) # 587 is a port number s.starttls() s.login("sender_email", "sender_email_password") otp = random.randint(1000, 9999) otp = str(otp) s.sendmail("sender_email", email_entry.get(), otp) messagebox.showinfo("Send OTP via Email", f"OTP sent to {email_entry.get()}") s.quit()
except: messagebox.showinfo("Send OTP via Email", "Could not send the OTP mail") |
Step 4: Now, let's run our application.
![]() |
Conclusion: In this python example we covered how to send OTP email form python script
Article Contributed By :
|
|
|
|
481 Views |