Python Automation Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Create the email_task.py file, as follows:
import argparse
import configparser

import smtplib
from email.message import EmailMessage


def main(to_email, server, port, from_email, password):
print(f'With love, from {from_email} to {to_email}')

# Create the message
subject = 'With love, from ME to YOU'
text = '''This is an example test'''
msg = EmailMessage()
msg.set_content(text)
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email

# Open communication and send
server = smtplib.SMTP_SSL(server, port)
server.login(from_email, password)
server.send_message(msg)
server.quit()


if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('email', type=str, help='destination email')
parser.add_argument('-c', dest='config', type=argparse.FileType('r'),
help='config file', default=None)

args = parser.parse_args()
if not args.config:
print('Error, a config file is required')
parser.print_help()
exit(1)

config = configparser.ConfigParser()
config.read_file(args.config)

main(args.email,
server=config['DEFAULT']['server'],
port=config['DEFAULT']['port'],
from_email=config['DEFAULT']['email'],
password=config['DEFAULT']['password'])
  1. Create a configuration file called email_conf.ini with the specifics of your email account. For example, for a Gmail account, fill the following template. The template is available in GitHub https://github.com/PacktPublishing/Python-Automation-Cookbook/blob/master/Chapter02/email_conf.ini, but be sure to fill it with your data:
[DEFAULT]
email = EMAIL@gmail.com
server = smtp.gmail.com
port = 465
password = PASSWORD
  1. Ensure that the file cannot be read or written by other users on the system, setting the permissions of the file to allow only our user. 600 permissions means read and write access for our user, and no access to anyone else:
$ chmod 600 email_config.ini
  1. Run the script to send a test email:
$ python3 email_task.py -c email_config.ini destination_email@server.com
  1. Check the inbox of the destination email; an email should be received with the subject With love, from ME to YOU.