Skip to main content
Practice

Analyzing Sales Reports with Python and Sending Emails

In this lesson, we will analyze the Sales Data by Client DataFrame defined in the previous lesson, create customized reports based on the data, and implement a program that sends these reports via email.


Setting Up SMTP Connection

First, configure the SMTP server, port, email address, and password for sending emails.

Email Sending Configuration
# SMTP server configuration
smtp_server = "smtp.gmail.com"
smtp_port = 587
sender_email = "your_email@gmail.com"
password = "your_email_password"

# Connecting to the SMTP server
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls() # Start TLS (Transport Layer Security) encryption
server.login(sender_email, password)
  1. smtplib.SMTP(): Sets up the SMTP server and port. In the example code, Gmail is used arbitrarily, but the values can be set differently according to the settings of the email provider in use.

  2. starttls(): Encrypts communication with the server.

  3. login(): Logs in with the email account.


Composing Email Body

Now, create the customized sales reports for each client in text form to use as the email body.

Utilize the previously created sales data to compose emails for each client.

Composing Email Body
def create_email_body(client_name, monthly_sales):
body = f"Hello, {client_name}!\n\n"
body += "Here is a summary of your sales over the past 3 months:\n\n"

for _, row in monthly_sales.iterrows():
body += f"Sales for {row['YearMonth']}: ${row['Sales Amount']}\n"
body += "\nThank you.\n"

return body

This function takes the client's name and sales data to create the email body.

iterrows() is used to loop through each client's monthly sales data to compose the body.


Sending Emails

Now that you’ve composed the email body, let's see how to send customized emails to each client.

The code below creates an email message using MIMEText and sends it using the SMTP server.

Sending Emails
from email.mime.text import MIMEText

# Sending emails to each client
for client_id, group in monthly_sales.groupby('Client ID'):
client_name = group['Client Name'].iloc[0]
recipient_email = "client_email@example.com" # Client's email address
email_body = create_email_body(client_name, group)

# Creating email message
msg = MIMEText(email_body)
msg['Subject'] = f"{client_name}'s Monthly Sales Report"
msg['From'] = sender_email
msg['To'] = recipient_email

# Sending email
server.sendmail(sender_email, recipient_email, msg.as_string())
print(f"Email sent to {client_name}!")
  1. MIMEText(): Creates the email body. The body is the customized text created by the create_email_body() function.

  2. sendmail(): Sends the composed email to the client.

  3. msg['Subject']: Sets the email subject.

Using this code, you can automatically send customized sales reports to each client via email.


Finalizing

After sending all emails, it's necessary to disconnect from the server.

Call quit() as shown below to terminate the connection to the SMTP server.

Disconnecting from SMTP Server
# Disconnecting from the SMTP server
server.quit()

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.