...
/Add an attachment / body using the email module
Add an attachment / body using the email module
How to add attachments to your emails in python
We'll cover the following...
Now we’ll take what we learned from the previous section and mix it together with the Python email module so that we can send attachments. The email module makes adding attachments extremely easy. Here’s the code:
Press + to interact
import osimport smtplibimport sysfrom configparser import ConfigParserfrom email import encodersfrom email.mime.text import MIMETextfrom email.mime.base import MIMEBasefrom email.mime.multipart import MIMEMultipartfrom email.utils import formatdate#----------------------------------------------------------------------def send_email_with_attachment(subject, body_text, to_emails,cc_emails, bcc_emails, file_to_attach):"""Send an email with an attachment"""base_path = os.path.dirname(os.path.abspath(__file__))config_path = os.path.join(base_path, "email.ini")header = 'Content-Disposition', 'attachment; filename="%s"' % file_to_attach# get the configif os.path.exists(config_path):cfg = ConfigParser()cfg.read(config_path)else:print("Config not found! Exiting!")sys.exit(1)# extract server and from_addr from confighost = cfg.get("smtp", "server")from_addr = cfg.get("smtp", "from_addr")# create the messagemsg = MIMEMultipart()msg["From"] = from_addrmsg["Subject"] = subjectmsg["Date"] = formatdate(localtime=True)if body_text:msg.attach( MIMEText(body_text) )msg["To"] = ', '.join(to_emails)msg["cc"] = ', '.join(cc_emails)attachment = MIMEBase('application', "octet-stream")try:with open(file_to_attach, "rb") as fh:data = fh.read()attachment.set_payload( data )encoders.encode_base64(attachment)attachment.add_header(*header)msg.attach(attachment)except IOError:msg = "Error opening attachment file %s" % file_to_attachprint(msg)sys.exit(1)emails = to_emails + cc_emailsserver = smtplib.SMTP(host)server.sendmail(from_addr, emails, msg.as_string())server.quit()if __name__ == "__main__":emails = ["mike@someAddress.org", "nedry@jp.net"]cc_emails = ["someone@gmail.com"]bcc_emails = ["anonymous@circe.org"]subject = "Test email with attachment from Python"body_text = "This email contains an attachment!"path = "/path/to/some/file"send_email_with_attachment(subject, body_text, emails,cc_emails, bcc_emails, path)
Here we have renamed our function and added a new argument, file_to_attach. We also need to add a header and create a MIMEMultipart object. The header could be created any time before we add the ...