Sending Email using Python

Now we are going to learn sending email using Python Programming Language, Python programming provides the facility of sending the mail using smtplib library. SMTP stands for Simple Mail Transfer Protocol client session object, using this we can send the email.

    Step

  1. First we to need to import smtplib library.
  2. After importing ,we will use smtp instance to encapsulate smtp connection.
  3. s = smtplib.SMTP('smtp.gmail.com', 587)
    
  4. For security reasons put smtp into TSL mode Transport Layer Security,it will encrypt all smtp commands for security and authentication.
  5. Store your message and subject to the variable ,and use the sendmail() method to send the message.
  6. import smtplib 
    s = smtplib.SMTP('smtp.gmail.com', 587) 
    sender=input("Your Email ID")
    password=input("Password")
    message=input("Message ")
    receiver=input("Receiver Email")
    s.starttls() 
    s.login(sender,password) 
    print("Login Successfully")
    s.sendmail(sender, receiver, message)
    print("Message Send to",receiver) 
    s.quit() 
    

Sending the file with Attachment

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
message = MIMEMultipart()
yemail =input("Your Email")
ypassword=input("Password")
remail = input("Receiver Mail")

body =input("Message")
message.attach(MIMEText(body,'plain'))
file="abc.txt"
attach1 =open(file,'rb')
part = MIMEBase('application','octet-stream')
part.set_payload((attach1).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',"attachment; filename= "+file)
message.attach(part)
txt = message.as_string()
server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(yemail,ypassword)
server.sendmail(yemail,remail,txt)
server.quit()
Subscribe Now