or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdemail-backend.mdindex.mdsignals.mdtemplates-personalization.mdwebhooks.md

configuration.mddocs/

0

# Configuration

1

2

Django settings integration for configuring SendGrid API access, tracking options, sandbox mode, debugging features, and other SendGrid-specific behaviors. All configuration is handled through Django's settings system.

3

4

## Capabilities

5

6

### Required Settings

7

8

Essential configuration settings that must be provided for the backend to function.

9

10

```python { .api }

11

# Required in settings.py

12

SENDGRID_API_KEY = str # SendGrid API key for authentication

13

EMAIL_BACKEND = "sendgrid_backend.SendgridBackend" # Django email backend

14

```

15

16

#### Basic Setup Example

17

18

```python

19

# settings.py

20

import os

21

22

EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"

23

SENDGRID_API_KEY = os.environ.get("SENDGRID_API_KEY")

24

25

# Validate API key presence

26

if not SENDGRID_API_KEY:

27

raise ImproperlyConfigured("SENDGRID_API_KEY environment variable is required")

28

```

29

30

### API Configuration

31

32

Settings for SendGrid API endpoint and connection parameters.

33

34

```python { .api }

35

SENDGRID_API_KEY = str # SendGrid API key (required)

36

SENDGRID_HOST_URL = str # API endpoint URL (optional)

37

```

38

39

#### API Configuration Examples

40

41

Standard US endpoint (default):

42

43

```python

44

# settings.py

45

SENDGRID_API_KEY = "SG.your-api-key-here"

46

# SENDGRID_HOST_URL defaults to https://api.sendgrid.com

47

```

48

49

EU endpoint configuration:

50

51

```python

52

# settings.py

53

SENDGRID_API_KEY = "SG.your-eu-api-key-here"

54

SENDGRID_HOST_URL = "https://api.eu.sendgrid.com"

55

```

56

57

Multiple environment configuration:

58

59

```python

60

# settings.py

61

import os

62

63

# Different API keys per environment

64

if os.environ.get("ENVIRONMENT") == "production":

65

SENDGRID_API_KEY = os.environ["SENDGRID_PROD_API_KEY"]

66

elif os.environ.get("ENVIRONMENT") == "staging":

67

SENDGRID_API_KEY = os.environ["SENDGRID_STAGING_API_KEY"]

68

else:

69

SENDGRID_API_KEY = os.environ["SENDGRID_DEV_API_KEY"]

70

```

71

72

### Sandbox and Debug Settings

73

74

Control email delivery behavior in development and testing environments.

75

76

```python { .api }

77

SENDGRID_SANDBOX_MODE_IN_DEBUG = bool # Enable sandbox in DEBUG mode (default: True)

78

SENDGRID_ECHO_TO_STDOUT = bool # Echo emails to stdout (default: False)

79

```

80

81

#### Sandbox Configuration Examples

82

83

Development environment setup:

84

85

```python

86

# settings.py

87

DEBUG = True

88

89

# Prevent accidental email sending in development

90

SENDGRID_SANDBOX_MODE_IN_DEBUG = True # Emails won't be delivered

91

92

# Enable debug output

93

SENDGRID_ECHO_TO_STDOUT = True # Print emails to console

94

```

95

96

Production environment setup:

97

98

```python

99

# settings.py

100

DEBUG = False

101

102

# Ensure emails are delivered in production

103

SENDGRID_SANDBOX_MODE_IN_DEBUG = False # Not used when DEBUG=False anyway

104

105

# Disable debug output

106

SENDGRID_ECHO_TO_STDOUT = False

107

```

108

109

Testing environment setup:

110

111

```python

112

# test_settings.py

113

DEBUG = True

114

115

# Force sandbox mode for tests

116

SENDGRID_SANDBOX_MODE_IN_DEBUG = True

117

118

# Capture email output for testing

119

SENDGRID_ECHO_TO_STDOUT = True

120

```

121

122

### Tracking Settings

123

124

Configure email open and click tracking behavior for all emails sent through the backend.

125

126

```python { .api }

127

SENDGRID_TRACK_EMAIL_OPENS = bool # Track email opens (default: True)

128

SENDGRID_TRACK_CLICKS_HTML = bool # Track clicks in HTML content (default: True)

129

SENDGRID_TRACK_CLICKS_PLAIN = bool # Track clicks in plain text (default: True)

130

```

131

132

#### Tracking Configuration Examples

133

134

Full tracking enabled (default):

135

136

```python

137

# settings.py

138

SENDGRID_TRACK_EMAIL_OPENS = True

139

SENDGRID_TRACK_CLICKS_HTML = True

140

SENDGRID_TRACK_CLICKS_PLAIN = True

141

```

142

143

Privacy-focused configuration:

144

145

```python

146

# settings.py - Minimal tracking for privacy compliance

147

SENDGRID_TRACK_EMAIL_OPENS = False

148

SENDGRID_TRACK_CLICKS_HTML = False

149

SENDGRID_TRACK_CLICKS_PLAIN = False

150

```

151

152

Selective tracking configuration:

153

154

```python

155

# settings.py - Track opens but not clicks

156

SENDGRID_TRACK_EMAIL_OPENS = True

157

SENDGRID_TRACK_CLICKS_HTML = False

158

SENDGRID_TRACK_CLICKS_PLAIN = False

159

```

160

161

### Webhook Configuration

162

163

Settings for webhook signature verification and event processing.

164

165

```python { .api }

166

SENDGRID_WEBHOOK_VERIFICATION_KEY = str # Webhook signature verification key

167

```

168

169

#### Webhook Configuration Example

170

171

```python

172

# settings.py

173

SENDGRID_WEBHOOK_VERIFICATION_KEY = os.environ.get("SENDGRID_WEBHOOK_KEY")

174

175

# Webhook endpoint configuration

176

WEBHOOK_ENDPOINTS = {

177

'sendgrid_events': '/webhooks/sendgrid/events/',

178

'sendgrid_inbound': '/webhooks/sendgrid/inbound/',

179

}

180

```

181

182

### Runtime Configuration Override

183

184

Backend initialization parameters that can override Django settings at runtime.

185

186

```python { .api }

187

# SendgridBackend.__init__() parameters

188

api_key = str # Override SENDGRID_API_KEY

189

host = str # Override SENDGRID_HOST_URL

190

stream = io.TextIOBase # Custom output stream for echoing

191

fail_silently = bool # Error handling behavior

192

```

193

194

#### Runtime Override Examples

195

196

Custom backend instance:

197

198

```python

199

from sendgrid_backend import SendgridBackend

200

import sys

201

202

# Override settings for specific use case

203

custom_backend = SendgridBackend(

204

api_key="different-api-key",

205

host="https://api.eu.sendgrid.com",

206

stream=sys.stderr, # Custom output stream

207

fail_silently=True

208

)

209

210

# Use custom backend

211

messages = [EmailMessage(...)]

212

sent_count = custom_backend.send_messages(messages)

213

```

214

215

### Configuration Validation

216

217

The backend performs automatic validation of configuration settings.

218

219

```python { .api }

220

# Validation errors raised

221

ImproperlyConfigured # Missing or invalid required settings

222

ValueError # Invalid parameter values (e.g., ip_pool_name length)

223

```

224

225

#### Configuration Validation Examples

226

227

API key validation:

228

229

```python

230

# Will raise ImproperlyConfigured if no API key provided

231

try:

232

backend = SendgridBackend()

233

except ImproperlyConfigured as e:

234

print("SendGrid configuration error:", e)

235

# Handle missing API key

236

```

237

238

Parameter validation:

239

240

```python

241

from django.core.mail import EmailMessage

242

243

msg = EmailMessage(from_email="test@example.com", to=["recipient@example.com"])

244

245

# Invalid IP pool name (too short)

246

msg.ip_pool_name = "x" # Must be 2-64 characters

247

248

try:

249

msg.send()

250

except ValueError as e:

251

print("Invalid IP pool name:", e)

252

```

253

254

### Environment-Specific Configuration

255

256

Best practices for managing configuration across different environments.

257

258

```python

259

# base_settings.py

260

EMAIL_BACKEND = "sendgrid_backend.SendgridBackend"

261

262

# Default tracking settings

263

SENDGRID_TRACK_EMAIL_OPENS = True

264

SENDGRID_TRACK_CLICKS_HTML = True

265

SENDGRID_TRACK_CLICKS_PLAIN = True

266

267

# development_settings.py

268

from .base_settings import *

269

270

DEBUG = True

271

SENDGRID_API_KEY = os.environ.get("SENDGRID_DEV_API_KEY")

272

SENDGRID_SANDBOX_MODE_IN_DEBUG = True

273

SENDGRID_ECHO_TO_STDOUT = True

274

275

# production_settings.py

276

from .base_settings import *

277

278

DEBUG = False

279

SENDGRID_API_KEY = os.environ.get("SENDGRID_PROD_API_KEY")

280

SENDGRID_HOST_URL = "https://api.eu.sendgrid.com" # EU compliance

281

282

# Disable debug features

283

SENDGRID_ECHO_TO_STDOUT = False

284

285

# testing_settings.py

286

from .base_settings import *

287

288

DEBUG = True

289

SENDGRID_API_KEY = "test-key" # Fake key for testing

290

SENDGRID_SANDBOX_MODE_IN_DEBUG = True

291

292

# Capture output for test assertions

293

SENDGRID_ECHO_TO_STDOUT = True

294

```

295

296

### Configuration Utilities

297

298

Helper functions for working with Django settings in the context of SendGrid configuration.

299

300

```python { .api }

301

def get_django_setting(setting_str, default=None):

302

"""

303

Safely retrieve Django setting with fallback default.

304

305

Parameters:

306

- setting_str (str): Name of Django setting

307

- default: Default value if setting not found

308

309

Returns:

310

Setting value or default

311

"""

312

```

313

314

#### Utility Usage Example

315

316

```python

317

from sendgrid_backend.util import get_django_setting

318

319

# Safe setting retrieval with defaults

320

sandbox_mode = get_django_setting("SENDGRID_SANDBOX_MODE_IN_DEBUG", True)

321

track_opens = get_django_setting("SENDGRID_TRACK_EMAIL_OPENS", True)

322

api_timeout = get_django_setting("SENDGRID_API_TIMEOUT", 30)

323

324

# Use in custom configuration logic

325

if get_django_setting("CUSTOM_EMAIL_THROTTLING", False):

326

# Apply custom rate limiting

327

pass

328

```

329

330

### Version Detection Constants

331

332

Constants for detecting SendGrid API version compatibility.

333

334

```python { .api }

335

# Available from sendgrid_backend.util

336

SENDGRID_VERSION: str # SendGrid package version string

337

SENDGRID_5: bool # True if using SendGrid v5.x

338

SENDGRID_6: bool # True if using SendGrid v6.x

339

```

340

341

#### Version Constants Usage

342

343

```python

344

from sendgrid_backend.util import SENDGRID_5, SENDGRID_6, SENDGRID_VERSION

345

346

# Check SendGrid version for compatibility

347

if SENDGRID_6:

348

# Use v6-specific features like dynamic_template_data

349

msg.dynamic_template_data = {"name": "John"}

350

else:

351

# Use v5-compatible substitutions

352

msg.substitutions = {"name": "John"}

353

354

# Log version information

355

print(f"Using SendGrid version: {SENDGRID_VERSION}")

356

```

357

358

### Personalization Utilities

359

360

Utility function for converting dictionary data to SendGrid Personalization objects.

361

362

```python { .api }

363

def dict_to_personalization(data: dict) -> Personalization:

364

"""

365

Convert dictionary to SendGrid Personalization object.

366

367

Reverses Sendgrid's Personalization.get() method to create a

368

Personalization object from its emitted data structure.

369

370

Parameters:

371

- data (dict): Dictionary containing personalization data

372

373

Returns:

374

- Personalization: SendGrid Personalization object

375

"""

376

```

377

378

#### Personalization Utility Usage

379

380

```python

381

from sendgrid_backend.util import dict_to_personalization

382

383

# Convert dictionary to Personalization object

384

personalization_data = {

385

"to": [{"email": "user@example.com", "name": "User"}],

386

"dynamic_template_data": {"name": "John", "product": "Widget"},

387

"custom_args": {"campaign": "spring_sale"}

388

}

389

390

personalization = dict_to_personalization(personalization_data)

391

392

# Use in EmailMessage

393

msg = EmailMessage(from_email="sender@example.com")

394

msg.personalizations = [personalization]

395

msg.send()

396

```