Uncover the infinite in IT

Table of Contents
< All Topics

Automated Email Sender from CSV or Excel File

Prerequisites:

  • Python installed on your machine
  • Pip (Python package installer) installed
  • Basic knowledge of the command line

Step 1: Create the Script

  1. Open a text editor (like Notepad, VSCode, Midnight Commander or any other code editor).
  2. Copy and paste the script provided in the previous responses into the text editor.
  3. Save the file with a .py extension, for example, sendmail.py.

The script:

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import openpyxl

# Function to send an email
def send_email(subject, body, to_email, smtp_server, smtp_port, smtp_username, smtp_password, from_email, encryption):
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    if encryption.lower() == 'starttls':
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.ehlo()
        server.starttls()
    elif encryption.lower() == 'ssl/tls':
        server = smtplib.SMTP_SSL(smtp_server, smtp_port)
    else:
        print("Unsupported encryption type. Exiting.")
        return

    server.ehlo()
    server.login(smtp_username, smtp_password)
    server.sendmail(from_email, to_email, msg.as_string())
    server.quit()

# Function to process and delete data file (either CSV or Excel)
def process_and_delete_data(file_path, smtp_server, smtp_port, smtp_username, smtp_password, from_email):
    _, file_extension = os.path.splitext(file_path)

    if file_extension.lower() == '.csv':
        delimiter = ';'
        import_module = lambda: __import__('csv')
    elif file_extension.lower() == '.xlsx':
        import_module = lambda: __import__('openpyxl')
    else:
        print(f"Unsupported file format: {file_extension}. Exiting.")
        return

    try:
        data_module = import_module()
    except ImportError:
        print(f"Could not import the required module for {file_extension}. Exiting.")
        return

    with open(file_path, 'r', newline='', encoding='utf-8') as file:
        if file_extension.lower() == '.csv':
            csv_reader = data_module.DictReader(file, delimiter=delimiter)
        elif file_extension.lower() == '.xlsx':
            wb = data_module.load_workbook(file_path)
            sheet = wb.active

            # Get user input for column names
            columns_input = input("Enter the column names you want to use (comma-separated): ")
            columns = [col.strip() for col in columns_input.split(',')]

            # Warn the user about column name format
            print("Warning: Column names should not have spaces and should match exactly with the names in CSV/XLSX.")
            print("Example format: Column1,Column2,Column3")

            csv_reader = [dict(zip(columns, row)) for row in sheet.iter_rows(values_only=True)]

    for row in csv_reader:
        to_email = input("Enter the destination email address: ")  # Send all emails to user-specified address

        # Get user input for the subject columns
        subject_columns_input = input("Enter the columns you want to use in the subject (comma-separated): ")
        subject_columns = [col.strip() for col in subject_columns_input.split(',')]

        # Build the subject based on user input columns
        subject = ' '.join([row[col] for col in subject_columns])

        body = ''
        for col, value in row.items():
            body += f"{col}: {value}\n"

        # Get user input for encryption type
        encryption = input("Enter the encryption type (STARTTLS, SSL/TLS, etc.): ")

        try:
            send_email(subject, body, to_email, smtp_server, smtp_port, smtp_username, smtp_password, from_email, encryption)
            print(f"Email sent to {to_email}")
        except Exception as e:
            print(f"Failed to send email: {str(e)}")

    # Delete the processed data file
    os.remove(file_path)
    print(f"Data file deleted: {file_path}")

# Get user input for SMTP and email details
smtp_server = input("Enter the SMTP server: ")
smtp_port = int(input("Enter the SMTP server port: "))
smtp_username = input("Enter the SMTP username: ")
smtp_password = input("Enter the SMTP password: ")
from_email = input("Enter the source email address: ")

# Get user input for the data file path
data_file_path = input("Enter the path of the CSV or Excel file: ")

# Process the data file
process_and_delete_data(data_file_path, smtp_server, smtp_port, smtp_username, smtp_password, from_email)

print("All emails sent and data file processed and deleted successfully.")

Step 2: Install Dependencies

Open your command line or terminal and navigate to the directory where the script is located.

pip install smtplib openpyxl

This will install the required libraries for sending emails and handling Excel files.

Step 3: Run the Script

  1. Navigate to the directory containing your script and the data file (CSV or Excel) using the command line.
cd /path/to/your/script
  1. Run the script using the following command:
python sendmail.py

Step 4: Input SMTP and Email Details

Follow the prompts to input the necessary details:

  • SMTP server
  • SMTP port
  • SMTP username
  • SMTP password
  • Source email address
  • Path of the CSV or Excel file
  • Destination email address
  • Columns for the subject
  • Encryption type (STARTTLS, SSL/TLS, etc.)

Step 5: Script Execution

The script will process the data file, send emails, and delete the data file. You will see output messages indicating the progress of the script, such as “Email sent to [destination email]”.

Example:

Enter the SMTP server: mail.example.com
Enter the SMTP server port: 587
Enter the SMTP username: your_username@example.com
Enter the SMTP password: your_password
Enter the source email address: noreply@example.com
Enter the path of the CSV or Excel file: /path/to/your/data.csv
Enter the destination email address: info@example.com
Enter the columns you want to use in the subject (comma-separated): IP,Severity,NVT Name
Enter the encryption type (STARTTLS, SSL/TLS, etc.): STARTTLS

Email sent to info@example.com
Data file deleted: /path/to/your/data.csv

All emails sent and data file processed and deleted successfully.

Notes:

  • Make sure to replace placeholder values (like server addresses, usernames, and passwords) with your actual information.
  • Ensure that your CSV or Excel file has the specified columns with matching names as used in the script.
  • Pay attention to any warnings or error messages displayed during script execution.

This tutorial provides a step-by-step guide on using the script for automated email sending based on data from a CSV or Excel file. Adjust the script and inputs based on your specific use case and requirements.