How To Send Email Using SMTPLIB Python Scripting

How To Send Email Using SMTPLIB Python Scripting

In this script we will see how we can send email using smtplib in python scripting. This script use gmail smtp server to send email hence we have used smtp server of gmail. You need to use your environment's smtp server to run this script.

Below is the entire script which we have written so far. Watch the video for full explanation and subscribe to the channel for more such video.

How To Send Email Using SMTPLIB Python Scripting
How To Send Email Using SMTPLIB Python Scripting

import paramiko,smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
p = paramiko.SSHClient()
cred = open("cred.csv","r")
for i in cred.readlines():
    try:
        line=i.strip()
        ls =line.split(",")
        print(ls)
        p.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        p.connect("%s"%ls[0],port =22, username = "%s"%ls[1], password="%s"%ls[2])
        stdin, stdout, stderr = p.exec_command("uname -a")
        opt = stdout.readlines()
        opt ="".join(opt)
        print(opt)
        temp=open("%s.txt"%ls[0],"w")
        temp.write(opt)
        temp.close()
        msg= MIMEMultipart('alternative')
        msg['Subject'] = 'Test Mail'
        From = "fromemailaddress@gmail.com"
        To = "toemailaddress@yahoo.co.in"
        Cc = "ccemailaddress@yahoo.co.in"
        text = "Info Collector"
        data = open("%s.txt"%ls[0],"r").read()
        part1 = MIMEText(text, 'plain')
        part2 = MIMEText(data, 'plain')
        msg.attach(part1)
        msg.attach(part2)
        s=smtplib.SMTP('smtp.gmail.com', 587)
        s.ehlo()
        s.starttls()
        gmail_cred = open("gmail_cred.txt","r").read().split(",")
        s.login(gmail_cred[0],gmail_cred[1])
        s.sendmail(From, To ,msg.as_string())
        s.quit()
    except Exception as error:
       print(error)
cred.close()


                    

No comments:

Post a Comment

Zoning In Cisco MDS SAN Switch In Command Line

Zoning In Cisco MDS SAN Switch In Command Line Zoning is a process of grouping initiator and target ports WWPN which is performed in SAN ...