There are some situations in which System Admins must send emails from their servers. For those who are working with the newest Linux versions, Python version 3 has become its default. In this article, I will share how to send SMTP authenticated emails by using a Python 3 script.
The following script uses both libraries “smtplib” to establish the connection with the server, and “sys” to obtain parameters from the command line. In this case, the parameter “-a” is used to attach a text file to be sent, and the parameter “-s” is used to set the subject of the message. You should change the lines below for your environment.
1 – Set your mail server hostname and port.
mailobj = smtplib.SMTP('myserver.com',587)
2 – Username and password.
mailobj.login('user@myserver.com','secret')
3 – Correspondent and recipient.
sender = 'from@myserver.com'
receivers = 'to@myserver.com'
4 – This is the correct way to run the script:
./send-email.py -a "/some/text/file" -s "subject"
Finally, here is the script source code:
#!/usr/bin/python3 import smtplib, sys param1 = sys.argv[1] param2 = sys.argv[3] if "-a" in param1: attached_file = sys.argv[2] f = open(attached_file, "r") body_text = f.read() if "-s" in param2: subject = sys.argv[4] mailobj = smtplib.SMTP('myserver.com',587) mailobj.ehlo() mailobj.starttls() mailobj.login('user@myserver.com','secret') sender = 'from@myserver.com' receivers = 'to@myserver.com' message = """From: FROM To: TO Subject: SUBJECT TEXT """ message = message.replace("FROM",sender) message = message.replace("TO",receivers) message = message.replace("SUBJECT",subject) message = message.replace("TEXT",body_text) mailobj.sendmail(sender, receivers, message) mailobj.quit()