import os
import smtplib
import email
# Compose mail
mail_message = """Hi
This is just a test mail from python with attachments.
Best Regards
"""
msg = email.MIMEMultipart.MIMEMultipart()
msg['Message-ID'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate(localtime=True)
msg['From'] = "from@example.org"
msg['To'] = "to@example.org, svarco"
msg['Subject'] = "Example Subject"
msg.attach(email.MIMEText.MIMEText(mail_message))
# add the attachments
lst_files_attach = ["/etc/passwd", "/etc/group"]
for file in lst_files_attach:
try:
with open(file, "rb") as newfile:
attachment = email.MIMEBase.MIMEBase('application', "octet-stream")
attachment.set_payload(newfile.read())
email.Encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="{filename}"'.format(filename = os.path.basename(file)))
msg.attach(attachment)
except IOError:
Output().error("Could not read file: {file}".format(file=file))
# Send the mail
smtp = smtplib.SMTP(MAIL_HOST)
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
smtp.quit() |
import os
import smtplib
import email
# Compose mail
mail_message = """Hi
This is just a test mail from python with attachments.
Best Regards
"""
msg = email.MIMEMultipart.MIMEMultipart()
msg['Message-ID'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate(localtime=True)
msg['From'] = "from@example.org"
msg['To'] = "to@example.org, svarco"
msg['Subject'] = "Example Subject"
msg.attach(email.MIMEText.MIMEText(mail_message))
# add the attachments
lst_files_attach = ["/etc/passwd", "/etc/group"]
for file in lst_files_attach:
try:
with open(file, "rb") as newfile:
attachment = email.MIMEBase.MIMEBase('application', "octet-stream")
attachment.set_payload(newfile.read())
email.Encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment; filename="{filename}"'.format(filename = os.path.basename(file)))
msg.attach(attachment)
except IOError:
Output().error("Could not read file: {file}".format(file=file))
# Send the mail
smtp = smtplib.SMTP(MAIL_HOST)
smtp.sendmail(msg['From'], msg['To'], msg.as_string())
smtp.quit()