You need to offer a valid email address and password to send an email through this recipe. We pass the email server, SMTP port, fromaddress, toaddress, email subject, and email body as the arguments, and receive the password to your email (from) address using the getpass library (so that your email password is not displayed in plain text).
Listing 5.10 gives the simple email client as follows:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 5 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import argparse import getpass def mail_client(host, port, fromAddress, password, toAddress, subject, body): msg = MIMEMultipart() msg['From'] = fromAddress msg['To'] = toAddress msg['Subject'] = subject message = body msg.attach(MIMEText(message)) mailserver = smtplib.SMTP(host,port) # Identify to the SMTP Gmail Client mailserver.ehlo() # Secure with TLS Encryption mailserver.starttls() # Reidentifying as an encrypted connection mailserver.ehlo() mailserver.login(fromAddress, password) mailserver.sendmail(fromAddress,toAddress,msg.as_string()) print ("Email sent from:", fromAddress) mailserver.quit() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Mail Server Example') parser.add_argument('--host', action="store",
dest="host", type=str, required=True) parser.add_argument('--port', action="store",
dest="port", type=int, required=True) parser.add_argument('--fromAddress', action="store",
dest="fromAddress", type=str, required=True) parser.add_argument('--toAddress', action="store",
dest="toAddress", type=str, required=True) parser.add_argument('--subject', action="store",
dest="subject", type=str, required=True) parser.add_argument('--body', action="store",
dest="body", type=str, required=True) password = getpass.getpass("Enter your Password:") given_args = parser.parse_args() mail_client(given_args.host, given_args.port,
given_args.fromAddress, password, given_args.toAddress,
given_args.subject, given_args.body)
This recipe logs in as a simple Python-based email client for your email account, and sends a plain-text email to the toaddress that you have specified. Running this program gives the following output:
$ python 15_10_secure_mail_client.py --host='smtp.gmail.com' --port=587 [email protected] [email protected] -subject="Hi, Hello.." --body="Good to see you all. Keep in touch. Take Care" python3 15_10_secure_mail_client.py --host='smtp.gmail.com' --port=587 [email protected] [email protected] -subject="Hi, Hello.." --body="Good to see you all. Keep in touch. Take Care" Enter your Password: Email sent from: [email protected]
The output is indicated by the following screenshot of the console, as well as the email received:
Sending Email from your Email Address