Monday 19 March 2018

SMTP (Simple Mail Transfer Protocol ) protocol with attachment using Python


"""
Important Points:
Simple Mail Transfer Protocol (SMTP) is an Internet standard for electronic mail (email) transmission.
You can use loops to send mails to a number of people.
This code is simple to implement. But it will not work if you have enabled 2-step verification on your gmail account. It is required to switch off the 2-step verification first.
Using this method, Gmail will always put your mail in the primary section and the mails sent will not be Spam.
"""


# libraries to be imported
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

fromaddr = "boyina.narendra@gmail.com"
toaddr = ["boyinanarendra1@gmail.com", "narendra.boyina@happiestminds.com", "yugeshyadav28@gmail.com", "sravya.ms01@gmail.com","vamsinadhmadugula@gmail.com"]

# instance of MIMEMultipart
msg = MIMEMultipart()

# storing the senders email address
msg['From'] = fromaddr

# storing the receivers email address
msg['To'] = ", ".join(toaddr)

# storing the subject
msg['Subject'] = "Regading daily status report"

# string to store the body of the mail
##body = "Body_of_the_mail"
body = "Hi Suguna,\n \t In attachment, I have mentioned the tasks done by me today  .\n PFA.\n\n Best regards,\n Narendra Boyina."

# attach the body with the msg instance
msg.attach(MIMEText(body, 'plain'))

# open the file to be sent
filename = "DSR.txt"
attachment = open("D:\DSR.txt", "r")

# 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'
msg.attach(p)

# creates SMTP session
s = smtplib.SMTP('smtp.gmail.com', 587)

# start TLS for security (Connect on port 587 if you're using TLS)
s.starttls()

# Authentication
s.login("boyina.narendra@gmail.com", " YOUR GMAIL PASSWORD")

# Converts the Multipart msg into a string
text = msg.as_string()

# sending the mail
s.sendmail(fromaddr, toaddr, text)

print(" From narendra's Email ID.... Mail has been sent with attachment")
# terminating the session
s.quit()