Python is a very strong language that does not require an external library to send emails. It offers a native library SMTP lib
( Simple Mail Transfer Protocol). In this article, a Gmail account is going to be used.
Note: the smtplib module defines an SMTP client session object that can be used to send emails by creating a session. For a Gmail account, port 587 is used.
The example below shows how to send email without attachment
# Sending emails without attachments using Python.# importing the required library.import smtplib# creates SMTP sessionemail = smtplib.SMTP('smtp.gmail.com', 587)# TLS for securityemail.starttls()# authentication# compiler gives an error for wrong credential.email.login("sender_email_id", "sender_password")# message to be sentmessage = "message_to_be_send"# sending the mailemail.sendmail("sender_email_id", "receiver_email_id", message)# terminating the sessionemail.quit()
The below code shows how to send emails using an attachment.
In the code snippet below, the MIMEultipart object is created in order to append the subject, the body, and attachment(s) to the emails.
# Sending emails with attachments using Python# libraries to be importedimport smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email import encodersfromaddr = "email_address_of_the_sender"toaddr = "email_address_of_the_receiver"# MIMEMultipartmsg = MIMEMultipart()# senders email addressmsg['From'] = fromaddr# receivers email addressmsg['To'] = toaddr# the subject of mailmsg['Subject'] = "subject_of_the_mail"# the body of the mailbody = "body_of_the_mail"# attaching the body with the msgmsg.attach(MIMEText(body, 'plain'))# open the file to be sent# rb is a flag for readonlyfilename = "file_name_with_extension"attachment = open("Path of the file", "rb")# MIMEBaseattac= MIMEBase('application', 'octet-stream')# To change the payload into encoded formattc.set_payload((attachment).read())# encode into base64encoders.encode_base64(attc)attc.add_header('Content-Disposition', "attachment; filename= %s" % filename)# attach the instance 'p' to instance 'msg'msg.attach(attc)# creates SMTP sessionemail = smtplib.SMTP('smtp.gmail.com', 587)# TLS for securityemail.starttls()# authenticationemail.login(fromaddr, "Password_of_the_sender")# Converts the Multipart msg into a stringmessage = msg.as_string()# sending the mailemail.sendmail(fromaddr, toaddr, message)# terminating the sessions.quit()
Strong recommendation: reset the setting once you are done sending the email. In order to run the above code in a perfect manner, the Gmail account needs the security permission shown below::