python
59 lines · 1 tab
Priya Sharma
Jan 2026
1 tab
from django.core.mail import EmailMessage, EmailMultiAlternatives
from django.template.loader import render_to_string
from django.conf import settings
import os
def send_invoice_email(order):
"""Send invoice with PDF attachment."""
subject = f'Invoice #{order.id}'
# Render email from template
context = {'order': order, 'site_url': settings.SITE_URL}
html_content = render_to_string('emails/invoice.html', context)
text_content = render_to_string('emails/invoice.txt', context)
email = EmailMultiAlternatives(
subject=subject,
body=text_content,
from_email=settings.DEFAULT_FROM_EMAIL,
to=[order.customer.email],
cc=['accounting@example.com'],
bcc=['archive@example.com'],
)
email.attach_alternative(html_content, 'text/html')
# Attach PDF file
pdf_path = f'/tmp/invoice_{order.id}.pdf'
if os.path.exists(pdf_path):
email.attach_file(pdf_path, mimetype='application/pdf')
# Attach in-memory file
csv_data = generate_csv_data(order)
email.attach('order_items.csv', csv_data, 'text/csv')
email.send()
def send_bulk_newsletter(subscribers, subject, template_name):
"""Send newsletter to many subscribers efficiently."""
messages = []
for subscriber in subscribers:
context = {'subscriber': subscriber}
html_content = render_to_string(f'emails/{template_name}.html', context)
msg = EmailMultiAlternatives(
subject=subject,
body='Newsletter',
from_email=settings.DEFAULT_FROM_EMAIL,
to=[subscriber.email],
)
msg.attach_alternative(html_content, 'text/html')
messages.append(msg)
# Send all at once
from django.core.mail import get_connection
connection = get_connection()
connection.send_messages(messages)
1 file · python
Explain with highlit
Django's email system supports attachments and HTML templates. I use EmailMessage for full control or EmailMultiAlternatives for HTML+text versions. For attachments, I use attach_file() or attach() methods. I render email content from templates for consistency. For bulk emails, I send in batches to avoid rate limits. I use Celery for async sending. I track bounces and unsubscribes for deliverability. SMTP settings go in environment variables. This enables rich, professional emails from Django apps.
Related snips
python
import os
import stat
for root, _dirs, files in os.walk('/etc'):
for name in files:
path = os.path.join(root, name)
Python security audit script for exposed risky filesystem state
python
auditing
host-security
by Kai Nakamura
1 tab
python
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2)
cost = models.DecimalField(max_digits=10, decimal_places=2)
margin = models.DecimalField(max_digits=5, decimal_places=2, blank=True)
Django model signals vs overriding save
django
python
models
by Priya Sharma
2 tabs
python
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
Django URL namespacing and reverse lookups
django
python
urls
by Priya Sharma
3 tabs
ruby
# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
default from: 'noreply@example.com'
def welcome_email(user)
@user = user
ActionMailer advanced patterns for transactional emails
ruby
rails
action-mailer
by Sarah Mitchell
2 tabs
python
import graphene
from graphene_django import DjangoObjectType
from blog.models import Post, Comment
class PostType(DjangoObjectType):
Django GraphQL with Graphene
django
python
graphql
by Priya Sharma
2 tabs
ruby
module EmailNormalization
extend ActiveSupport::Concern
included do
attr_accessor :soft_warnings
Soft Validation: Normalize + Validate Email
rails
activerecord
validations
by codesnips
4 tabs
Share this code
Here's the card — post it anywhere.