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

email-service.mddocs/

0

# Email Sending Service

1

2

The email sending service provides the main interface for sending emails through SendGrid. It includes configuration methods, authentication setup, and sending capabilities for both single and multiple emails.

3

4

## Capabilities

5

6

### Service Configuration

7

8

Configure the SendGrid service with API keys, authentication, and client settings.

9

10

```javascript { .api }

11

/**

12

* Set the SendGrid API key for authentication

13

* @param apiKey - Your SendGrid API key

14

*/

15

sgMail.setApiKey(apiKey);

16

17

/**

18

* Set Twilio Email authentication credentials

19

* @param username - Twilio username

20

* @param password - Twilio password

21

*/

22

sgMail.setTwilioEmailAuth(username, password);

23

24

/**

25

* Set request timeout in milliseconds

26

* @param timeout - Timeout value in milliseconds

27

*/

28

sgMail.setTimeout(timeout);

29

30

/**

31

* Set template substitution wrapper characters

32

* @param left - Left wrapper character (default: '{{')

33

* @param right - Right wrapper character (default: '}}')

34

*/

35

sgMail.setSubstitutionWrappers(left, right);

36

```

37

38

**Usage Examples:**

39

40

```javascript

41

const sgMail = require('@sendgrid/mail');

42

43

// Basic setup

44

sgMail.setApiKey(process.env.SENDGRID_API_KEY);

45

46

// Configure timeout for slow connections

47

sgMail.setTimeout(10000); // 10 second timeout

48

49

// Custom substitution wrappers for templates

50

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

51

52

// Twilio Email Auth (alternative to API key)

53

sgMail.setTwilioEmailAuth('your_username', 'your_password');

54

```

55

56

### Content Security

57

58

Prevent sensitive data from being sent in emails through content filtering rules.

59

60

```javascript { .api }

61

/**

62

* Set rules for filtering sensitive content from emails

63

* @param rules - Array of strings, RegExp objects, or rule objects

64

*/

65

sgMail.setSecretRules(rules);

66

```

67

68

**Usage Examples:**

69

70

```javascript

71

// Simple string patterns

72

sgMail.setSecretRules([

73

'password',

74

'secret',

75

'confidential'

76

]);

77

78

// Regular expression patterns

79

sgMail.setSecretRules([

80

/\b\d{4}-\d{4}-\d{4}-\d{4}\b/, // Credit card pattern

81

/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i // Email pattern

82

]);

83

84

// Rule objects with names

85

sgMail.setSecretRules([

86

{

87

pattern: /\bssn:\s*\d{3}-\d{2}-\d{4}\b/i,

88

name: 'Social Security Number'

89

}

90

]);

91

```

92

93

### Email Sending

94

95

Send single or multiple emails with full control over delivery options.

96

97

```javascript { .api }

98

/**

99

* Send an email or array of emails

100

* @param data - Email data object or array of email data objects

101

* @param isMultiple - Flag indicating multiple recipient handling (optional)

102

* @param callback - Optional callback function (error, result) => void

103

* @returns Promise resolving to send result

104

*/

105

sgMail.send(data, isMultiple, callback);

106

107

/**

108

* Send multiple emails (convenience method)

109

* @param data - Array of email data objects

110

* @param callback - Optional callback function (error, result) => void

111

* @returns Promise resolving to send results array

112

*/

113

sgMail.sendMultiple(data, callback);

114

```

115

116

**Usage Examples:**

117

118

```javascript

119

// Single email with Promise

120

const msg = {

121

to: 'recipient@example.com',

122

from: 'sender@example.com',

123

subject: 'Hello World',

124

text: 'Hello from SendGrid!',

125

html: '<h1>Hello from SendGrid!</h1>'

126

};

127

128

sgMail.send(msg)

129

.then(() => console.log('Email sent'))

130

.catch(error => console.error(error));

131

132

// Single email with callback

133

sgMail.send(msg, (error, result) => {

134

if (error) {

135

console.error('Error:', error);

136

} else {

137

console.log('Success:', result);

138

}

139

});

140

141

// Multiple emails in parallel

142

const messages = [

143

{

144

to: 'user1@example.com',

145

from: 'noreply@example.com',

146

subject: 'Welcome User 1',

147

text: 'Welcome to our service!'

148

},

149

{

150

to: 'user2@example.com',

151

from: 'noreply@example.com',

152

subject: 'Welcome User 2',

153

text: 'Welcome to our service!'

154

}

155

];

156

157

sgMail.sendMultiple(messages)

158

.then(results => console.log('All emails sent:', results))

159

.catch(error => console.error('Error sending emails:', error));

160

161

// Single email to multiple recipients (each gets individual email)

162

const msgToMultiple = {

163

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

164

from: 'sender@example.com',

165

subject: 'Broadcast Message',

166

text: 'This message goes to multiple recipients'

167

};

168

169

sgMail.send(msgToMultiple, true) // isMultiple = true

170

.then(() => console.log('Emails sent to all recipients'))

171

.catch(error => console.error(error));

172

```

173

174

### MailService Class

175

176

Create custom service instances with independent configuration.

177

178

```javascript { .api }

179

/**

180

* MailService class for creating independent service instances

181

*/

182

const { MailService } = require('@sendgrid/mail');

183

184

/**

185

* Create a new MailService instance

186

*/

187

const customService = new MailService();

188

189

// All configuration methods available on custom instances

190

customService.setApiKey(apiKey);

191

customService.setTwilioEmailAuth(username, password);

192

customService.setTimeout(timeout);

193

customService.setSubstitutionWrappers(left, right);

194

customService.setSecretRules(rules);

195

customService.send(data, isMultiple, callback);

196

customService.sendMultiple(data, callback);

197

```

198

199

**Usage Examples:**

200

201

```javascript

202

const { MailService } = require('@sendgrid/mail');

203

204

// Create separate services for different use cases

205

const transactionalService = new MailService();

206

const marketingService = new MailService();

207

208

// Configure each service independently

209

transactionalService.setApiKey(process.env.SENDGRID_TRANSACTIONAL_KEY);

210

marketingService.setApiKey(process.env.SENDGRID_MARKETING_KEY);

211

212

// Set different timeouts

213

transactionalService.setTimeout(5000); // Fast timeout for transactional

214

marketingService.setTimeout(30000); // Longer timeout for marketing

215

216

// Use services independently

217

transactionalService.send(orderConfirmation);

218

marketingService.send(newsletter);

219

```

220

221

## Error Handling

222

223

The service returns detailed error information for debugging and monitoring.

224

225

```javascript

226

sgMail.send(invalidMsg)

227

.catch(error => {

228

console.error('SendGrid Error:', error.message);

229

230

// HTTP response details

231

if (error.response) {

232

console.error('Status Code:', error.response.statusCode);

233

console.error('Response Body:', error.response.body);

234

235

// SendGrid-specific error details

236

if (error.response.body.errors) {

237

error.response.body.errors.forEach(err => {

238

console.error(`Error: ${err.message} (Field: ${err.field})`);

239

});

240

}

241

}

242

});

243

```

244

245

## Authentication Methods

246

247

SendGrid Mail supports two authentication methods:

248

249

1. **API Key Authentication** (Recommended):

250

```javascript

251

sgMail.setApiKey('SG.your-api-key-here');

252

```

253

254

2. **Twilio Email Authentication**:

255

```javascript

256

sgMail.setTwilioEmailAuth('your-username', 'your-password');

257

```

258

259

The API key method is recommended for most use cases as it provides better security and easier credential management.

260

261

## Content Filtering

262

263

Content filtering helps prevent accidental transmission of sensitive data. When secret rules are triggered, the send operation will throw an error before the email is transmitted:

264

265

```javascript

266

sgMail.setSecretRules(['password', 'secret']);

267

268

const badMsg = {

269

to: 'user@example.com',

270

from: 'sender@example.com',

271

subject: 'Your account info',

272

text: 'Your password is: secret123' // This will trigger the filter

273

};

274

275

sgMail.send(badMsg)

276

.catch(error => {

277

// Error: The pattern '/secret/' was found in the Mail content!

278

console.error(error.message);

279

});

280

```