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
- First we to need to import smtplib library.
- After importing ,we will use smtp instance to encapsulate smtp connection.
- For security reasons put smtp into TSL mode Transport Layer Security,it will encrypt all smtp commands for security and authentication.
- Store your message and subject to the variable ,and use the sendmail() method to send the message.
s = smtplib.SMTP('smtp.gmail.com', 587)
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()