Python Send Email Via Gmail SMTP



Python Send Email Via Gmail SMTP


we will learn how Python sends Email via Gmail SMTP Server. We will use following Python modules for this:

1) smtplib
2) MIMEText
3) MIMEMultipart

In order to work with Gmail SMTP, you need to give permission to access less secure apps from your Google account.

To give access, go through below instructions:

1) Go to your Google Account.
2) On the left navigation panel, select Security.




3) Scroll down to the section 'Less secure app access'. 
4) Click on the button 'Turn on access (not recommended)'
5) Now turn on the button to give access to apps.



Now open any of your IDE and paste the below code, save file as send_email.py in a directory.


Code:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

mail_content = '''Hi,
This is a testing email sent using Python and Gmail smtp.'''

# The mail addresses and password
sender_address = '<from_user>@gmail.com'
sender_pass = '<Gmail Password>'
receiver_address = '<to_user>@gmail.com'

# Setup the MIME
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = receiver_address

# The subject line
message['Subject'] = 'A test mail sent by Python. It has an attachment.'

# The body and the attachments for the mail
message.attach(MIMEText(mail_content, 'plain'))

# Create SMTP session for sending the mail
session = smtplib.SMTP('smtp.gmail.com', 587)  # use gmail with port

session.starttls()  # enable security
session.login(sender_address, sender_pass)  # login with mail_id and password

text = message.as_string()
session.sendmail(sender_address, receiver_address, text)
session.quit()
print('Mail Sent')


sender_address - From Address (Your Gmail Id)
sender_pass - Your Gmail account password
receiver_address - To Address

Now, open the terminal from the directory where 'send_email.py' is saved. 

Run below command to send email to user

python send_email.py


Comments

Popular posts from this blog

Create Desktop Application with PHP

Insert pandas dataframe into Mongodb

Python desktop application