How To Send Email Using Python

 Well, hello programmers, this is themidom. Today in this post you will learn how to send email using python. So, without any delay, how about we begin.

First, we need to import one python module.

1) smtplib (this is inbuild so, you don't need to download and install)


smtplib stands for Simple Mail Transfer Protocol Library. And It is used to connect with your Email server and later user commands to send Emails, with a valid username and password.

 So, first, you need to enable less secure apps of your Gmail account. Now if you don't want to compromise with your security, then just follow the steps:

(you can follow steps, if your two factor authentication is enabled or you need to enable it)

1) Go to your Gmail Account.


And now you need to click on the google apps option




Now, you will get something like this:


Click on the account option, you will be redirected to this page


From, the left sidebar click on security, and you will be redirected to this page.



Now, scroll down you will get the App passwords option, now click on it.


Then, you will be redirected to the sign-in page, just give your correct password, and then you will be redirected to this page.


And guess what, now we have click on the select app option, you will get dropbox like that


Select, Mail option, and in case of the select device option, select for your required device (If you are on windows select for windows, and if you are on another device, select for it). Then just simply click on the "generate" button. And you will get a popup like this.


Now, the yellow shaded area is your password, make sure to copy it on a text file and save it. You can use this password only to send Mail.

And we are done here, you see how we have got app password, without compromising the security.

And, now let's get the code of sending mail using python, copy the below script and, you are good to go.


 import smtplib  
 def sendEmail(to, content):  
     server = smtplib.SMTP('smtp.gmail.com', 587)  
     server.ehlo()  
     server.starttls()  
     server.login('your_email@gmail.com', 'your_password')  
     server.sendmail('your_email@gmail.com', to, content)  
     server.close()  
 to = "your_receiver@gmail.com"  
 subject = input("what's the subject: ")  
 message = input("what's the message: ")  
 content = f"""|  
 Subject: {subject}  
 {content}  
 https://themidom.in  
 """  
 print("sending mail")  
 try:  
   sendEmail(to, content=message)  
   print("sent")  
 except Exception as e:  
   print(f"Not sent because of {e}")  
Now, you can copy and paste the script into any python file, and make sure to give your email in your_email, and Your password in you_password, and receiver email in you_receiver. So, that's it for this post, see ya next.

                        --Themidom.

Post a Comment

If you have have any doubt please let me know

Previous Post Next Post

Ads

Ads