About Python: Python has become one of the most popular programming languages in the world in recent years. It’s used in everything from machine learning to building websites and software testing. It can be used by developers and non-developers alike. Python, one of the most popular programming languages in the world, has created everything from Netflix’s recommendation algorithm to the software that controls self-driving cars. Python is a general-purpose language, which means it’s designed to be used in a range of applications, including data science, software and web development, automation, and generally getting stuff done.
Python – Sending Email using SMTP:
In Python, the smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
The following script will allow you to send an email via the Gmail SMTP server. However, Google will not allow logging in via smtplib because it has flagged this type of login as “less secure”. To solve this, go to https://www.google.com/settings/security/lesssecureapps while you’re logged in to your Google account, and enable “Allow less secure apps”.
import smtplib sender_mail = 'firstname.lastname@example.org' receivers_mail = ['email@example.com'] message = """From: From Person %s To: To Person %s Subject: Sending SMTP e-mail This is a test e-mail message. """%(sender_mail,receivers_mail) try: password = input('Enter the password'); smtpObj = smtplib.SMTP('gmail.com',587) smtpobj.login(sender_mail,password) smtpObj.sendmail(sender_mail, receivers_mail, message) print("Successfully sent email") except Exception: print("Error: unable to send email")
Python – Sending Email With an Attachment:
In this example, we are going to send an email with an image attachment. The process is similar to sending a plain text email.
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage from email.mime.text import MIMEText # create message object instance msg = MIMEMultipart() # setup the parameters of the message password = "your_password" msg['From'] = "your_address" msg['To'] = "to_address" msg['Subject'] = "Photos" file = "Python.pdf" # attach image to message body msg.attach(MIMEText(open(file).read())) # create server server = smtplib.SMTP('smtp.gmail.com: 587') server.starttls() # Login Credentials for sending the mail server.login(msg['From'], password) # send the message via the server. server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit()