CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-sendgrid-v5

Django email backend implementation compatible with SendGrid API v5+ for seamless email delivery integration

Pending
Overview
Eval results
Files

templates-personalization.mddocs/

Templates and Personalization

SendGrid's dynamic template system and personalization features enable customized email content for individual recipients. This includes template variable substitution, dynamic content generation, and advanced personalization patterns.

Capabilities

Dynamic Templates

Use SendGrid's dynamic transactional templates with variable substitution and conditional content.

# EmailMessage template attributes
msg.template_id = str  # SendGrid template ID (e.g., "d-abc123def456")
msg.dynamic_template_data = dict  # Template variables (SendGrid v6+)
msg.substitutions = dict  # Template substitutions (SendGrid v5)

Template Usage Examples

Basic template with dynamic data:

from django.core.mail import EmailMessage

msg = EmailMessage(
    from_email='sender@example.com',
    to=['recipient@example.com'],
)

# Set template ID and variables
msg.template_id = "d-abc123def456789"
msg.dynamic_template_data = {
    "first_name": "John",
    "product_name": "Premium Widget",
    "order_total": "$99.99",
    "shipping_date": "March 15, 2024"
}

msg.send()

Template with conditional content:

msg = EmailMessage(
    from_email='store@example.com',
    to=['customer@example.com'],
)

msg.template_id = "d-welcome-template"
msg.dynamic_template_data = {
    "user": {
        "name": "Jane Doe",
        "email": "jane@example.com",
        "is_premium": True,
        "join_date": "2024-01-15"
    },
    "features": [
        {"name": "Premium Support", "available": True},
        {"name": "Advanced Analytics", "available": True}
    ]
}

msg.send()

Personalization Objects

Advanced personalization using SendGrid's Personalization objects for fine-grained control over individual recipients.

# EmailMessage personalization attributes
msg.personalizations = list  # List of Personalization objects or dicts
msg.make_private = bool  # Send individual emails to each recipient
msg.custom_args = dict  # Custom tracking arguments

Personalization Examples

Individual personalization for multiple recipients:

from sendgrid.helpers.mail import Personalization, Email

msg = EmailMessage(
    subject='Personalized Newsletter',
    from_email='newsletter@example.com',
)

# Create personalization for each recipient
personalizations = []

# First recipient
p1 = Personalization()
p1.add_to(Email("john@example.com", "John Doe"))
p1.dynamic_template_data = {
    "name": "John",
    "interests": ["technology", "sports"],
    "recommended_products": ["laptop", "headphones"]
}
personalizations.append(p1)

# Second recipient  
p2 = Personalization()
p2.add_to(Email("jane@example.com", "Jane Smith"))
p2.dynamic_template_data = {
    "name": "Jane",
    "interests": ["books", "travel"], 
    "recommended_products": ["kindle", "luggage"]
}
personalizations.append(p2)

# Apply personalizations
msg.personalizations = personalizations
msg.template_id = "d-personalized-newsletter"
msg.send()

Using dictionary format for personalization:

msg = EmailMessage(
    from_email='sales@example.com',
)

# Dictionary format personalizations
msg.personalizations = [
    {
        "to": [{"email": "buyer1@example.com", "name": "Alice Johnson"}],
        "dynamic_template_data": {
            "purchase_history": ["Widget A", "Widget B"],
            "discount_code": "ALICE20"
        },
        "custom_args": {"customer_segment": "premium"}
    },
    {
        "to": [{"email": "buyer2@example.com", "name": "Bob Wilson"}], 
        "dynamic_template_data": {
            "purchase_history": ["Basic Plan"],
            "discount_code": "BOB10"
        },
        "custom_args": {"customer_segment": "standard"}
    }
]

msg.template_id = "d-targeted-offer"
msg.send()

Private Messaging

Send individual emails to multiple recipients to maintain privacy and enable personalization.

msg.make_private = bool  # Send separate email to each recipient

Private Messaging Example

msg = EmailMessage(
    subject='Your Personal Report',
    from_email='reports@example.com',
    to=['user1@example.com', 'user2@example.com', 'user3@example.com'],
)

# Each recipient gets individual email (addresses hidden from others)
msg.make_private = True

# Custom arguments for tracking
msg.custom_args = {
    "campaign_id": "quarterly_report_2024_q1",
    "email_type": "automated_report"
}

msg.send()

Custom Arguments

Add custom tracking arguments to emails for analytics and segmentation purposes.

msg.custom_args = dict  # Custom key-value pairs for tracking

Custom Arguments Examples

Marketing campaign tracking:

msg = EmailMessage(
    subject='Special Promotion',
    body='Check out our latest offers!',
    from_email='marketing@example.com',
    to=['customer@example.com'],
)

msg.custom_args = {
    "campaign_name": "spring_sale_2024",
    "user_segment": "high_value_customer", 
    "email_version": "A",  # For A/B testing
    "trigger_event": "cart_abandonment"
}

msg.send()

Version Compatibility

The package handles differences between SendGrid API versions automatically:

SendGrid v5 (Legacy)

  • Uses substitutions for template variables
  • Limited personalization features
  • String-based API parameters

SendGrid v6 (Current)

  • Uses dynamic_template_data for template variables
  • Full personalization object support
  • Enhanced type safety and validation
# The backend automatically detects version and uses appropriate method
if SENDGRID_6:
    # Uses dynamic_template_data
    personalization.dynamic_template_data = template_vars
else:
    # Uses substitutions  
    for key, value in template_vars.items():
        personalization.add_substitution(Substitution(key, value))

Advanced Personalization Patterns

Conditional content based on recipient data:

def create_personalized_email(recipient_data):
    msg = EmailMessage(
        from_email='system@example.com',
        to=[recipient_data['email']],
    )
    
    # Determine template based on user type
    if recipient_data['is_premium']:
        msg.template_id = "d-premium-template"
        template_data = {
            "premium_features": recipient_data['features'],
            "support_level": "Priority"
        }
    else:
        msg.template_id = "d-standard-template"  
        template_data = {
            "upgrade_offer": True,
            "support_level": "Standard"
        }
    
    # Add common personalization
    template_data.update({
        "user_name": recipient_data['name'],
        "account_status": recipient_data['status'],
        "last_login": recipient_data['last_activity']
    })
    
    msg.dynamic_template_data = template_data
    return msg

# Send personalized emails
recipients = get_user_list()
for user in recipients:
    email = create_personalized_email(user)
    email.send()

Install with Tessl CLI

npx tessl i tessl/pypi-django-sendgrid-v5

docs

configuration.md

email-backend.md

index.md

signals.md

templates-personalization.md

webhooks.md

tile.json