or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-delivery.mdattachments-content.mdemail-service.mdindex.mdmessage-construction.mdtemplates-personalization.mdtracking-analytics.md

message-construction.mddocs/

0

# Message Construction

1

2

Message construction provides fine-grained control over email building using the Mail class from @sendgrid/helpers. This allows for complex email structures with multiple content types, recipients, attachments, and advanced settings.

3

4

## Capabilities

5

6

### Mail Class Creation

7

8

Create and initialize Mail instances for building complex email messages.

9

10

```javascript { .api }

11

const { Mail } = require('@sendgrid/helpers').classes;

12

13

/**

14

* Create a Mail instance

15

* @param data - Optional initial mail data

16

*/

17

const mail = new Mail(data);

18

19

/**

20

* Create Mail instance from data (static factory method)

21

* @param data - Mail data object, array, or existing Mail instance

22

* @returns Mail instance or array of Mail instances

23

*/

24

const mail = Mail.create(data);

25

26

/**

27

* Populate Mail instance from data object

28

* @param data - Mail data to populate the instance

29

*/

30

mail.fromData(data);

31

32

/**

33

* Convert Mail instance to JSON format for SendGrid API

34

* @returns JSON representation of the email

35

*/

36

const jsonData = mail.toJSON();

37

```

38

39

**Usage Examples:**

40

41

```javascript

42

const { Mail } = require('@sendgrid/helpers').classes;

43

44

// Create empty mail instance

45

const mail = new Mail();

46

47

// Create mail with initial data

48

const mail = new Mail({

49

from: 'sender@example.com',

50

to: 'recipient@example.com',

51

subject: 'Hello World',

52

text: 'Hello from SendGrid!'

53

});

54

55

// Factory method

56

const mail = Mail.create({

57

from: 'sender@example.com',

58

to: 'recipient@example.com',

59

subject: 'Factory Created',

60

html: '<h1>Created with factory method</h1>'

61

});

62

63

// Create multiple mail instances

64

const mails = Mail.create([

65

{ from: 'sender@example.com', to: 'user1@example.com', subject: 'Message 1' },

66

{ from: 'sender@example.com', to: 'user2@example.com', subject: 'Message 2' }

67

]);

68

```

69

70

### Core Message Properties

71

72

Set fundamental email properties like sender, subject, and delivery timing.

73

74

```javascript { .api }

75

/**

76

* Set the sender email address

77

* @param from - Email address string or object with name and email

78

*/

79

mail.setFrom(from);

80

81

/**

82

* Set the email subject line

83

* @param subject - Subject text

84

*/

85

mail.setSubject(subject);

86

87

/**

88

* Set reply-to email address

89

* @param replyTo - Reply-to email address

90

*/

91

mail.setReplyTo(replyTo);

92

93

/**

94

* Set scheduled send time

95

* @param sendAt - Unix timestamp for when to send the email

96

*/

97

mail.setSendAt(sendAt);

98

99

/**

100

* Set reply-to list for multiple reply addresses

101

* @param replyToList - Array of email address objects

102

*/

103

mail.setReplyToList(replyToList);

104

```

105

106

**Usage Examples:**

107

108

```javascript

109

// Basic sender and subject

110

mail.setFrom('noreply@example.com');

111

mail.setSubject('Important Update');

112

113

// Sender with display name

114

mail.setFrom({ email: 'support@example.com', name: 'Support Team' });

115

116

// Reply-to different from sender

117

mail.setReplyTo('support@example.com');

118

119

// Schedule email for future delivery

120

const futureTime = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now

121

mail.setSendAt(futureTime);

122

123

// Multiple reply-to addresses

124

mail.setReplyToList([

125

{ email: 'support@example.com', name: 'Support' },

126

{ email: 'sales@example.com', name: 'Sales' }

127

]);

128

```

129

130

### Recipient Management

131

132

Add and manage email recipients including to, cc, and bcc addresses.

133

134

```javascript { .api }

135

/**

136

* Convenience method for adding recipients

137

* @param to - To recipients (required)

138

* @param cc - CC recipients (optional)

139

* @param bcc - BCC recipients (optional)

140

*/

141

mail.addTo(to, cc, bcc);

142

143

/**

144

* Set personalizations array for complex recipient management

145

* @param personalizations - Array of personalization objects

146

*/

147

mail.setPersonalizations(personalizations);

148

149

/**

150

* Add a single personalization

151

* @param personalization - Personalization object for specific recipients

152

*/

153

mail.addPersonalization(personalization);

154

```

155

156

**Usage Examples:**

157

158

```javascript

159

// Simple recipient

160

mail.addTo('user@example.com');

161

162

// Multiple recipients with CC and BCC

163

mail.addTo(

164

['user1@example.com', 'user2@example.com'],

165

'manager@example.com',

166

'audit@example.com'

167

);

168

169

// Complex recipient management with personalizations

170

mail.addPersonalization({

171

to: [{ email: 'john@example.com', name: 'John Doe' }],

172

subject: 'Personal message for John',

173

dynamicTemplateData: { name: 'John', account: 'Premium' }

174

});

175

176

mail.addPersonalization({

177

to: [{ email: 'jane@example.com', name: 'Jane Smith' }],

178

subject: 'Personal message for Jane',

179

dynamicTemplateData: { name: 'Jane', account: 'Basic' }

180

});

181

```

182

183

### Content Management

184

185

Manage email content including text, HTML, and multiple content types.

186

187

```javascript { .api }

188

/**

189

* Set email content array

190

* @param content - Array of content objects with type and value

191

*/

192

mail.setContent(content);

193

194

/**

195

* Add a single content item

196

* @param content - Content object with type and value

197

*/

198

mail.addContent(content);

199

200

/**

201

* Add plain text content

202

* @param text - Plain text content

203

*/

204

mail.addTextContent(text);

205

206

/**

207

* Add HTML content

208

* @param html - HTML content

209

*/

210

mail.addHtmlContent(html);

211

```

212

213

**Usage Examples:**

214

215

```javascript

216

// Add plain text content

217

mail.addTextContent('This is the plain text version of the email.');

218

219

// Add HTML content

220

mail.addHtmlContent('<h1>HTML Email</h1><p>This is the <strong>HTML</strong> version.</p>');

221

222

// Set multiple content types

223

mail.setContent([

224

{ type: 'text/plain', value: 'Plain text version' },

225

{ type: 'text/html', value: '<h1>HTML version</h1>' }

226

]);

227

228

// Add custom content type

229

mail.addContent({

230

type: 'text/calendar',

231

value: 'BEGIN:VCALENDAR\nVERSION:2.0\n...'

232

});

233

```

234

235

### Template Integration

236

237

Integrate with SendGrid templates for dynamic content generation.

238

239

```javascript { .api }

240

/**

241

* Set SendGrid template ID

242

* @param templateId - Template ID (dynamic templates start with 'd-')

243

*/

244

mail.setTemplateId(templateId);

245

246

/**

247

* Set dynamic template data for the entire email

248

* @param dynamicTemplateData - Object containing template variables

249

*/

250

mail.setDynamicTemplateData(dynamicTemplateData);

251

252

/**

253

* Set legacy template substitutions

254

* @param substitutions - Object mapping substitution keys to values

255

*/

256

mail.setSubstitutions(substitutions);

257

258

/**

259

* Set substitution wrapper characters

260

* @param wrappers - Array with left and right wrapper characters

261

*/

262

mail.setSubstitutionWrappers(wrappers);

263

```

264

265

**Usage Examples:**

266

267

```javascript

268

// Dynamic template (recommended)

269

mail.setTemplateId('d-1234567890abcdef');

270

mail.setDynamicTemplateData({

271

username: 'john_doe',

272

loginUrl: 'https://app.example.com/login',

273

supportEmail: 'support@example.com'

274

});

275

276

// Legacy template

277

mail.setTemplateId('legacy-template-id');

278

mail.setSubstitutions({

279

':username:': 'john_doe',

280

':loginUrl:': 'https://app.example.com/login'

281

});

282

283

// Custom substitution wrappers

284

mail.setSubstitutionWrappers(['[[', ']]']); // Use [[variable]] instead of {{variable}}

285

```

286

287

### Categories and Organization

288

289

Organize emails with categories, headers, and custom arguments for tracking and management.

290

291

```javascript { .api }

292

/**

293

* Set email categories for organization and analytics

294

* @param categories - Array of category strings

295

*/

296

mail.setCategories(categories);

297

298

/**

299

* Add a single category

300

* @param category - Category string

301

*/

302

mail.addCategory(category);

303

304

/**

305

* Set custom SMTP headers

306

* @param headers - Object mapping header names to values

307

*/

308

mail.setHeaders(headers);

309

310

/**

311

* Add a single header

312

* @param key - Header name

313

* @param value - Header value

314

*/

315

mail.addHeader(key, value);

316

317

/**

318

* Set custom arguments for tracking

319

* @param customArgs - Object with custom tracking data

320

*/

321

mail.setCustomArgs(customArgs);

322

323

/**

324

* Set template sections for legacy templates

325

* @param sections - Object mapping section names to content

326

*/

327

mail.setSections(sections);

328

```

329

330

**Usage Examples:**

331

332

```javascript

333

// Email categories for analytics

334

mail.setCategories(['transactional', 'password-reset']);

335

mail.addCategory('high-priority');

336

337

// Custom headers

338

mail.setHeaders({

339

'X-Priority': '1',

340

'X-Mailer': 'MyApp v1.0'

341

});

342

mail.addHeader('X-Campaign-ID', 'spring-2024-promotion');

343

344

// Custom arguments for tracking

345

mail.setCustomArgs({

346

userId: '12345',

347

campaignId: 'welcome-series',

348

version: 'A'

349

});

350

351

// Template sections for legacy templates

352

mail.setSections({

353

':header:': '<h1>Welcome to Our Service</h1>',

354

':footer:': '<p>© 2024 Example Corp</p>'

355

});

356

```

357

358

### Advanced Configuration

359

360

Configure delivery options, suppression management, and batch processing.

361

362

```javascript { .api }

363

/**

364

* Set batch ID for grouping related emails

365

* @param batchId - Unique batch identifier

366

*/

367

mail.setBatchId(batchId);

368

369

/**

370

* Set IP pool for sending

371

* @param ipPoolName - Name of the IP pool to use

372

*/

373

mail.setIpPoolName(ipPoolName);

374

375

/**

376

* Set Advanced Suppression Management settings

377

* @param asm - ASM configuration object

378

*/

379

mail.setAsm(asm);

380

381

/**

382

* Control warning display for dynamic templates

383

* @param hide - Whether to hide warnings

384

*/

385

mail.setHideWarnings(hide);

386

```

387

388

**Usage Examples:**

389

390

```javascript

391

// Batch processing

392

mail.setBatchId('batch-2024-03-15-newsletter');

393

394

// IP pool selection

395

mail.setIpPoolName('marketing-pool');

396

397

// Suppression management

398

mail.setAsm({

399

groupId: 123,

400

groupsToDisplay: [123, 456, 789]

401

});

402

403

// Hide dynamic template warnings

404

mail.setHideWarnings(true);

405

```

406

407

## Complete Example

408

409

```javascript

410

const { Mail } = require('@sendgrid/helpers').classes;

411

412

// Create comprehensive email

413

const mail = new Mail();

414

415

// Basic properties

416

mail.setFrom({ email: 'noreply@example.com', name: 'Example Corp' });

417

mail.setSubject('Welcome to Our Service');

418

mail.setReplyTo('support@example.com');

419

420

// Recipients with personalization

421

mail.addPersonalization({

422

to: [{ email: 'new-user@example.com', name: 'New User' }],

423

dynamicTemplateData: {

424

firstName: 'New',

425

accountType: 'Premium',

426

activationUrl: 'https://app.example.com/activate?token=abc123'

427

}

428

});

429

430

// Template

431

mail.setTemplateId('d-welcome-template-id');

432

433

// Organization

434

mail.setCategories(['transactional', 'welcome']);

435

mail.setCustomArgs({

436

userId: '54321',

437

signupSource: 'website'

438

});

439

440

// Custom headers

441

mail.addHeader('X-Campaign', 'user-onboarding');

442

443

// Advanced settings

444

mail.setBatchId('welcome-batch-2024-03');

445

mail.setIpPoolName('transactional-pool');

446

447

// Convert to JSON for sending

448

const emailData = mail.toJSON();

449

console.log('Email ready for sending:', emailData);

450

```