Python Emailing: Sending Emails with Python
Published: 2023-06-13 14:59:20

In the modern business world, email communication has become an essential tool for companies to interact with employees, customers, partners, and stakeholders. Sending one email may be simple, but how about sending hundreds or thousands of emails?

With Python, developers can automate the process of sending emails, making it easier to communicate through emails. Python provides several libraries that can be used to send emails, including smtplib, email, and MIMEText. These libraries make it possible to create and send email messages, add attachments, and even send HTML-formatted emails.

In this article, readers will learn how to set up their email account to use Simple Mail Transfer Protocol (SMTP) and how to use Python’s built-in SMTP library to send emails. Additionally, readers will also learn how to format an email message and add attachments to an email, and have the confidence to apply this skill in their work or personal projects.

## How to Install Python?
Well, the answer is you don't really need to install if you don't have one already. Simply create an account on Lightly IDE and you'll be ready with all the preconfigured environments to start your coding task.

When you're logged into your workspace, simply create a Python project and start following the remaining tutorial to automate your emails.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8xmyrs1gvtyr5ec1zat.png)


You can also install Python or other local IDEs that support Python. But believe us, this is the easiest way to start off.

## Access to an email account to send email with Python
Before we start sending emails with Python, we need to have access to an email account. In Python, we can use the built-in smtplib module to connect to an SMTP (Simple Mail Transfer Protocol) server and send an email. To do this, we need the following information:

- SMTP server address: This is the address of the SMTP server that will handle the email. This can usually be found in the email provider's documentation.
- SMTP server port number: This is the port number used by the SMTP server. This can also usually be found in the email provider's documentation.
- Email account username: This is the username used to log in to the email account.
- Email account password: This is the password used to log in to the email account.

Once we have this information, we can move on to connecting to the SMTP server and sending an email.

For example, this is the SMTP information of Gmail:
- Gmail SMTP server address: smtp.gmail.com
- Gmail SMTP username: Your Gmail address (example@gmail.com)
- Gmail SMTP password: Your Gmail password
- Gmail SMTP port (TLS): 587
- Gmail SMTP port (SSL): 465
- Gmail SMTP TLS/SSL required: Yes

To obtain your SMTP credentials from other providers, you will need to log in to your email account through your email provider's website and navigate to the settings page. From there, look for the SMTP settings section and take note of the server address, port, username, and password. Make sure to keep these details safe and secure as they are sensitive information that can be used to access your email account.

## Sending Emails with Python
Python provides two built-in libraries for sending emails: smtplib and email.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3sego4jd6n8u0ldl4zv.png)


The smtplib library allows you to send emails using the Simple Mail Transfer Protocol (SMTP). It provides a simple and intuitive interface for sending emails through a secure connection or an unsecured connection.

On the other hand, the email library allows you to create email messages that can be sent using smtplib or any other email-sending library. It provides a rich set of features for creating complex email messages such as adding attachments, HTML content, and multiple recipients. Using these two libraries together, you can easily send emails programmatically in Python.

## How to import smtplib and email in Python
In order to send an email with Python, we need to use the smtplib module to establish a connection with the SMTP (Simple Mail Transfer Protocol) server and the email module to create and format the email message. Therefore, we need to import these modules in our Python script by adding the following lines at the top of our code:

```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
```

The smtplib module provides a way to send emails using the SMTP server. The MIMEText class from the email.mime.text module creates a plain text email message, while the MIMEMultipart class from the email.mime.multipart module is used to create a message with multiple parts, such as attachments or HTML content.

## Sending a plain text email using email library in Python
In order to send an email using Python, we have to first create an email message object using the email library. This can be accomplished by importing the necessary modules and setting the recipient, sender, subject, and body of the email. We can also attach files to the email message if needed.

### Setting the email recipient, sender, subject, and body
Setting the email recipient, sender, subject and body are the basic components of an email. In Python, we can set these components using the smtplib module. We first import the module and then define our recipient, sender, subject and body as strings.

```python
# Create a multipart message object
message = MIMEMultipart()

# Set the email sender, recipient, and subject
message['From'] = 'sender@example.com'
message['To'] = 'recipient@example.com'
message['Subject'] = 'Your email subject'

# Set the email body
body = 'This is the content of your email.'
message.attach(MIMEText(body, 'plain'))
```

We then call the SMTP() function to set up the SMTP connection. Once the connection is established, we use the sendmail() function to send the email, passing in the sender, recipient, and message body as arguments. To add a subject to the email, we include it as a header in the message.

```python
# Set up the SMTP server
smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'your_username'
password = 'your_password'

# Create a SMTP connection and login
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)

# Send the email
server.send_message(message)

# Close the SMTP connection
server.quit()
```

Make sure to replace 'sender@example.com', 'recipient@example.com', 'Your email subject', 'This is the content of your email.', 'smtp.example.com', 587, 'your_username', and 'your_password' with your actual email details.

### Attachment of files to the email message
Attaching files to an email message is a common requirement in today's world. Python makes it very simple and easy to attach files to email messages using its built-in libraries. To attach files, we need to import the MIMEMultipart and MIMEBase classes from the email.mime module.

```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
```

The MIMEMultipart class is used to create a message that can have multiple parts while the MIMEBase class is used to attach different types of files to the message.

Once we have imported the necessary classes, we can create an instance of MIMEMultipart and set its subject, from, and to fields. We can then use the MIMEBase class to attach files to the message. Finally, we need to encode the attached files using base64 and set their headers before attaching them to the message using the attach() method.

```python
# Set the email body
body = 'This is the content of your email.'
message.attach(MIMEText(body, 'plain'))

# Attach files to the email
filename = 'file1.txt'
attachment = open(filename, 'rb')

part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename= {filename}')

message.attach(part)
attachment.close()
```

## Advanced Emailing with HTML in Python
Python's email module allows us to send emails with customized HTML content. To do this, we can use the MIMEMultipart class to create a new message object that can hold both plain text and HTML content. We can then use the MIMEText class to attach the HTML content to the message object, specifying that it is in HTML format.

### Customize your email with HTML
To fully customize the HTML email, we can add CSS styles directly to the HTML content using the style attribute. Alternatively, we can create a separate CSS file and link it to the HTML content using the link tag.

It is important to note that not all email clients support CSS styles, and some may even strip them out. Therefore, it is best to keep the styling simple and avoid using complex CSS features.

To create a HTML email using Python, the following steps can be followed:

1. Import the required libraries and modules - smtplib, email.mime.text and email.mime.multipart.
2. Create an instance of SMTP class by specifying the SMTP server address and port number.
3. Login to the SMTP server using valid credentials.
4. Create an instance of MIMEMultipart class and add the subject and recipient(s) to the message.
5. Add the HTML content to the message using email.mime.text.MIMEText and set the content type to 'html'.
6. Attach any required files or images to the message using email.mime.image.MIMEImage or email.mime.application.MIMEApplication.
7. Send the message using the sendmail method of the SMTP instance.

### How to add CSS to the email
To add CSS to the email, we need to modify the HTML content of the email. In the email message body, we can include inline CSS styles or link to an external CSS file. To include inline styles, we need to use the style attribute in the HTML tags. For example, to set the font color of the text to red, we can use the following code:

```html
<p style="color: red;">This is some text in red color</p>
```

To link to an external CSS file, we need to add a link tag in the head section of the HTML content. For example, if the CSS file is named styles.css and is located in the same directory as our Python script, we can use the following code:

```html
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
```

Then, we need to define the CSS styles in the styles.css file. For example, to set the font color of the text to red, we can use the following code:

```css
p {
    color: red;
}
```

By following these steps, we can add CSS styles to our email messages and make them more visually appealing.

### How to send HTML emails in Python
Sending an email with HTML content using Python is quite simple. With the smtplib and email libraries noted earlier, you can import the necessary libraries and set up the email content as follows:

```python
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Create a multipart message object
message = MIMEMultipart('alternative')

# Set the email sender, recipient, and subject
message['From'] = 'sender@example.com'
message['To'] = 'recipient@example.com'
message['Subject'] = 'Your email subject'

# Create the HTML content of the email
html_content = '''
<html>
<head></head>
<body>
    <h1>This is the HTML content of your email</h1>
    <p>You can use HTML tags to format the email content.</p>
</body>
</html>
'''

# Attach the HTML content to the email
html_part = MIMEText(html_content, 'html')
message.attach(html_part)
```

In the above example, the email content is provided as HTML using the MIMEText class with the 'html' parameter. You can modify the html_content variable to include the desired HTML content for your email. You can use HTML tags and CSS styling within the html_content to format your email.

Make sure to replace 'sender@example.com', 'recipient@example.com', 'Your email subject', 'smtp.example.com', 587, 'your_username', and 'your_password' with your actual email details.

Then, set up the SMTP server and send the email. Remember to ensure that the SMTP server details are correct and that you have the necessary permissions to send emails through the server.

```python
# Set up the SMTP server
smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'your_username'
password = 'your_password'

# Create a SMTP connection and login
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(username, password)

# Send the email
server.send_message(message)

# Close the SMTP connection
server.quit()
```

## Sending multiple emails to different recipients using Python
Besides creating emails, you can also send multiple emails to different recipients using the loop function. To send multiple personalized emails in Python, you can use the smtplib and email libraries along with a loop to iterate over your recipients and customize the email content for each recipient.

### Creating the recipients list in Python to send multiple emails
Before we start sending emails, you'll need to create a recipients list for the email to loop over. you can use various methods depending on your specific use case. Here are a few examples:

Creating a list of dictionaries:
```python
recipients = [
    {'name': 'John Doe', 'company': 'ABC Corp', 'email': 'john.doe@example.com'},
    {'name': 'Jane Smith', 'company': 'XYZ Inc', 'email': 'jane.smith@example.com'},
    # Add more recipients as needed
]
```

In this example, each recipient is represented as a dictionary containing the 'name', 'company', and 'email' keys. You can add as many recipients as needed by appending dictionaries to the recipients list.

Reading recipient data from a CSV file:
```python
import csv

recipients = []

with open('recipients.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        recipients.append(row)
```

In this example, you can store recipient data in a CSV file with columns like 'name', 'company', and 'email'. The code reads the CSV file using the csv.DictReader class and appends each row (dictionary) to the recipients list.

Fetching recipient data from a database:
```python
import sqlite3

recipients = []

# Connect to the database
conn = sqlite3.connect('mydatabase.db')
cursor = conn.cursor()

# Execute a query to fetch recipient data
cursor.execute("SELECT name, company, email FROM recipients_table")

# Fetch all rows
rows = cursor.fetchall()

# Iterate over rows and append recipient dictionaries
for row in rows:
    recipient = {'name': row[0], 'company': row[1], 'email': row[2]}
    recipients.append(recipient)

# Close the database connection
conn.close()
```

In this example, recipient data is fetched from a database using the SQLite module as an illustration. You'll need to modify the database connection and query according to your database type and structure. The fetched data is then appended to the recipients list as dictionaries.

These are just a few examples of how you can create the recipients list for looping over in your email-sending script. The specific method you choose will depend on how you store and retrieve recipient data in your application.

### Create a template to send multiple emails to different recipients using Python
Follow the library imports that we've noted earlier and set up the email content and recipient list as follows:

```python
# Define the email sender and subject
sender = 'sender@example.com'
subject = 'Your email subject'

# Define the email body template
email_template = '''
Dear {name},

This is a personalized email for {company}. Thank you for your interest in our services.

Best regards,
Your Company
'''

# Define the list of recipients with their names and companies
recipients = [
    {'name': 'John Doe', 'company': 'ABC Corp', 'email': 'john.doe@example.com'},
    {'name': 'Jane Smith', 'company': 'XYZ Inc', 'email': 'jane.smith@example.com'},
    # Add more recipients as needed
]
```

You can also modify the recipient list according to the different ways of listing recipients that we've showed earlier, and send the personalized email using the following code:

```python
# Set up the SMTP server
smtp_server = 'smtp.example.com'
smtp_port = 587
username = 'your_username'
password = 'your_password'

# Iterate over the recipients and send personalized emails
for recipient in recipients:
    # Create a multipart message object
    message = MIMEMultipart()

    # Set the email sender, recipient, and subject
    message['From'] = sender
    message['To'] = recipient['email']
    message['Subject'] = subject

    # Customize the email body using the template
    email_body = email_template.format(name=recipient['name'], company=recipient['company'])

    # Attach the email body
    message.attach(MIMEText(email_body, 'plain'))

    # Create a SMTP connection and login
    server = smtplib.SMTP(smtp_server, smtp_port)
    server.starttls()
    server.login(username, password)

    # Send the email
    server.send_message(message)

    # Close the SMTP connection
    server.quit()
```

In the code above, the email body is personalized for each recipient using the email_template string. The placeholders {name} and {company} are dynamically replaced with the recipient's name and company using the format() method. The loop iterates over each recipient in the recipients list, creates a personalized email message, and sends it using the SMTP server.

Make sure to replace 'sender@example.com', 'Your email subject', 'smtp.example.com', 587, 'your_username', and 'your_password' with your actual email details. Also, update the recipients list with the names, companies, and email addresses of the recipients.

## Are there other Python libraries made for email communication?
Yes. While this article covers the basics of sending emails with Python, there are other Python libraries available that can provide additional functionality for email communication. Some of these libraries include yagmail, Mailchimp, pyzmail, IMAPClient, and imbox.

By exploring these libraries, readers can gain a better understanding of how to handle attachments, send personalized emails, and integrate with third-party email services. Additionally, readers can learn about advanced email features such as email filtering and parsing with these libraries. Therefore, I encourage readers to further explore these Python libraries to expand their knowledge and capabilities in email communication.

## Learning Python with an online Python compiler
Learning a new programming language might be intimidating if you're just starting out. Lightly IDE, however, makes learning Python simple and convenient for everybody. [Lightly IDE](https://www.lightly-dev.com/) was made so that even complete novices may get started writing code.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qvkixggtg6me40s75t5b.png)


Lightly IDE's intuitive design is one of its many strong points. If you've never written any code before, don't worry; the interface is straightforward. You may quickly get started with Python programming with our [online Python compiler](https://www.lightly-dev.com/python/) only a few clicks.

The best part of Lightly IDE is that it is cloud-based, so your code and projects are always accessible from any device with an internet connection. You can keep studying and coding regardless of where you are at any given moment.

Lightly IDE is a great place to start if you're interested in learning Python. Learn and collaborate with other learners and developers on your projects and receive comments on your code now.

[Python Emailing: Sending Emails with Python](https://www.lightly-dev.com/blog/python-send-email/)