Install our app for a better experience!

Teacher Evaluation Email API

Teacher Evaluation Email API

The Teacher Evaluation Email API provides endpoints for sending evaluation reports via email with attachments (PDF, DOCX, CSV). This documentation covers all email-related functionality including manual sending, automatic sending, and configuration.

Table of Contents

  1. Overview
  2. Authentication
  3. API Endpoints
  4. Email Configuration
  5. Manual Email Sending
  6. Automatic Email Sending
  7. Troubleshooting
  8. Examples

Overview

The email API allows you to:

  • Send individual evaluation reports via email
  • Send batch evaluation reports via email
  • Configure automatic email settings for batches
  • Check email status and configuration
  • Include multiple attachment formats (PDF, DOCX, CSV)
  • Add custom messages to emails

Email Features

  • Multiple Formats: PDF, DOCX, and CSV attachments
  • Organization SMTP: Uses organization-specific SMTP settings when configured
  • Fallback System: Automatically falls back to system SMTP if organization SMTP fails
  • Custom Messages: Add personalized messages to emails
  • Batch Support: Send summary reports for batch evaluations
  • Logging: Comprehensive logging for debugging email delivery issues

Authentication

All email API endpoints require authentication. You must have:

  • Valid account on the platform
  • Organization membership with one of these roles:
  • Admin - Full organization access
  • Examiner - Can create evaluations and send emails
  • Super Admin - Platform-wide access
  • Active membership status

Note: If you don't have the required membership, contact your organization administrator.

Authentication Methods

  1. Token Authentication (recommended for API integration)
  2. Session Authentication (for web applications)

Token Authentication Example:

# First, get your token
curl -X POST https://preparebuddy.com/assessment/api/auth/token/ \
  -H "Content-Type: application/json" \
  -d '{"username": "your_username", "password": "your_password"}'

# Response includes token
# {"success": true, "token": "abc123...", ...}

# Then use the token
curl -X POST https://preparebuddy.com/assessment/api/batches/19/email/ \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer abc123..." \
  -d '{"teacher_name": "John Smith", "teacher_email": "teacher@school.edu"}'

Session Authentication Example:

# After logging in via web interface
curl -X POST https://preparebuddy.com/assessment/api/batches/19/email/ \
  -H "Content-Type: application/json" \
  -H "Cookie: sessionid=your_session_id" \
  -d '{"teacher_name": "John Smith", "teacher_email": "teacher@school.edu"}'

API Endpoints

Base URL

https://www.preparebuddy.com/assessment/api/

Endpoint Summary

Endpoint Method Description
/evaluations/{id}/email/ POST Send individual evaluation email
/batches/{id}/email/ POST Send batch evaluation email
/batches/{id}/email/configure/ POST Configure batch auto-email settings
/batches/{id}/email/status/ GET Get batch email status

1. Send Individual Evaluation Email

Send an email with individual evaluation report.

Endpoint: POST /evaluations/{evaluation_id}/email/

Request Body

{
  "teacher_name": "John Smith",
  "teacher_email": "teacher@school.edu",
  "include_pdf": true,
  "include_docx": true,
  "include_csv": false,
  "additional_message": "Please review your evaluation results."
}

Parameters

Parameter Type Required Default Description
teacher_name string Yes - Full name of the teacher
teacher_email string Yes - Valid email address
include_pdf boolean No true Include PDF attachment
include_docx boolean No true Include DOCX attachment
include_csv boolean No false Include CSV attachment
additional_message string No "" Custom message to include

Response

{
  "success": true,
  "message": "Email sent successfully",
  "email_details": {
    "recipient": "teacher@school.edu",
    "teacher_name": "John Smith",
    "attachments": ["PDF", "DOCX"],
    "sent_at": "2025-07-11T12:00:00Z",
    "evaluation_id": 123,
    "report_type": "Individual Evaluation"
  }
}

Example Request

curl -X POST https://www.preparebuddy.com/assessment/api/evaluations/123/email/ \
  -H "Content-Type: application/json" \
  -H "Cookie: sessionid=your_session_id" \
  -d '{
    "teacher_name": "John Smith",
    "teacher_email": "john.smith@school.edu",
    "include_pdf": true,
    "include_docx": true,
    "include_csv": false,
    "additional_message": "Here is your detailed evaluation report. Please review the feedback and recommendations."
  }'

2. Send Batch Evaluation Email

Send an email with batch evaluation summary report.

Endpoint: POST /batches/{batch_id}/email/

Request Body

{
  "teacher_name": "John Smith", 
  "teacher_email": "teacher@school.edu",
  "include_pdf": true,
  "include_docx": true,
  "include_csv": false,
  "additional_message": "Please review your batch evaluation results."
}

Parameters

Same as individual evaluation endpoint.

Response

{
  "success": true,
  "message": "Email sent successfully",
  "email_details": {
    "recipient": "teacher@school.edu",
    "teacher_name": "John Smith",
    "attachments": ["PDF", "DOCX"],
    "sent_at": "2025-07-11T12:00:00Z",
    "batch_id": 19,
    "report_type": "Batch Evaluation",
    "batch_summary": {
      "batch_name": "Spring 2025 Evaluations",
      "total_feedbacks": 5,
      "average_score": 48.9,
      "total_possible_score": 60
    }
  }
}

Example Request

curl -X POST https://www.preparebuddy.com/assessment/api/batches/19/email/ \
  -H "Content-Type: application/json" \
  -H "Cookie: sessionid=your_session_id" \
  -d '{
    "teacher_name": "Sarah Johnson",
    "teacher_email": "sarah.johnson@university.edu",
    "include_pdf": true,
    "include_docx": true,
    "include_csv": true,
    "additional_message": "Your batch evaluation for Spring 2025 has been completed. This report includes analysis of 5 feedback submissions."
  }'

3. Configure Batch Auto-Email

Configure automatic email settings for a batch evaluation.

Endpoint: POST /batches/{batch_id}/email/configure/

Request Body

{
  "send_email_on_completion": true,
  "manual_email_recipient": "teacher@school.edu",
  "email_format_preferences": "pdf_docx",
  "email_message": "Your evaluation has been completed."
}

Parameters

Parameter Type Required Description
send_email_on_completion boolean No Enable auto-email when batch completes
manual_email_recipient string No Override email address for manual cases
email_format_preferences string No Format preference: pdf_only, docx_only, pdf_docx, all_formats
email_message string No Default message for auto-emails

Response

{
  "success": true,
  "message": "Email configuration updated",
  "configuration": {
    "send_email_on_completion": true,
    "manual_email_recipient": "teacher@school.edu",
    "email_format_preferences": "pdf_docx",
    "email_message": "Your evaluation has been completed.",
    "format_description": "PDF and Word Document"
  }
}

4. Get Batch Email Status

Get current email configuration and status for a batch.

Endpoint: GET /batches/{batch_id}/email/status/

Response

{
  "batch_id": 19,
  "batch_name": "Spring 2025 Evaluations",
  "email_configuration": {
    "send_email_on_completion": true,
    "manual_email_recipient": "teacher@school.edu",
    "email_format_preferences": "pdf_docx",
    "email_message": "Your evaluation has been completed."
  },
  "status": {
    "batch_completed": true,
    "auto_email_sent": true,
    "last_email_sent": "2025-07-11T10:30:00Z"
  }
}

Email Configuration

Organization SMTP Settings

If your organization has configured SMTP settings, emails will be sent using your organization's email server. Otherwise, the system will use the default PrepareBuddy SMTP.

SMTP Configuration Fields

  • SMTP Host: Mail server hostname
  • SMTP Port: Usually 587 (TLS) or 465 (SSL)
  • Username: SMTP authentication username
  • Password: SMTP authentication password
  • Use SSL/TLS: Encryption settings
  • From Name: Display name in emails
  • From Email: Reply-to email address

Email Format Preferences

Configure which attachments to include by default:

  • pdf_only: PDF format only
  • docx_only: Word document only
  • pdf_docx: PDF and Word document (default)
  • all_formats: PDF, Word document, and CSV

Manual Email Sending

Using the Web Interface

  1. Navigate to the evaluation or batch details page
  2. Click the "Email Report" button
  3. Fill in the recipient details:
  4. Teacher name
  5. Email address
  6. Select attachment formats
  7. Add custom message (optional)
  8. Click "Send Email"

Using the API

Use the individual or batch email endpoints described above.


Automatic Email Sending

Batch-Level Configuration

Configure automatic emails when creating or editing a batch:

  1. Enable Auto-Email: Check "Send email on completion"
  2. Format Preferences: Select default attachment formats
  3. Manual Recipient: Add fallback email for cases where teacher email is not available
  4. Default Message: Set a standard message for auto-emails

Auto-Email via API Workflow

When using the API, automatic email delivery integrates seamlessly with the batch evaluation workflow. This section explains how to configure and use auto-email programmatically.

How It Works

  1. Create Batch: Upload feedbacks and create batch evaluation via API
  2. Configure Auto-Email: Use /batches/{id}/email/configure/ to enable auto-email
  3. Run Evaluation: Call /batches/{id}/run/ - this endpoint blocks until completion
  4. Automatic Email: Email is sent automatically before the API endpoint returns

Important: Synchronous Processing

⚠️ The /api/batches/{id}/run/ endpoint processes evaluations synchronously (typically 1-3 minutes). When send_email_on_completion is enabled:

  • The endpoint blocks until all evaluations are complete
  • Email is sent automatically before the response is returned
  • You receive confirmation that email was sent in the response

This ensures you know the email was sent before your API call completes.

Complete API Workflow Example

import requests

# Step 1: Authenticate
auth_response = requests.post(
    "https://your-domain.com/api/auth/token/",
    json={"username": "teacher", "password": "pass123"}
)
token = auth_response.json()['session_key']
headers = {"Authorization": f"Bearer {token}"}

# Step 2: Upload feedbacks
feedbacks_response = requests.post(
    "https://your-domain.com/api/feedbacks/bulk/",
    headers=headers,
    json={
        "organization_id": 1,
        "feedbacks": [
            {
                "title": "Math Feedback",
                "feedback_content": "Student demonstrates excellent understanding...",
                "assessment_type": "assignment",
                "teacher_name": "John Smith"
            }
        ]
    }
)
feedback_ids = [f['id'] for f in feedbacks_response.json()['feedbacks']]

# Step 3: Create batch with RAG
batch_response = requests.post(
    "https://your-domain.com/api/batches/create/",
    headers=headers,
    json={
        "name": "Q1 2025 Teacher Evaluations",
        "rubric_id": 5,
        "organization_id": 1,
        "feedback_ids": feedback_ids,
        "use_reference_matching": True,
        "reference_matching_mode": "dynamic",
        "reference_detail_level": "detailed",
        "max_references": 5
    }
)
batch_id = batch_response.json()['batch']['id']

# Step 4: Configure auto-email
email_config_response = requests.post(
    f"https://your-domain.com/api/batches/{batch_id}/email/configure/",
    headers=headers,
    json={
        "send_email_on_completion": True,
        "manual_email_recipient": "teacher@school.edu",
        "email_format_preferences": "pdf_docx",
        "email_message": "Your evaluation is complete. Please review the attached reports."
    }
)
print(f"✓ Auto-email configured: {email_config_response.json()['configuration']}")

# Step 5: Run evaluation (blocks until complete, email sent automatically)
print("Running evaluation... (this may take 1-3 minutes)")
run_response = requests.post(
    f"https://your-domain.com/api/batches/{batch_id}/run/",
    headers=headers
)
result = run_response.json()
print(f"✓ Evaluation completed: {result['status']}")
print("✓ Email sent automatically before this response was returned")

# Step 6: Verify email was sent
status_response = requests.get(
    f"https://your-domain.com/api/batches/{batch_id}/email/status/",
    headers=headers
)
status = status_response.json()
print(f"✓ Auto-email sent: {status['status']['auto_email_sent']}")
print(f"✓ Sent at: {status['status']['last_email_sent']}")

API Endpoints for Auto-Email

Configure Auto-Email:

POST /api/batches/{batch_id}/email/configure/
Content-Type: application/json
Authorization: Bearer {token}

{
  "send_email_on_completion": true,
  "manual_email_recipient": "teacher@school.edu",
  "email_format_preferences": "pdf_docx",
  "email_message": "Your evaluation has been completed."
}

Run Evaluation (with auto-email):

POST /api/batches/{batch_id}/run/
Authorization: Bearer {token}

# Response (after email is sent):
{
  "message": "Evaluation completed successfully",
  "batch_id": 50,
  "status": "completed"
}

Check Email Status:

GET /api/batches/{batch_id}/email/status/
Authorization: Bearer {token}

# Response:
{
  "email_configuration": {
    "send_email_on_completion": true,
    "email_format_preferences": "pdf_docx"
  },
  "status": {
    "auto_email_sent": true,
    "last_email_sent": "2025-01-15T10:35:00Z"
  }
}

Email Format Preferences

When configuring auto-email, you can specify which attachments to include:

Preference Attachments Included
pdf_only PDF report only
docx_only Word document only
pdf_docx PDF + Word (recommended)
all_formats PDF + Word + CSV

Best Practices

  1. Always configure auto-email before running evaluation - You cannot configure it after evaluation completes
  2. Use pdf_docx format - Provides flexibility for recipients
  3. Add custom message - Personalize the email for better context
  4. Handle errors gracefully - Check response status and handle email failures
  5. Verify email status - Use /email/status/ endpoint to confirm delivery

Error Handling

try:
    # Run evaluation with auto-email configured
    run_response = requests.post(
        f"{API_BASE}/batches/{batch_id}/run/",
        headers=headers,
        timeout=300  # 5 minute timeout for long evaluations
    )

    if run_response.status_code == 200:
        result = run_response.json()
        print(f"✓ Evaluation completed: {result['status']}")

        # Verify email was sent
        status_response = requests.get(
            f"{API_BASE}/batches/{batch_id}/email/status/",
            headers=headers
        )
        status = status_response.json()

        if status['status']['auto_email_sent']:
            print(f"✓ Email sent to: {status['email_configuration']['manual_email_recipient']}")
        else:
            print("⚠️ Warning: Email may not have been sent. Check logs.")
    else:
        print(f"✗ Evaluation failed: {run_response.json()}")

except requests.exceptions.Timeout:
    print("⚠️ Request timed out. Evaluation may still be processing.")
    print("Check batch status: GET /api/batches/{batch_id}/status/")
except requests.exceptions.RequestException as e:
    print(f"✗ Request failed: {e}")

Workflow Timing

Typical workflow timing with auto-email:

  1. Configure auto-email: < 1 second
  2. Run evaluation: 1-3 minutes (depends on feedback count)
  3. Evaluation processing: 30-120 seconds
  4. RAG matching: 5-15 seconds (if enabled)
  5. Report generation: 5-10 seconds
  6. Email sending: 2-5 seconds
  7. API response: After all above steps complete

Complete Workflow Reference

For a comprehensive guide to the complete API workflow including authentication, feedback upload, batch creation, RAG configuration, and auto-email, see:

📚 API Core Workflow Guide - Complete step-by-step workflow with examples

📚 RAG Configuration Guide - Detailed RAG parameter documentation

📚 API Usage Guide - Quick start guide with code examples

Organization-Level Settings

Configure organization-wide email preferences in the admin panel:

  • Auto-email enabled: Enable/disable automatic emails
  • Fallback behavior: What to do when teacher email is missing
  • Default message: Organization-wide default message
  • SMTP settings: Custom email server configuration

Troubleshooting

Common Issues

1. Email Not Received

Symptoms: API returns success but email not in inbox

Solutions: - Check spam/junk folder - Verify email address is correct - Check if organization SMTP is configured properly - Review server logs for delivery issues

2. Authentication Error

Symptoms: 401 Unauthorized or 403 Forbidden

Solutions: - Ensure user is logged in - Check user has examiner privileges - Verify session cookie is valid

3. Attachment Generation Failed

Symptoms: "No attachments could be generated" error

Solutions: - Check if evaluation/batch has completed - Verify rubric and results exist - Check server permissions for file generation

Debugging

Enable detailed logging to troubleshoot email issues:

import logging
logging.getLogger('qbank.utils.email_service').setLevel(logging.INFO)
logging.getLogger('assessment.api_views_simple').setLevel(logging.INFO)

Log Messages

Look for these log patterns:

API: Starting email send for batch 19
EMAIL_SERVICE: Starting email send to user@example.com
FALLBACK_EMAIL: Using account: notification@preparebuddy.com
EMAIL_SERVICE: Email sent successfully

Examples

Example 1: Send Individual Evaluation

import requests
import json

# Authentication (assume logged in with session)
session = requests.Session()

# Send individual evaluation email
url = "https://www.preparebuddy.com/assessment/api/evaluations/123/email/"
data = {
    "teacher_name": "Dr. Alice Johnson",
    "teacher_email": "alice.johnson@university.edu",
    "include_pdf": True,
    "include_docx": True,
    "include_csv": False,
    "additional_message": "Thank you for providing detailed feedback to your students. This evaluation report shows the quality and consistency of your feedback."
}

response = session.post(url, json=data)
print(f"Status: {response.status_code}")
print(f"Response: {response.json()}")

Example 2: Send Batch Evaluation with All Formats

# Send batch evaluation with all attachment formats
url = "https://www.preparebuddy.com/assessment/api/batches/19/email/"
data = {
    "teacher_name": "Prof. Robert Smith",
    "teacher_email": "robert.smith@college.edu",
    "include_pdf": True,
    "include_docx": True,
    "include_csv": True,
    "additional_message": "Your batch evaluation for the Spring 2025 semester has been completed. This comprehensive report includes analysis of all feedback submissions and provides actionable insights for improvement."
}

response = session.post(url, json=data)
result = response.json()

if result['success']:
    print(f"Email sent successfully to {result['email_details']['recipient']}")
    print(f"Attachments: {', '.join(result['email_details']['attachments'])}")
    print(f"Batch summary: {result['email_details']['batch_summary']}")
else:
    print(f"Email failed: {result.get('error')}")

Example 3: Configure Auto-Email for Batch

# Configure automatic email settings
url = "https://www.preparebuddy.com/assessment/api/batches/19/email/configure/"
data = {
    "send_email_on_completion": True,
    "manual_email_recipient": "backup@department.edu",
    "email_format_preferences": "pdf_docx",
    "email_message": "Your teacher evaluation has been completed. Please review the attached reports and recommendations."
}

response = session.post(url, json=data)
config = response.json()

print(f"Auto-email configured: {config['configuration']}")

Example 4: Check Email Status

# Check batch email status
url = "https://www.preparebuddy.com/assessment/api/batches/19/email/status/"
response = session.get(url)
status = response.json()

print(f"Batch: {status['batch_name']}")
print(f"Auto-email enabled: {status['email_configuration']['send_email_on_completion']}")
print(f"Batch completed: {status['status']['batch_completed']}")
print(f"Auto-email sent: {status['status']['auto_email_sent']}")

Example 5: Error Handling

try:
    response = session.post(url, json=data)
    response.raise_for_status()  # Raises an HTTPError for bad responses

    result = response.json()
    if result['success']:
        print("Email sent successfully!")
        print(f"Details: {result['email_details']}")
    else:
        print(f"Email failed: {result.get('error')}")

except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
except json.JSONDecodeError:
    print("Invalid JSON response")
except KeyError as e:
    print(f"Missing expected field in response: {e}")

Rate Limiting

The email system includes built-in rate limiting:

  • Default accounts: 400 emails per day per account
  • Organization SMTP: Depends on your mail server limits
  • Automatic rotation: System rotates between multiple notification accounts

Security Considerations

  1. Authentication Required: All endpoints require valid authentication
  2. Permission Checks: Users can only send emails for evaluations they have access to
  3. Email Validation: All email addresses are validated before sending
  4. Secure SMTP: All email connections use SSL/TLS encryption
  5. Rate Limiting: Built-in protection against email abuse

Support

For additional support:

  1. Check the troubleshooting section above
  2. Review server logs for detailed error messages
  3. Verify your organization's SMTP configuration
  4. Contact your system administrator for SMTP issues

Last updated: July 11, 2025