Skip to content

DataDave-Dev/Send-Mails

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mass Email Sending System / Sistema de Envío Masivo de Correos

Language Version

Language / Idioma


English Version

Mass Email Sending System

Automated system for sending personalized mass emails using Python. Designed for email marketing campaigns, mass notifications, and business communications with sending rate control and detailed logging.

Key Features

  • Mass email sending from Excel files
  • Template personalization using Jinja2
  • Sending rate control to avoid spam blocks
  • Sent emails logging in Excel
  • Responsive HTML templates compatible with multiple email clients
  • Dry-run mode for testing without sending real emails
  • Detailed logging of all operations
  • Clean architecture with domain and service separation

Requirements

  • Python 3.7+
  • SMTP account (Gmail, Outlook, custom server, etc.)

Project Structure

Send-Mails/
├── src/
│   ├── config.py                 # Configuration and environment variables
│   ├── domain/
│   │   ├── email.py              # Email data model
│   │   └── recipient.py          # Recipient data model
│   ├── services/
│   │   ├── smtp_sender.py        # SMTP sending service
│   │   ├── rate_limiter.py       # Sending rate control
│   │   ├── html_renderer.py      # Jinja2 template rendering
│   │   ├── excel_loader.py       # Load recipients from Excel
│   │   └── sent_logger.py        # Log sent emails
│   └── utils/
│       └── logger.py             # Logging configuration
├── templates/
│   ├── invitation.html           # Invitation template
│   └── reactivation.html         # Reactivation template
├── data/
│   ├── recipients.xlsx           # Recipients file
│   └── correos_enviados.xlsx    # Sent emails log
├── main.py                       # Main script
├── generate_dummy_data.py        # Test data generator
├── requirements.txt              # Project dependencies
├── .env.example                  # Environment variables example
└── README.md                     # This file

Installation

1. Clone the repository

git clone <repository-url>
cd Send-Mails

2. Create a virtual environment

python -m venv venv

3. Activate the virtual environment

Windows:

venv\Scripts\activate

Linux/Mac:

source venv/bin/activate

4. Install dependencies

pip install -r requirements.txt

5. Configure environment variables

Copy the .env.example file to .env and configure your SMTP credentials:

cp .env.example .env

Edit .env with your credentials:

# SMTP Configuration
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_password_or_app_password
FROM_EMAIL=your_email@gmail.com

# Sending limits (to avoid spam blocks)
MAX_EMAILS_PER_HOUR=100
MAX_EMAILS_PER_INTERVAL=10
INTERVAL_MINUTES=5

Gmail Configuration

If using Gmail, you need to generate an "App Password":

  1. Go to Google Account Settings
  2. Security > 2-Step Verification (must be enabled)
  3. App passwords
  4. Generate new password for "Mail"
  5. Use that password in SMTP_PASSWORD

Usage

Prepare the recipients file

Create an Excel file at data/recipients.xlsx with the following columns:

Email Name Company
example@email.com John Doe ABC Company
another@email.com Jane Smith XYZ Company

Or generate test data:

python generate_dummy_data.py

Send emails

Normal mode (sends real emails):

python main.py

Test mode (doesn't send emails, just simulates):

python main.py --dry-run

Customize templates

HTML templates are in templates/. You can customize them using Jinja2 variables:

<p>Hello {{ name }},</p>
<p>Your company {{ company }} has been selected...</p>

To change the template used, edit in main.py:73:

body_html = template_service.render("reactivation.html", context)

Advanced Configuration

Sending Limits

To avoid being marked as spam, configure limits in .env:

  • MAX_EMAILS_PER_HOUR: Maximum emails per hour (default: 250)
  • MAX_EMAILS_PER_INTERVAL: Maximum emails per interval (default: 10)
  • INTERVAL_MINUTES: Interval duration in minutes (default: 5)

Example: 10 emails every 5 minutes = 120 emails/hour maximum

Subject Customization

Edit in main.py:76:

email_content = EmailContent(
    subject="Your custom subject here",
    body_html=body_html,
    to_email=recipient.email
)

Add More Personalization Variables

  1. Add columns to Excel
  2. Modify src/services/excel_loader.py if necessary
  3. Update context in main.py:69-72:
context = {
    "name": recipient.name,
    "company": recipient.company,
    "new_variable": recipient.new_variable  # Add here
}

Logging and Monitoring

Log File

The system generates an app.log file with detailed information:

2026-01-26 10:00:00 - INFO - Starting email sender...
2026-01-26 10:00:01 - INFO - Loading recipients from data/recipients.xlsx...
2026-01-26 10:00:01 - INFO - Loaded 50 recipients.
2026-01-26 10:00:02 - INFO - Processing example@email.com...
2026-01-26 10:00:03 - INFO - Email sent successfully to example@email.com

Sent Emails Log

Sent emails are logged in data/correos_enviados.xlsx with:

  • Send date and time
  • Company
  • Recipient name
  • Email

This allows:

  • Sending audit
  • Avoiding duplicates
  • Campaign analysis

System Architecture

Domain Layer

  • email.py: Defines email content model
  • recipient.py: Defines recipient model

Services Layer

  • smtp_sender.py: Handles SMTP connection and sending
  • rate_limiter.py: Implements sending rate control
  • html_renderer.py: Renders Jinja2 templates
  • excel_loader.py: Loads and validates data from Excel
  • sent_logger.py: Logs sent emails to Excel

Utilities

  • logger.py: Centralized logging configuration
  • config.py: Configuration and environment variables management

Troubleshooting

Error: "Authentication failed"

  • Verify that SMTP_USER and SMTP_PASSWORD are correct
  • If using Gmail, make sure to use an "App Password"
  • Verify that 2-Step Verification is enabled

Error: "Connection refused"

  • Verify that SMTP_SERVER and SMTP_PORT are correct
  • Verify that your firewall allows outgoing connections on SMTP port
  • Some ISPs block port 25, use 587 (TLS) or 465 (SSL)

Emails Go to Spam

  • Configure SPF, DKIM, and DMARC on your domain
  • Don't send too many emails in a short time
  • Adjust sending limits in .env
  • Use a verified domain instead of Gmail/Outlook
  • Avoid spam words in subject and content

Error: "No such file or directory: 'data/recipients.xlsx'"

python generate_dummy_data.py

Or manually create the data/ folder and Excel file.

Best Practices

  1. Always use --dry-run first to verify everything works
  2. Keep backups of the recipients file
  3. Monitor the log file during mass sends
  4. Respect sending limits of your SMTP provider
  5. Personalize messages for better open rates
  6. Include unsubscribe option to comply with GDPR/CAN-SPAM
  7. Verify emails before sending (syntax, valid domains)
  8. Use responsive templates for mobile and desktop

Security

  • NEVER upload the .env file to the repository (it's in .gitignore)
  • Use app passwords instead of your main password
  • Limit access to log file (may contain sensitive information)
  • Consider encrypting the Excel file with recipients

Contributing

Contributions are welcome. Please:

  1. Fork the project
  2. Create a branch for your feature (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

This project is for internal use. All rights reserved.

Dependencies

  • pandas: Excel data manipulation
  • openpyxl: Excel file reading/writing
  • jinja2: HTML template engine
  • python-dotenv: Environment variables management

Changelog

v1.0.0 (2026-01-26)

  • Initial mass email sending system
  • Support for customizable HTML templates
  • Sending rate control
  • Sent emails logging
  • Dry-run mode for testing
  • Invitation and reactivation templates

FAQ

How many emails can I send per day? Depends on your SMTP provider:

  • Gmail: ~500/day
  • Outlook: ~300/day
  • SendGrid/AWS SES: According to your plan

Can I use other SMTP providers? Yes, just configure SMTP_SERVER, SMTP_PORT and credentials in .env

How do I add attachments? Modify smtp_sender.py to include attachments using MIMEBase

Does it work with custom SMTP servers? Yes, configure your server's SMTP parameters in .env

Can I send in plain text format? Yes, modify EmailContent to include body_text and adjust smtp_sender.py

Roadmap

  • Attachment support
  • Web panel for campaign management
  • Open and click statistics
  • CRM integration
  • Scheduled sending
  • A/B testing of templates
  • Email validation before sending
  • Multi-language support

Versión en Español

Sistema de Envío Masivo de Correos Electrónicos

Sistema automatizado para el envío masivo de correos electrónicos personalizados usando Python. Diseñado para campañas de email marketing, notificaciones masivas y comunicaciones empresariales con control de tasas de envío y registro detallado.

Características Principales

  • Envío masivo de correos desde archivos Excel
  • Personalización de plantillas usando Jinja2
  • Control de tasa de envío para evitar bloqueos por spam
  • Registro de correos enviados en Excel
  • Plantillas HTML responsivas compatibles con múltiples clientes de correo
  • Modo dry-run para pruebas sin enviar correos reales
  • Logging detallado de todas las operaciones
  • Arquitectura limpia con separación de dominios y servicios

Requisitos

  • Python 3.7+
  • Cuenta SMTP (Gmail, Outlook, servidor personalizado, etc.)

Estructura del Proyecto

Send-Mails/
├── src/
│   ├── config.py                 # Configuración y variables de entorno
│   ├── domain/
│   │   ├── email.py              # Modelo de datos de Email
│   │   └── recipient.py          # Modelo de datos de Destinatario
│   ├── services/
│   │   ├── smtp_sender.py        # Servicio de envío SMTP
│   │   ├── rate_limiter.py       # Control de tasa de envío
│   │   ├── html_renderer.py      # Renderizado de plantillas Jinja2
│   │   ├── excel_loader.py       # Carga de destinatarios desde Excel
│   │   └── sent_logger.py        # Registro de correos enviados
│   └── utils/
│       └── logger.py             # Configuración de logging
├── templates/
│   ├── invitation.html           # Plantilla de invitación
│   └── reactivation.html         # Plantilla de reactivación
├── data/
│   ├── recipients.xlsx           # Archivo con destinatarios
│   └── correos_enviados.xlsx    # Registro de envíos
├── main.py                       # Script principal
├── generate_dummy_data.py        # Generador de datos de prueba
├── requirements.txt              # Dependencias del proyecto
├── .env.example                  # Ejemplo de variables de entorno
└── README.md                     # Este archivo

Instalación

1. Clonar el repositorio

git clone <url-del-repositorio>
cd Send-Mails

2. Crear un entorno virtual

python -m venv venv

3. Activar el entorno virtual

Windows:

venv\Scripts\activate

Linux/Mac:

source venv/bin/activate

4. Instalar dependencias

pip install -r requirements.txt

5. Configurar variables de entorno

Copiar el archivo .env.example a .env y configurar las credenciales SMTP:

cp .env.example .env

Editar .env con tus credenciales:

# Configuración SMTP
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=tu_email@gmail.com
SMTP_PASSWORD=tu_password_o_app_password
FROM_EMAIL=tu_email@gmail.com

# Límites de envío (para evitar bloqueos por spam)
MAX_EMAILS_PER_HOUR=100
MAX_EMAILS_PER_INTERVAL=10
INTERVAL_MINUTES=5

Configuración para Gmail

Si usas Gmail, necesitas generar una "Contraseña de aplicación":

  1. Ir a Configuración de cuenta de Google
  2. Seguridad > Verificación en dos pasos (debe estar activada)
  3. Contraseñas de aplicaciones
  4. Generar nueva contraseña para "Correo"
  5. Usar esa contraseña en SMTP_PASSWORD

Uso

Preparar el archivo de destinatarios

Crear un archivo Excel en data/recipients.xlsx con las siguientes columnas:

Email Name Company
ejemplo@email.com Juan Pérez Empresa ABC
otro@email.com María López Empresa XYZ

O generar datos de prueba:

python generate_dummy_data.py

Enviar correos

Modo normal (envía correos reales):

python main.py

Modo de prueba (no envía correos, solo simula):

python main.py --dry-run

Personalizar plantillas

Las plantillas HTML están en templates/. Puedes personalizarlas usando variables Jinja2:

<p>Hola {{ name }},</p>
<p>Tu empresa {{ company }} ha sido seleccionada...</p>

Para cambiar la plantilla usada, editar en main.py:73:

body_html = template_service.render("reactivation.html", context)

Configuración Avanzada

Límites de envío

Para evitar ser marcado como spam, configura los límites en .env:

  • MAX_EMAILS_PER_HOUR: Máximo de correos por hora (default: 250)
  • MAX_EMAILS_PER_INTERVAL: Máximo de correos por intervalo (default: 10)
  • INTERVAL_MINUTES: Duración del intervalo en minutos (default: 5)

Ejemplo: 10 correos cada 5 minutos = 120 correos/hora máximo

Personalización del asunto

Editar en main.py:76:

email_content = EmailContent(
    subject="Tu asunto personalizado aquí",
    body_html=body_html,
    to_email=recipient.email
)

Agregar más variables de personalización

  1. Agregar columnas al Excel
  2. Modificar src/services/excel_loader.py si es necesario
  3. Actualizar el contexto en main.py:69-72:
context = {
    "name": recipient.name,
    "company": recipient.company,
    "nueva_variable": recipient.nueva_variable  # Agregar aquí
}

Registro y Monitoreo

Archivo de log

El sistema genera un archivo app.log con información detallada:

2026-01-26 10:00:00 - INFO - Starting email sender...
2026-01-26 10:00:01 - INFO - Loading recipients from data/recipients.xlsx...
2026-01-26 10:00:01 - INFO - Loaded 50 recipients.
2026-01-26 10:00:02 - INFO - Processing ejemplo@email.com...
2026-01-26 10:00:03 - INFO - Email sent successfully to ejemplo@email.com

Registro de envíos

Los correos enviados se registran en data/correos_enviados.xlsx con:

  • Fecha y hora de envío
  • Empresa
  • Nombre del destinatario
  • Email

Esto permite:

  • Auditoría de envíos
  • Evitar duplicados
  • Análisis de campañas

Arquitectura del Sistema

Capa de Dominio

  • email.py: Define el modelo de contenido de email
  • recipient.py: Define el modelo de destinatario

Capa de Servicios

  • smtp_sender.py: Maneja la conexión y envío SMTP
  • rate_limiter.py: Implementa el control de tasa de envío
  • html_renderer.py: Renderiza plantillas Jinja2
  • excel_loader.py: Carga y valida datos desde Excel
  • sent_logger.py: Registra correos enviados en Excel

Utilidades

  • logger.py: Configuración centralizada de logging
  • config.py: Gestión de configuración y variables de entorno

Solución de Problemas

Error: "Authentication failed"

  • Verifica que SMTP_USER y SMTP_PASSWORD sean correctos
  • Si usas Gmail, asegúrate de usar una "Contraseña de aplicación"
  • Verifica que la verificación en dos pasos esté activada

Error: "Connection refused"

  • Verifica que SMTP_SERVER y SMTP_PORT sean correctos
  • Verifica que tu firewall permita conexiones salientes en el puerto SMTP
  • Algunos ISP bloquean el puerto 25, usa 587 (TLS) o 465 (SSL)

Los correos llegan a spam

  • Configura SPF, DKIM y DMARC en tu dominio
  • No envíes demasiados correos en poco tiempo
  • Ajusta los límites de envío en .env
  • Usa un dominio verificado en lugar de Gmail/Outlook
  • Evita palabras spam en el asunto y contenido

Error: "No such file or directory: 'data/recipients.xlsx'"

python generate_dummy_data.py

O crea manualmente la carpeta data/ y el archivo Excel.

Mejores Prácticas

  1. Siempre usa --dry-run primero para verificar que todo funciona
  2. Mantén backups del archivo de destinatarios
  3. Monitorea el archivo de log durante envíos masivos
  4. Respeta los límites de envío de tu proveedor SMTP
  5. Personaliza los mensajes para mejor tasa de apertura
  6. Incluye opción de desuscripción para cumplir con GDPR/CAN-SPAM
  7. Verifica los correos antes de enviar (sintaxis, dominios válidos)
  8. Usa plantillas responsivas para móviles y desktop

Seguridad

  • NUNCA subas el archivo .env al repositorio (está en .gitignore)
  • Usa contraseñas de aplicación en lugar de tu contraseña principal
  • Limita el acceso al archivo de log (puede contener información sensible)
  • Considera encriptar el archivo Excel con destinatarios

Contribuir

Las contribuciones son bienvenidas. Por favor:

  1. Fork del proyecto
  2. Crea una rama para tu feature (git checkout -b feature/AmazingFeature)
  3. Commit de tus cambios (git commit -m 'Add some AmazingFeature')
  4. Push a la rama (git push origin feature/AmazingFeature)
  5. Abre un Pull Request

Licencia

Este proyecto es de uso interno. Todos los derechos reservados.

Dependencias

  • pandas: Manipulación de datos Excel
  • openpyxl: Lectura/escritura de archivos Excel
  • jinja2: Motor de plantillas HTML
  • python-dotenv: Gestión de variables de entorno

Changelog

v1.0.0 (2026-01-26)

  • Sistema inicial de envío masivo de correos
  • Soporte para plantillas HTML personalizables
  • Control de tasa de envío
  • Registro de correos enviados
  • Modo dry-run para pruebas
  • Plantillas de invitación y reactivación

FAQ

¿Cuántos correos puedo enviar por día? Depende de tu proveedor SMTP:

  • Gmail: ~500/día
  • Outlook: ~300/día
  • SendGrid/AWS SES: Según tu plan

¿Puedo usar otros proveedores SMTP? Sí, solo configura SMTP_SERVER, SMTP_PORT y credenciales en .env

¿Cómo agrego adjuntos? Modifica smtp_sender.py para incluir adjuntos usando MIMEBase

¿Funciona con servidores SMTP personalizados? Sí, configura los parámetros SMTP de tu servidor en .env

¿Puedo enviar en formato texto plano? Sí, modifica EmailContent para incluir body_text y ajusta smtp_sender.py

Roadmap

  • Soporte para adjuntos
  • Panel web para gestión de campañas
  • Estadísticas de apertura y clics
  • Integración con CRM
  • Programación de envíos
  • A/B testing de plantillas
  • Validación de emails antes de enviar
  • Soporte para múltiples idiomas

About

Sistema para Envios de Correos Masivos con Rate Limiter / System for Sending Mass Emails with Rate Limiter

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages