First, I make sure I have the necessary libraries. I need smtplib
for sending the email and email.mime
for composing the email with different parts (like the subject, body, and attachments). These are included in Python’s standard library, so I don’t need to install them manually.
I also imported smtplib
for sending emails and MIMEText
and MIMEMultipart
for creating the email structure.
I set up the SMTP server, port, and credentials (my email address and password). Which is a Gmail SMTP server. I had to generate a specific password only for python for this to work in the Gmail website
I wrote the subject and a body for the email. This is where I define the message content.
I used MIMEMultipart
to create the email message, which allows me to send both plain text and HTML content or even attachments in the future. I then attach the body to the email.
After creating the email, I’ll connect to the SMTP server, login, and send the email. Then, I will close the connection.
Once the script is written and saved as testemailer.py
, I’m ready to run it. So I made the script executable by running …
To execute the script and send the email, I ran
I’ve now sent an email from a Python script on my Linux server! I can customize the script to include attachments, html content, or send to multiple recipients.