python reading YAML, stdout, and sending an email
this article includes:
- using YAML library in Python3,
- reading YAML file in Python by using load() method from yaml module,
- redirecting the Python output to a file,
- sending that file to Google Mail.
let's start by writing YAML fomartted file:
fruits.yaml
mangos: 10
tomotos: 30
strawberrys: 12
apples: 20
after that, I must install YAML library in Python:
$ pip install pyyaml
let's now try to read the data file by using a Python script. The load() method from the yaml module can be used to read YAML files.
i specified yaml.FullLoader is the value for the Loader parameter, which loads the full YAML language, avoiding arbitrary code execution.
and define Logger class to redirect stout to a file (using sys module):
process_yaml.py
import yaml, sys
with open(r'fruits.yaml') as file:
# The FullLoader parameter handles the conversion from YAML
# scalar values to Python the dictionary format
fruits_list = yaml.load(file, Loader=yaml.FullLoader)
# Redirect stdout to a file
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
self.log = open(filename, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger("log.txt")
sys.stdout.flush()
# Print the result
print(fruits_list, flush=True)
sending_email.py with an attachment using smtplib module:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path
email = 'freecodecamp@gmail.com'
password = 'xdncndumcnsbabcd'
send_to_email = 'codeacademy@gmail.com'
subject = 'Sending Email with an attachment'
message = 'Please find the attachment to email, thanks'
file_location = 'log.txt'
msg = MIMEMultipart()
msg['From'] = email
msg['To'] = send_to_email
msg['Subject'] = subject
msg.attach(MIMEText(message, 'plain'))
# Setup the attachment
filename = os.path.basename(file_location)
attachment = open(file_location, "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
# Attach the attachment to the MIMEMultipart object
msg.attach(part)
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(email, password)
text = msg.as_string()
server.sendmail(email, send_to_email, text)
server.quit()
smtplib library defines a Simple Mail Transfer Protocol (SMTP) client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.
since May 30, 2022, the less secure app access setting has been unavailable for Gmail. So, you may get an error message:
> python3 sending_email.py
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor b64-20020a621b43000000b0056c3a0dc65fsm3758432pfb.71 - gsmtp')
setup an App Password to fix it.
- go to your Goolge Account, Security, and turn on 2 Steps Verification.
- in Security section, setup an App Password as below:
it generates a random password. Then, I can use such a password to send emails in Python.
now, I have a Gmail test account and can send emails using Python!
python3 sending_email.py