SoFunction
Updated on 2025-03-05

Code examples (mail, excel) for using Python to automate office work

1. Preparation for Python automated office

1.1 Install the necessary libraries

Before implementing automated office work, relevant libraries need to be installed. The following are commonly used Python libraries:

  • Mail automationsmtplib(Send an email),imaplib(incoming mail),email(Processing email content).
  • Excel Operationsopenpyxl(operate Excel files),pandas(Data processing).
  • Environment configurationdotenv(Manage environment variables).

The installation method is as follows:

pip install openpyxl pandas python-dotenv

1.2 Set up email service

In order to be able to send and receive mail, you need:

  • Make sure that the mailbox has SMTP (send) and IMAP (receive) services enabled.
  • Use an authorized app key (such as Gmail's "App-specific Password").

2. Automatic email processing

2.1 Send email

Sample code

The following code implements sending emails through SMTP:

import smtplib
from  import MIMEText
from  import MIMEMultipart
 
def send_email(sender_email, sender_password, recipient_email, subject, body):
    # Create a mail object    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = subject
    (MIMEText(body, 'plain'))
 
    # Connect to the SMTP server and send emails    try:
        with ('', 587) as server:
            ()
            (sender_email, sender_password)
            server.send_message(msg)
        print("The email was sent successfully!")
    except Exception as e:
        print(f"Email sending failed:{e}")
 
# Call examplesend_email(
    sender_email='your_email@',
    sender_password='your_app_password',
    recipient_email='recipient@',
    subject='Test email',
    body='This is a test email sent through Python.  '
)

Things to note

  1. Gmail users need to enable "Allow unsafe app access" or generate an App password.
  2. When replacing the SMTP service address, other mailbox service providers may require different configurations:
    • QQ Email
    • Outlook:smtp.

2.2 Receive and read emails

Sample code

The following code shows how to read unread messages through IMAP:

import imaplib
import email
 
def fetch_emails(email_address, password):
    try:
        # Connect to the IMAP server        with imaplib.IMAP4_SSL('') as mail:
            (email_address, password)
            ('inbox')  # Select Inbox 
            # Search for unread emails            status, messages = (None, 'UNSEEN')
            for num in messages[0].split():
                status, msg_data = (num, '(RFC822)')
                for response_part in msg_data:
                    if isinstance(response_part, tuple):
                        msg = email.message_from_bytes(response_part[1])
                        print(f"From: {msg['from']}")
                        print(f"theme: {msg['subject']}")
                        if msg.is_multipart():
                            for part in ():
                                if part.get_content_type() == 'text/plain':
                                    print(f"content: {part.get_payload(decode=True).decode()}")
                        else:
                            print(f"content: {msg.get_payload(decode=True).decode()}")
    except Exception as e:
        print(f"Mail reading failed:{e}")
 
# Call examplefetch_emails('your_email@', 'your_app_password')

3. Excel automated processing

3.1 Reading and writing Excel files

Sample code

useopenpyxlRead and write Excel:

import openpyxl
 
# Open Excel fileworkbook = openpyxl.load_workbook('')
sheet = 
 
# Read datafor row in sheet.iter_rows(min_row=1, max_row=5, min_col=1, max_col=3):
    print([ for cell in row])
 
# Write datasheet['A6'] = 'New Data'
('example_updated.xlsx')
print("Excel file updated!")

3.2 Data processing and analysis

Sample code

usepandasAnalysis of Excel data:

import pandas as pd
 
# Read Excel filesdata = pd.read_excel('')
 
# Print the first five elements of dataprint(())
 
# Data Processingdata['Total Score'] = data['math'] + data['English'] + data['science']
print(data)
 
# Save the resultsdata.to_excel('', index=False)
print("The data processing is completed and saved!")

4. Comprehensive example: Read Excel attachments from emails and analyze them

The following code shows a complete automated workflow:

  • Receive mail and extract attachments.
  • Read Excel data and perform analysis.
  • Send the result back to the sender.

Sample code

import os
import imaplib
import email
import pandas as pd
from  import MIMEText
from  import MIMEMultipart
import smtplib
 
def fetch_and_process_email(email_address, password):
    # Connect to IMAP    with imaplib.IMAP4_SSL('') as mail:
        (email_address, password)
        ('inbox')
 
        # Search for emails with attachments        status, messages = (None, 'ALL')
        for num in messages[0].split():
            status, msg_data = (num, '(RFC822)')
            for response_part in msg_data:
                if isinstance(response_part, tuple):
                    msg = email.message_from_bytes(response_part[1])
                    if msg.is_multipart():
                        for part in ():
                            if part.get_filename():  # Find the attachment                                file_path = ((), part.get_filename())
                                with open(file_path, 'wb') as f:
                                    (part.get_payload(decode=True))
                                print(f"Attachment saved: {file_path}")
 
                                # Process attachment data                                data = pd.read_excel(file_path)
                                data['Total Score'] = (axis=1)
                                processed_path = ''
                                data.to_excel(processed_path, index=False)
                                print("Data processing is completed")
 
                                # Return processing results                                send_email(
                                    sender_email=email_address,
                                    sender_password=password,
                                    recipient_email=msg['from'],
                                    subject='Data processing results',
                                    body='The attachment has been processed, please check it.  ',
                                    attachment_path=processed_path
                                )
 
def send_email(sender_email, sender_password, recipient_email, subject, body, attachment_path):
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = recipient_email
    msg['Subject'] = subject
    (MIMEText(body, 'plain'))
 
    # Add attachment    with open(attachment_path, 'rb') as f:
        attachment = ('application', 'octet-stream')
        attachment.set_payload(())
        .encode_base64(attachment)
        attachment.add_header('Content-Disposition', f'attachment; filename={(attachment_path)}')
        (attachment)
 
    # Send email    with ('', 587) as server:
        ()
        (sender_email, sender_password)
        server.send_message(msg)
    print("The email has been sent!")
 
# Call examplefetch_and_process_email('your_email@', 'your_app_password')

This is the article about code examples (email, excel) for using Python to implement automated office. For more related Python automation office content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!