@aws-blocks/bb-email-client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,174 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # @aws-blocks/bb-email-client
2
+
3
+ Transactional email sending via Amazon SES.
4
+
5
+ ## Usage
6
+
7
+ ```typescript
8
+ import { EmailClient } from '@aws-blocks/bb-email-client';
9
+
10
+ const emailClient = new EmailClient(scope, 'notifications', {
11
+ fromAddress: 'noreply@example.com',
12
+ configurationSet: 'my-tracking-set', // optional
13
+ });
14
+
15
+ // Send a single email
16
+ const { messageId } = await emailClient.send({
17
+ to: 'user@example.com',
18
+ subject: 'Welcome!',
19
+ body: 'Thanks for signing up.',
20
+ html: '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
21
+ });
22
+ console.log('Sent:', messageId);
23
+
24
+ // Send a batch of emails (uses SES SendBulkEmail API with inline templates — no setup required)
25
+ const result = await emailClient.sendBatch([
26
+ { to: 'alice@example.com', subject: 'Hi Alice', body: 'Hello!' },
27
+ { to: 'bob@example.com', subject: 'Hi Bob', body: 'Hello!' },
28
+ ]);
29
+ const sent = result.results.filter(r => r.status === 'success').length;
30
+ const failed = result.results.filter(r => r.status === 'failed').length;
31
+ console.log(`Sent: ${sent}, Failed: ${failed}`);
32
+ ```
33
+
34
+ ## API
35
+
36
+ ### `new EmailClient(scope, id, options)`
37
+
38
+ | Option | Type | Required | Description |
39
+ |--------|------|----------|-------------|
40
+ | `fromAddress` | `string` | ✅ | Verified sender email address |
41
+ | `replyTo` | `string[]` | ❌ | Reply-to addresses |
42
+ | `configurationSet` | `string` | ❌ | SES configuration set name |
43
+
44
+ ### `emailClient.send(message): Promise<SendResult>`
45
+
46
+ Send to one or more recipients. Returns `{ messageId: string }`.
47
+
48
+ | Field | Type | Description |
49
+ |-------|------|-------------|
50
+ | `message.to` | `string \| string[]` | Recipient address(es) |
51
+ | `message.subject` | `string` | Subject line |
52
+ | `message.body` | `string` | Plain text body |
53
+ | `message.html` | `string?` | HTML body (optional) |
54
+ | `message.cc` | `string[]?` | CC addresses (optional) |
55
+ | `message.bcc` | `string[]?` | BCC addresses (optional) |
56
+
57
+ ### `emailClient.sendBatch(messages): Promise<SendBatchResult>`
58
+
59
+ Send multiple messages using the SES `SendBulkEmail` API with inline templates.
60
+ No stored SES template is required — each message's subject, body, and HTML are passed
61
+ directly via `TemplateContent`.
62
+
63
+ Returns `{ results: Array<{ status, messageId?, error? }> }`.
64
+
65
+ Never throws on send failures. Both partial and total failures are reported per-entry in the
66
+ `results` array (with `status: 'failed'`).
67
+
68
+ Each message in the array is an `EmailMessage` (same type as `send()`):
69
+
70
+ | Field | Type | Description |
71
+ |-------|------|-------------|
72
+ | `to` | `string \| string[]` | Recipient address(es) |
73
+ | `subject` | `string` | Subject line |
74
+ | `body` | `string` | Plain text body |
75
+ | `html` | `string?` | HTML body (optional) |
76
+ | `cc` | `string[]?` | CC addresses (optional) |
77
+ | `bcc` | `string[]?` | BCC addresses (optional) |
78
+
79
+ ## Error Handling
80
+
81
+ ```typescript
82
+ import { EmailErrors } from '@aws-blocks/bb-email-client';
83
+ import { isBlocksError } from '@aws-blocks/core';
84
+
85
+ try {
86
+ await emailClient.send({ to: 'user@example.com', subject: 'Hi', body: 'Hello' });
87
+ } catch (e: unknown) {
88
+ if (isBlocksError(e, EmailErrors.SendFailed)) {
89
+ // General send failure — check error message for details
90
+ }
91
+ if (isBlocksError(e, EmailErrors.InvalidInput)) {
92
+ // Malformed input (e.g. invalid email address)
93
+ }
94
+ if (isBlocksError(e, EmailErrors.DomainNotVerified)) {
95
+ // Sending domain not verified in SES
96
+ }
97
+ if (isBlocksError(e, EmailErrors.AccountPaused)) {
98
+ // Account sending is paused by AWS
99
+ }
100
+ if (isBlocksError(e, EmailErrors.RateLimited)) {
101
+ // Transient — safe to retry after backoff
102
+ }
103
+ }
104
+ ```
105
+
106
+ ## Local Development
107
+
108
+ In local dev mode (`npm run dev`), emails are:
109
+ - Logged to the console with format: `[Email:{id}] → recipient | Subject: ... | Body: ...`
110
+ - Persisted to `.bb-data/{fullId}/emails.json` for inspection
111
+ - Batch sends emit a rate-limit warning (simulating SES sandbox behavior)
112
+
113
+ ## Package Export Conditions
114
+
115
+ This package uses a custom `"cdk"` export condition:
116
+
117
+ ```json
118
+ {
119
+ "exports": {
120
+ ".": {
121
+ "cdk": "./dist/index.cdk.js",
122
+ "aws-runtime": "./dist/index.aws.js",
123
+ "default": "./dist/index.mock.js"
124
+ }
125
+ }
126
+ }
127
+ ```
128
+
129
+ > **Note:** The `"cdk"` condition is a Blocks framework convention, resolved by the Blocks build
130
+ > toolchain (tsx with `--conditions=cdk`). It is **not** a built-in Node.js condition and will
131
+ > not resolve in standard `node` or `ts-node` unless you pass `--conditions=cdk` explicitly.
132
+
133
+ ## Limits
134
+
135
+ - **Per-message recipients**: 50 recipients max per message (To + CC + BCC combined)
136
+ - **Batch API destinations**: 50 destinations per `SendBulkEmail` API call (handled automatically via chunking)
137
+ - **Message size**: 40 MB per message
138
+ - **SES sandbox rate**: 1 email/sec (request production access for higher throughput)
139
+
140
+ > **Note:** In local dev (mock), per-message recipient and size limits are enforced locally before
141
+ > sending (limit violations are recorded as failed entries). In the AWS runtime, these limits are
142
+ > enforced by SES itself, so the failure surfaces in the SES response rather than locally — the
143
+ > failure point differs between runtimes, but in both cases failures appear per-entry in `results`.
144
+
145
+
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Typed error constants for Email. Use with `isBlocksError()` in catch blocks.
3
+ *
4
+ * @example
5
+ * ```typescript
6
+ * try {
7
+ * await email.send('user@example.com', { subject: 'Hi', body: 'Hello' });
8
+ * } catch (e: unknown) {
9
+ * if (isBlocksError(e, EmailErrors.SendFailed)) {
10
+ * // General send failure — check error message for details
11
+ * }
12
+ * if (isBlocksError(e, EmailErrors.InvalidInput)) {
13
+ * // malformed input (e.g. invalid email address)
14
+ * }
15
+ * throw e;
16
+ * }
17
+ * ```
18
+ */
19
+ export declare const EmailErrors: {
20
+ readonly SendFailed: "EmailSendFailedException";
21
+ readonly InvalidInput: "InvalidInputException";
22
+ readonly DomainNotVerified: "DomainNotVerifiedException";
23
+ readonly AccountPaused: "AccountSendingPausedException";
24
+ readonly RateLimited: "RateLimitedException";
25
+ };
26
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,WAAW;;;;;;CAMd,CAAC"}
package/dist/errors.js ADDED
@@ -0,0 +1,27 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * Typed error constants for Email. Use with `isBlocksError()` in catch blocks.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * try {
9
+ * await email.send('user@example.com', { subject: 'Hi', body: 'Hello' });
10
+ * } catch (e: unknown) {
11
+ * if (isBlocksError(e, EmailErrors.SendFailed)) {
12
+ * // General send failure — check error message for details
13
+ * }
14
+ * if (isBlocksError(e, EmailErrors.InvalidInput)) {
15
+ * // malformed input (e.g. invalid email address)
16
+ * }
17
+ * throw e;
18
+ * }
19
+ * ```
20
+ */
21
+ export const EmailErrors = {
22
+ SendFailed: 'EmailSendFailedException',
23
+ InvalidInput: 'InvalidInputException',
24
+ DomainNotVerified: 'DomainNotVerifiedException',
25
+ AccountPaused: 'AccountSendingPausedException',
26
+ RateLimited: 'RateLimitedException',
27
+ };
@@ -0,0 +1,59 @@
1
+ import { Scope } from '@aws-blocks/core';
2
+ import type { ScopeParent } from '@aws-blocks/core';
3
+ export { EmailErrors } from './errors.js';
4
+ export type { EmailOptions, EmailMessage, SendResult, SendBatchResult } from './types.js';
5
+ import type { EmailOptions, EmailMessage, SendResult, SendBatchResult } from './types.js';
6
+ import type { ChildLogger } from '@aws-blocks/bb-logger';
7
+ /**
8
+ * Send transactional emails via Amazon SES.
9
+ *
10
+ * **When to use:** You need to send transactional emails (welcome messages,
11
+ * password resets, notifications, order confirmations).
12
+ *
13
+ * **When NOT to use:** For bulk marketing campaigns, use a dedicated ESP.
14
+ * For in-app notifications, use a notification service.
15
+ *
16
+ * **Best practices:**
17
+ * - Verify your sending domain in SES before production use
18
+ * - Use a configuration set for delivery tracking
19
+ * - Keep email content under 40 MB
20
+ * - Each message is limited to 50 recipients (To + CC + BCC combined)
21
+ *
22
+ * **Scaling:** SES handles up to 200 emails/second by default (can request increase).
23
+ * No infrastructure to manage.
24
+ */
25
+ export declare class EmailClient extends Scope {
26
+ private client;
27
+ private fromAddress;
28
+ private replyTo?;
29
+ private configurationSet?;
30
+ /** @internal Logger for internal operations. Defaults to error-level when not provided. */
31
+ protected log: ChildLogger;
32
+ constructor(scope: ScopeParent, id: string, options: EmailOptions);
33
+ /**
34
+ * Send an email to one or more recipients.
35
+ *
36
+ * Uses the SDK's built-in adaptive retry with maxAttempts: 3.
37
+ *
38
+ * @param message - The email message to send (to, subject, body, optional html/cc/bcc).
39
+ * @returns The SES message ID for the sent email.
40
+ * @throws {EmailErrors.SendFailed} General send failure.
41
+ * @throws {EmailErrors.InvalidInput} If input is invalid (e.g. malformed address, too many recipients).
42
+ * @throws {EmailErrors.DomainNotVerified} If the sending domain is not verified.
43
+ * @throws {EmailErrors.AccountPaused} If account sending is paused.
44
+ * @throws {EmailErrors.RateLimited} If rate limit is exceeded.
45
+ */
46
+ send(message: EmailMessage): Promise<SendResult>;
47
+ /**
48
+ * Send a batch of email messages using the SES SendBulkEmail API with inline passthrough templates.
49
+ *
50
+ * Messages are chunked into groups of 50 destinations per API call (SES limit).
51
+ *
52
+ * TODO: Add retry logic for transient failures (throttling, 5xx).
53
+ *
54
+ * @param messages - Array of email messages to send.
55
+ * @returns Result with per-message status in the same order as the input array.
56
+ */
57
+ sendBatch(messages: EmailMessage[]): Promise<SendBatchResult>;
58
+ }
59
+ //# sourceMappingURL=index.aws.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.aws.d.ts","sourceRoot":"","sources":["../src/index.aws.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAIpD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE1F,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAG1F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAwCzD;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,WAAY,SAAQ,KAAK;IACrC,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,WAAW,CAAS;IAC5B,OAAO,CAAC,OAAO,CAAC,CAAW;IAC3B,OAAO,CAAC,gBAAgB,CAAC,CAAS;IAElC,2FAA2F;IAC3F,SAAS,CAAC,GAAG,EAAE,WAAW,CAAC;gBAEf,KAAK,EAAE,WAAW,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY;IAYjE;;;;;;;;;;;;OAYG;IACG,IAAI,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAAC,UAAU,CAAC;IAiCtD;;;;;;;;;OASG;IACG,SAAS,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,eAAe,CAAC;CAqEnE"}
@@ -0,0 +1,194 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { SESv2Client, SendEmailCommand, SendBulkEmailCommand } from '@aws-sdk/client-sesv2';
4
+ import { Scope } from '@aws-blocks/core';
5
+ import { BB_NAME, BB_VERSION } from './version.js';
6
+ // Re-export public types and errors
7
+ export { EmailErrors } from './errors.js';
8
+ import { EmailErrors } from './errors.js';
9
+ import { Logger } from '@aws-blocks/bb-logger';
10
+ const BATCH_CHUNK_SIZE = 50;
11
+ function blocksError(name, message) {
12
+ const err = new Error(`${name}: ${message}`);
13
+ err.name = name;
14
+ return err;
15
+ }
16
+ function mapSesError(err) {
17
+ const message = err.message ?? 'Unknown SES error';
18
+ if (err.name === 'MailFromDomainNotVerifiedException') {
19
+ return blocksError(EmailErrors.DomainNotVerified, message);
20
+ }
21
+ if (err.name === 'MessageRejected') {
22
+ const lower = message.toLowerCase();
23
+ if (lower.includes('not verified') || lower.includes('identity')) {
24
+ return blocksError(EmailErrors.DomainNotVerified, message);
25
+ }
26
+ return blocksError(EmailErrors.SendFailed, message);
27
+ }
28
+ if (err.name === 'AccountSuspendedException' || err.name === 'SendingPausedException') {
29
+ return blocksError(EmailErrors.AccountPaused, message);
30
+ }
31
+ if (err.name === 'TooManyRequestsException' || err.name === 'ThrottlingException') {
32
+ return blocksError(EmailErrors.RateLimited, message);
33
+ }
34
+ if (err.name === 'BadRequestException') {
35
+ return blocksError(EmailErrors.InvalidInput, message);
36
+ }
37
+ return blocksError(EmailErrors.SendFailed, message);
38
+ }
39
+ /**
40
+ * Send transactional emails via Amazon SES.
41
+ *
42
+ * **When to use:** You need to send transactional emails (welcome messages,
43
+ * password resets, notifications, order confirmations).
44
+ *
45
+ * **When NOT to use:** For bulk marketing campaigns, use a dedicated ESP.
46
+ * For in-app notifications, use a notification service.
47
+ *
48
+ * **Best practices:**
49
+ * - Verify your sending domain in SES before production use
50
+ * - Use a configuration set for delivery tracking
51
+ * - Keep email content under 40 MB
52
+ * - Each message is limited to 50 recipients (To + CC + BCC combined)
53
+ *
54
+ * **Scaling:** SES handles up to 200 emails/second by default (can request increase).
55
+ * No infrastructure to manage.
56
+ */
57
+ export class EmailClient extends Scope {
58
+ client;
59
+ fromAddress;
60
+ replyTo;
61
+ configurationSet;
62
+ /** @internal Logger for internal operations. Defaults to error-level when not provided. */
63
+ log;
64
+ constructor(scope, id, options) {
65
+ super(id, { parent: scope, bbName: BB_NAME, bbVersion: BB_VERSION });
66
+ this.log = options?.logger ?? new Logger(this, 'logger', { level: 'error' });
67
+ this.client = new SESv2Client({
68
+ maxAttempts: 3,
69
+ customUserAgent: this.buildUserAgentChain(),
70
+ });
71
+ this.fromAddress = options.fromAddress;
72
+ this.replyTo = options.replyTo;
73
+ this.configurationSet = options.configurationSet;
74
+ }
75
+ /**
76
+ * Send an email to one or more recipients.
77
+ *
78
+ * Uses the SDK's built-in adaptive retry with maxAttempts: 3.
79
+ *
80
+ * @param message - The email message to send (to, subject, body, optional html/cc/bcc).
81
+ * @returns The SES message ID for the sent email.
82
+ * @throws {EmailErrors.SendFailed} General send failure.
83
+ * @throws {EmailErrors.InvalidInput} If input is invalid (e.g. malformed address, too many recipients).
84
+ * @throws {EmailErrors.DomainNotVerified} If the sending domain is not verified.
85
+ * @throws {EmailErrors.AccountPaused} If account sending is paused.
86
+ * @throws {EmailErrors.RateLimited} If rate limit is exceeded.
87
+ */
88
+ async send(message) {
89
+ const { to, subject, body, html, cc, bcc } = message;
90
+ const recipients = Array.isArray(to) ? to : [to];
91
+ const command = new SendEmailCommand({
92
+ FromEmailAddress: this.fromAddress,
93
+ Destination: {
94
+ ToAddresses: recipients,
95
+ ...(cc?.length ? { CcAddresses: cc } : {}),
96
+ ...(bcc?.length ? { BccAddresses: bcc } : {}),
97
+ },
98
+ ...(this.replyTo && { ReplyToAddresses: this.replyTo }),
99
+ Content: {
100
+ Simple: {
101
+ Subject: { Data: subject },
102
+ Body: {
103
+ Text: { Data: body },
104
+ ...(html ? { Html: { Data: html } } : {}),
105
+ },
106
+ },
107
+ },
108
+ ...(this.configurationSet ? { ConfigurationSetName: this.configurationSet } : {}),
109
+ });
110
+ try {
111
+ const response = await this.client.send(command);
112
+ return { messageId: response.MessageId ?? '' };
113
+ }
114
+ catch (err) {
115
+ if (err.name && err.name in EmailErrors)
116
+ throw err;
117
+ throw mapSesError(err);
118
+ }
119
+ }
120
+ /**
121
+ * Send a batch of email messages using the SES SendBulkEmail API with inline passthrough templates.
122
+ *
123
+ * Messages are chunked into groups of 50 destinations per API call (SES limit).
124
+ *
125
+ * TODO: Add retry logic for transient failures (throttling, 5xx).
126
+ *
127
+ * @param messages - Array of email messages to send.
128
+ * @returns Result with per-message status in the same order as the input array.
129
+ */
130
+ async sendBatch(messages) {
131
+ const results = new Array(messages.length);
132
+ // Process in chunks of BATCH_CHUNK_SIZE
133
+ for (let chunkStart = 0; chunkStart < messages.length; chunkStart += BATCH_CHUNK_SIZE) {
134
+ const chunkIndices = messages
135
+ .slice(chunkStart, chunkStart + BATCH_CHUNK_SIZE)
136
+ .map((_, i) => chunkStart + i);
137
+ const chunk = chunkIndices.map(idx => messages[idx]);
138
+ const command = new SendBulkEmailCommand({
139
+ FromEmailAddress: this.fromAddress,
140
+ ...(this.replyTo && { ReplyToAddresses: this.replyTo }),
141
+ ...(this.configurationSet ? { ConfigurationSetName: this.configurationSet } : {}),
142
+ DefaultContent: {
143
+ Template: {
144
+ TemplateContent: {
145
+ Subject: '{{subject}}',
146
+ Html: '{{html}}',
147
+ Text: '{{body}}',
148
+ },
149
+ TemplateData: JSON.stringify({ subject: '', body: '', html: '' }),
150
+ },
151
+ },
152
+ BulkEmailEntries: chunk.map(msg => ({
153
+ Destination: {
154
+ ToAddresses: Array.isArray(msg.to) ? msg.to : [msg.to],
155
+ CcAddresses: msg.cc || [],
156
+ BccAddresses: msg.bcc || [],
157
+ },
158
+ ReplacementEmailContent: {
159
+ ReplacementTemplate: {
160
+ ReplacementTemplateData: JSON.stringify({
161
+ subject: msg.subject,
162
+ body: msg.body,
163
+ ...(msg.html ? { html: msg.html } : { html: msg.body }),
164
+ }),
165
+ },
166
+ },
167
+ })),
168
+ });
169
+ try {
170
+ const response = await this.client.send(command);
171
+ const bulkResults = response.BulkEmailEntryResults ?? [];
172
+ for (let i = 0; i < chunkIndices.length; i++) {
173
+ const globalIdx = chunkIndices[i];
174
+ const entry = bulkResults[i];
175
+ if (entry?.Status === 'SUCCESS') {
176
+ results[globalIdx] = { status: 'success', messageId: entry.MessageId ?? '' };
177
+ }
178
+ else {
179
+ const errorMsg = entry?.Error ?? 'Unknown bulk send error';
180
+ results[globalIdx] = { status: 'failed', error: errorMsg };
181
+ }
182
+ }
183
+ }
184
+ catch (err) {
185
+ // Entire chunk failed — mark all as failed
186
+ for (const globalIdx of chunkIndices) {
187
+ const mapped = mapSesError(err);
188
+ results[globalIdx] = { status: 'failed', error: mapped.message };
189
+ }
190
+ }
191
+ }
192
+ return { results };
193
+ }
194
+ }
@@ -0,0 +1,4 @@
1
+ export declare class EmailClient {
2
+ constructor(...args: any[]);
3
+ }
4
+ //# sourceMappingURL=index.browser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.browser.d.ts","sourceRoot":"","sources":["../src/index.browser.ts"],"names":[],"mappings":"AAIA,qBAAa,WAAW;gBACV,GAAG,IAAI,EAAE,GAAG,EAAE;CAC3B"}
@@ -0,0 +1,6 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Browser stub - Email runs server-side only
4
+ export class EmailClient {
5
+ constructor(...args) { }
6
+ }
@@ -0,0 +1,9 @@
1
+ import { Scope } from '@aws-blocks/core/cdk';
2
+ import type { ScopeParent } from '@aws-blocks/core';
3
+ export { EmailErrors } from './errors.js';
4
+ export type { EmailOptions, EmailMessage, SendResult, SendBatchResult } from './types.js';
5
+ import type { EmailOptions } from './types.js';
6
+ export declare class EmailClient extends Scope {
7
+ constructor(scope: ScopeParent, id: string, options: EmailOptions);
8
+ }
9
+ //# sourceMappingURL=index.cdk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cdk.d.ts","sourceRoot":"","sources":["../src/index.cdk.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAGpD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE1F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C,qBAAa,WAAY,SAAQ,KAAK;gBACzB,KAAK,EAAE,WAAW,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,YAAY;CAgCjE"}