Ads

Python 7 - Sending Emails from Python

Welcome Everyone,

I am Chakrapani Upadhyaya a full stack engineer.

In this article we will learn how to send a email from python.


Lets Begin....

Send email from python we need to manually go through the steps of connecting to an email server, confirming connection, setting a protocol, logging on and finally sending the message to recipients mentioned.

Note:

Luckily we have built in library in python called smtplib this makes above mentioned steps very easy to us.

All major email providers has their own SMTP(Simple Mail Transfer Protocol) Server.

ProviderSMTP Server Domain Name
Gmailsmtp.gmail.com
Yahoosmtp.mail.yahoo.com
Outlooksmtp-mail.outlook.com

Steps:

1. Create python file called send_email.py

2. Install the package 

pip install smtplib

3. Then we write below statements inside the file

import smtplib



gmail_user = 'YOUR_GMAIL_ID@gmail.com'

gmail_app_password = 'GOOGLE-APP-PASSWORD'



sent_from = gmail_user

sent_to = ['THE-TO@gmail.com']

sent_subject = "Welcome Code With Chakri!"

sent_body = "This sample body text"



try:

 server = smtplib.SMTP_SSL('smtp.gmail.com', 465)

 server.ehlo()

 server.login(gmail_user, gmail_app_password)

 server.sendmail(sent_from, sent_to, sent_body)

 server.close()

 print('Email sent Successfully!')

except Exception as exception:

	 print("Error: %s!\n\n" % exception)


Note:

You need to create the app password for sending the email.

Please follow the below steps.

https://support.google.com/accounts/answer/185839


Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !