Hi @Vipul, try out this code. I've given the explanation through the comments.
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from = "sender email address"
to = "receiver email address"
# instance of MIMEMultipart
data = MIMEMultipart()
# storing the senders email address
data['From'] = from
# storing the receivers email address
data['To'] = to
# storing the subject
data['Subject'] = "Subject of the Mail"
# string to store the body of the mail
body = "Body-of-the-mail"
# attach the body with the msg instance
data.attach(MIMEText(body, 'plain'))
# open the file to be sent
filename = "File-name-with-extension"
attachment = open("Path of the file", "rb")
# instance of MIMEBase and named as p
p = MIMEBase('application', 'octet-stream')
# To change the payload into encoded form
p.set_payload((attachment).read())
# encode into base64
encoders.encode_base64(p)
p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
# attach the instance 'p' to instance 'msg'
data.attach(p)
# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)
# start TLS for security
s.starttls()
# Authentication
s.login(from, "Password-of-the-sender")
# Converts the Multipart msg into a string
text = data.as_string()
# sending the mail
s.sendmail(from, to, text)
# terminating the session
s.quit()
Hope this helps!!
If you need to know more about Python, join Python online course today.
Thanks!