Sending emails directly from a Python script can be achieved using a variety of libraries such as smtplib, email, and email.message. This capability is particularly useful for automating tasks like sending notifications, updates, or backups. Let's explore a simple way to send an email using Python.

Before diving into the code, ensure you have a port 25 email server (like Gmail's smtp server at smtp.gmail.com) and the necessary credentials to authenticate. For security reasons, also enable 'Less secure apps' in your Gmail account settings or use an App Password if you have 2-Step Verification turned on.

Setting Up Our Email Server and Credentials
For our example, we'll use Gmail's SMTP server. First, import the required libraries:

{% highlight python %} import smtplib from email.message import EmailMessage {% endhighlight %}
Creating a New Email Message

Next, create an instance of the EmailMessage class to compose your email:
{% highlight python %} msg = EmailMessage() msg.set_content('Hello, this is an automated email sent from Python!') {% endhighlight %}
Configuring Recipients and Senders

Set the recipients and the sender of the email using the set_recipients and set_from methods:
{% highlight python %} msg.set_from('Sender Name <sender@email.com>') msg.set_recipients(['recipient@email.com']) {% endhighlight %}
Sending the Email Using the smtplib Library

To send the email, create an SMTP object and use its send_message method. For Gmail, use smtp.gmail.com and port 587 with starttls:
{% highlight python %} smtp_server = 'smtp.gmail.com' smtp_port = 587 with smtplib.SMTP(smtp_server, smtp_port) as server: server.starttls() server.login('sender@email.com', 'Password') server.send_message(msg) {% endhighlight %}




















Handling SMTP Exceptions
To handle potential SMTP-related errors, wrap the send_message call in a try-except block:
{% highlight python %} try: server.send_message(msg) except smtplib.SMTPException as e: print(f'Error: {e}') {% endhighlight %}
That's it! You've successfully created a Python script to send an email. To make this script more useful, consider adding features like:
- Argument parsing for recipient, subject, and message content
- IMAP or POP3-based email checking for new messages
- Configurable email server and SMTP port
- Attachment support
Lastly, remember to handle email contents and credentials securely, especially when distributing your script. Requesting user input for sensitive information or using environment variables can help keep your script safe.