or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

templates-personalization.mddocs/

0

# Templates and Personalization

1

2

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.

3

4

## Capabilities

5

6

### Dynamic Templates

7

8

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

9

10

```python { .api }

11

# EmailMessage template attributes

12

msg.template_id = str # SendGrid template ID (e.g., "d-abc123def456")

13

msg.dynamic_template_data = dict # Template variables (SendGrid v6+)

14

msg.substitutions = dict # Template substitutions (SendGrid v5)

15

```

16

17

#### Template Usage Examples

18

19

Basic template with dynamic data:

20

21

```python

22

from django.core.mail import EmailMessage

23

24

msg = EmailMessage(

25

from_email='sender@example.com',

26

to=['recipient@example.com'],

27

)

28

29

# Set template ID and variables

30

msg.template_id = "d-abc123def456789"

31

msg.dynamic_template_data = {

32

"first_name": "John",

33

"product_name": "Premium Widget",

34

"order_total": "$99.99",

35

"shipping_date": "March 15, 2024"

36

}

37

38

msg.send()

39

```

40

41

Template with conditional content:

42

43

```python

44

msg = EmailMessage(

45

from_email='store@example.com',

46

to=['customer@example.com'],

47

)

48

49

msg.template_id = "d-welcome-template"

50

msg.dynamic_template_data = {

51

"user": {

52

"name": "Jane Doe",

53

"email": "jane@example.com",

54

"is_premium": True,

55

"join_date": "2024-01-15"

56

},

57

"features": [

58

{"name": "Premium Support", "available": True},

59

{"name": "Advanced Analytics", "available": True}

60

]

61

}

62

63

msg.send()

64

```

65

66

### Personalization Objects

67

68

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

69

70

```python { .api }

71

# EmailMessage personalization attributes

72

msg.personalizations = list # List of Personalization objects or dicts

73

msg.make_private = bool # Send individual emails to each recipient

74

msg.custom_args = dict # Custom tracking arguments

75

```

76

77

#### Personalization Examples

78

79

Individual personalization for multiple recipients:

80

81

```python

82

from sendgrid.helpers.mail import Personalization, Email

83

84

msg = EmailMessage(

85

subject='Personalized Newsletter',

86

from_email='newsletter@example.com',

87

)

88

89

# Create personalization for each recipient

90

personalizations = []

91

92

# First recipient

93

p1 = Personalization()

94

p1.add_to(Email("john@example.com", "John Doe"))

95

p1.dynamic_template_data = {

96

"name": "John",

97

"interests": ["technology", "sports"],

98

"recommended_products": ["laptop", "headphones"]

99

}

100

personalizations.append(p1)

101

102

# Second recipient

103

p2 = Personalization()

104

p2.add_to(Email("jane@example.com", "Jane Smith"))

105

p2.dynamic_template_data = {

106

"name": "Jane",

107

"interests": ["books", "travel"],

108

"recommended_products": ["kindle", "luggage"]

109

}

110

personalizations.append(p2)

111

112

# Apply personalizations

113

msg.personalizations = personalizations

114

msg.template_id = "d-personalized-newsletter"

115

msg.send()

116

```

117

118

Using dictionary format for personalization:

119

120

```python

121

msg = EmailMessage(

122

from_email='sales@example.com',

123

)

124

125

# Dictionary format personalizations

126

msg.personalizations = [

127

{

128

"to": [{"email": "buyer1@example.com", "name": "Alice Johnson"}],

129

"dynamic_template_data": {

130

"purchase_history": ["Widget A", "Widget B"],

131

"discount_code": "ALICE20"

132

},

133

"custom_args": {"customer_segment": "premium"}

134

},

135

{

136

"to": [{"email": "buyer2@example.com", "name": "Bob Wilson"}],

137

"dynamic_template_data": {

138

"purchase_history": ["Basic Plan"],

139

"discount_code": "BOB10"

140

},

141

"custom_args": {"customer_segment": "standard"}

142

}

143

]

144

145

msg.template_id = "d-targeted-offer"

146

msg.send()

147

```

148

149

### Private Messaging

150

151

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

152

153

```python { .api }

154

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

155

```

156

157

#### Private Messaging Example

158

159

```python

160

msg = EmailMessage(

161

subject='Your Personal Report',

162

from_email='reports@example.com',

163

to=['user1@example.com', 'user2@example.com', 'user3@example.com'],

164

)

165

166

# Each recipient gets individual email (addresses hidden from others)

167

msg.make_private = True

168

169

# Custom arguments for tracking

170

msg.custom_args = {

171

"campaign_id": "quarterly_report_2024_q1",

172

"email_type": "automated_report"

173

}

174

175

msg.send()

176

```

177

178

### Custom Arguments

179

180

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

181

182

```python { .api }

183

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

184

```

185

186

#### Custom Arguments Examples

187

188

Marketing campaign tracking:

189

190

```python

191

msg = EmailMessage(

192

subject='Special Promotion',

193

body='Check out our latest offers!',

194

from_email='marketing@example.com',

195

to=['customer@example.com'],

196

)

197

198

msg.custom_args = {

199

"campaign_name": "spring_sale_2024",

200

"user_segment": "high_value_customer",

201

"email_version": "A", # For A/B testing

202

"trigger_event": "cart_abandonment"

203

}

204

205

msg.send()

206

```

207

208

### Version Compatibility

209

210

The package handles differences between SendGrid API versions automatically:

211

212

#### SendGrid v5 (Legacy)

213

- Uses `substitutions` for template variables

214

- Limited personalization features

215

- String-based API parameters

216

217

#### SendGrid v6 (Current)

218

- Uses `dynamic_template_data` for template variables

219

- Full personalization object support

220

- Enhanced type safety and validation

221

222

```python

223

# The backend automatically detects version and uses appropriate method

224

if SENDGRID_6:

225

# Uses dynamic_template_data

226

personalization.dynamic_template_data = template_vars

227

else:

228

# Uses substitutions

229

for key, value in template_vars.items():

230

personalization.add_substitution(Substitution(key, value))

231

```

232

233

### Advanced Personalization Patterns

234

235

Conditional content based on recipient data:

236

237

```python

238

def create_personalized_email(recipient_data):

239

msg = EmailMessage(

240

from_email='system@example.com',

241

to=[recipient_data['email']],

242

)

243

244

# Determine template based on user type

245

if recipient_data['is_premium']:

246

msg.template_id = "d-premium-template"

247

template_data = {

248

"premium_features": recipient_data['features'],

249

"support_level": "Priority"

250

}

251

else:

252

msg.template_id = "d-standard-template"

253

template_data = {

254

"upgrade_offer": True,

255

"support_level": "Standard"

256

}

257

258

# Add common personalization

259

template_data.update({

260

"user_name": recipient_data['name'],

261

"account_status": recipient_data['status'],

262

"last_login": recipient_data['last_activity']

263

})

264

265

msg.dynamic_template_data = template_data

266

return msg

267

268

# Send personalized emails

269

recipients = get_user_list()

270

for user in recipients:

271

email = create_personalized_email(user)

272

email.send()

273

```