Nothing much to say here. The below python code will help you send email with an attachment. In the below sample code, I have used SMTP details of gmail.com.
You will need to update the login credentials in the below script and the recipient email ID. In case you are using any other host other than gmail then you need to update the SMTP address and port number ( a quick google search would give you the details, example: hotmail.com SMTP).
Note: Below code is tested in Python 2.7.
import smtplib, os from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Encoders from email.mime.text import MIMEText emaillist=['email@example.com'] # Receipient email address msg = MIMEMultipart('mixed') msg['Subject'] = 'Arrest Warrent' # mail subject line msg['From'] = 'firstname.lastname@example.org' # From email address msg['To'] = ', '.join(emaillist) part = MIMEBase('application', "octet-stream") # Provide the path of the file to be attached in the mail part.set_payload(open('C:'+os.sep+'Users'+os.sep+'abhijit'+os.sep+'Desktop'+os.sep+'WarrentDetails.txt', "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="WarrentDetails.txt"') msg.attach(part) msg.add_header('To', msg['From']) text = "Dear Sir, \n\n An arrest warrent has been generated due to XYZ reason by ZZZ complain.\n YOU MUST APPEAR IN PERSON TO RESOLVE THIS MATTER. \n\n Regards,\n FBI :)" part1 = MIMEText(text, 'plain') msg.attach(part1) # provide SMTP details of the host and its port number server = smtplib.SMTP_SSL("smtp.gmail.com",465) # If the host supports TLS then enable the below 2 lines of code # server.ehlo() # server.starttls() server.login("email@example.com", "password") server.sendmail(msg['From'], emaillist , msg.as_string())
Here is the output when we run the script:
The script is available in GitHub: CLICK HERE.