@builderbot/provider-email 1.3.15-alpha.8

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.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Leifer Mendez
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,254 @@
1
+ # @builderbot/provider-email
2
+
3
+ Email provider for BuilderBot using IMAP/SMTP. Receive emails in real-time using IMAP IDLE and send emails via SMTP.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @builderbot/provider-email
9
+ # or
10
+ pnpm add @builderbot/provider-email
11
+ ```
12
+
13
+ ## Features
14
+
15
+ - Real-time email reception using IMAP IDLE
16
+ - Send emails via SMTP
17
+ - Thread/conversation tracking
18
+ - Attachment support (send and receive)
19
+ - Compatible with any IMAP/SMTP server (Gmail, Outlook, custom servers, etc.)
20
+
21
+ ## Quick Start
22
+
23
+ ```typescript
24
+ import { createBot, createProvider, createFlow, addKeyword } from '@builderbot/bot'
25
+ import { EmailProvider } from '@builderbot/provider-email'
26
+
27
+ const emailProvider = createProvider(EmailProvider, {
28
+ imap: {
29
+ host: 'imap.gmail.com',
30
+ port: 993,
31
+ secure: true,
32
+ auth: {
33
+ user: 'your-email@gmail.com',
34
+ pass: 'your-app-password'
35
+ }
36
+ },
37
+ smtp: {
38
+ host: 'smtp.gmail.com',
39
+ port: 465,
40
+ secure: true,
41
+ auth: {
42
+ user: 'your-email@gmail.com',
43
+ pass: 'your-app-password'
44
+ }
45
+ }
46
+ })
47
+
48
+ const welcomeFlow = addKeyword(['hello', 'hi'])
49
+ .addAnswer('Hello! I received your email.')
50
+ .addAction(async (ctx, { provider }) => {
51
+ console.log('Email from:', ctx.from)
52
+ console.log('Subject:', ctx.subject)
53
+ console.log('Body:', ctx.body)
54
+ console.log('Is reply:', ctx.isReply)
55
+ })
56
+
57
+ const main = async () => {
58
+ await createBot({
59
+ flow: createFlow([welcomeFlow]),
60
+ provider: emailProvider,
61
+ database: new MemoryDB()
62
+ })
63
+ }
64
+
65
+ main()
66
+ ```
67
+
68
+ ## Configuration
69
+
70
+ ### IEmailProviderArgs
71
+
72
+ | Property | Type | Required | Default | Description |
73
+ |----------|------|----------|---------|-------------|
74
+ | `imap` | `ImapConfig` | Yes | - | IMAP server configuration |
75
+ | `smtp` | `SmtpConfig` | Yes | - | SMTP server configuration |
76
+ | `mailbox` | `string` | No | `'INBOX'` | Mailbox to monitor |
77
+ | `markAsRead` | `boolean` | No | `true` | Mark emails as read after processing |
78
+ | `fromEmail` | `string` | No | SMTP user | From address for outgoing emails |
79
+ | `fromName` | `string` | No | - | Display name for outgoing emails |
80
+
81
+ ### ImapConfig / SmtpConfig
82
+
83
+ | Property | Type | Required | Description |
84
+ |----------|------|----------|-------------|
85
+ | `host` | `string` | Yes | Server hostname |
86
+ | `port` | `number` | Yes | Server port |
87
+ | `secure` | `boolean` | No | Use SSL/TLS (default: true) |
88
+ | `auth.user` | `string` | Yes | Username |
89
+ | `auth.pass` | `string` | Yes | Password or app password |
90
+
91
+ ## Email Context (ctx)
92
+
93
+ When an email is received, the context object includes:
94
+
95
+ ```typescript
96
+ interface EmailBotContext {
97
+ from: string // Sender's email address
98
+ name: string // Sender's display name
99
+ body: string // Email body (plain text)
100
+ subject: string // Email subject
101
+ messageId: string // Unique message ID
102
+ threadId?: string // Thread ID for conversations
103
+ inReplyTo?: string // ID of email being replied to
104
+ isReply: boolean // Whether this is a reply
105
+ attachments?: Array<{
106
+ filename: string
107
+ contentType: string
108
+ size: number
109
+ }>
110
+ html?: string // HTML content (if available)
111
+ to?: string[] // Recipients
112
+ cc?: string[] // CC recipients
113
+ date?: Date // Email date
114
+ }
115
+ ```
116
+
117
+ ## API Methods
118
+
119
+ ### sendMessage(to, message, options?)
120
+
121
+ Send an email to a recipient.
122
+
123
+ ```typescript
124
+ await provider.sendMessage('recipient@example.com', 'Hello!', {
125
+ subject: 'Greeting',
126
+ html: '<h1>Hello!</h1>'
127
+ })
128
+ ```
129
+
130
+ ### sendMedia(to, message, mediaPath, options?)
131
+
132
+ Send an email with an attachment.
133
+
134
+ ```typescript
135
+ await provider.sendMedia(
136
+ 'recipient@example.com',
137
+ 'Please find the document attached.',
138
+ '/path/to/document.pdf',
139
+ { subject: 'Document' }
140
+ )
141
+ ```
142
+
143
+ ### reply(ctx, message, options?)
144
+
145
+ Reply to an existing email thread.
146
+
147
+ ```typescript
148
+ .addAction(async (ctx, { provider }) => {
149
+ await provider.reply(ctx, 'Thank you for your message!')
150
+ })
151
+ ```
152
+
153
+ ### saveFile(ctx, options?)
154
+
155
+ Save an email attachment to disk.
156
+
157
+ ```typescript
158
+ .addAction(async (ctx, { provider }) => {
159
+ if (ctx.attachments?.length) {
160
+ const filePath = await provider.saveFile(ctx, {
161
+ path: './downloads',
162
+ attachmentIndex: 0
163
+ })
164
+ console.log('Saved to:', filePath)
165
+ }
166
+ })
167
+ ```
168
+
169
+ ### getAttachments(ctx)
170
+
171
+ Get all attachments from an email.
172
+
173
+ ```typescript
174
+ const attachments = provider.getAttachments(ctx)
175
+ ```
176
+
177
+ ### isReply(ctx)
178
+
179
+ Check if the email is a reply.
180
+
181
+ ```typescript
182
+ if (provider.isReply(ctx)) {
183
+ console.log('This is a reply to:', ctx.inReplyTo)
184
+ }
185
+ ```
186
+
187
+ ### getThreadId(ctx)
188
+
189
+ Get the thread ID for conversation tracking.
190
+
191
+ ```typescript
192
+ const threadId = provider.getThreadId(ctx)
193
+ ```
194
+
195
+ ## Gmail Configuration
196
+
197
+ For Gmail, you need to use an App Password:
198
+
199
+ 1. Enable 2-Factor Authentication on your Google account
200
+ 2. Go to [Google App Passwords](https://myaccount.google.com/apppasswords)
201
+ 3. Generate a new app password for "Mail"
202
+ 4. Use this password in the configuration
203
+
204
+ ```typescript
205
+ {
206
+ imap: {
207
+ host: 'imap.gmail.com',
208
+ port: 993,
209
+ secure: true,
210
+ auth: {
211
+ user: 'your-email@gmail.com',
212
+ pass: 'xxxx xxxx xxxx xxxx' // App password
213
+ }
214
+ },
215
+ smtp: {
216
+ host: 'smtp.gmail.com',
217
+ port: 465,
218
+ secure: true,
219
+ auth: {
220
+ user: 'your-email@gmail.com',
221
+ pass: 'xxxx xxxx xxxx xxxx' // App password
222
+ }
223
+ }
224
+ }
225
+ ```
226
+
227
+ ## Outlook/Office 365 Configuration
228
+
229
+ ```typescript
230
+ {
231
+ imap: {
232
+ host: 'outlook.office365.com',
233
+ port: 993,
234
+ secure: true,
235
+ auth: {
236
+ user: 'your-email@outlook.com',
237
+ pass: 'your-password'
238
+ }
239
+ },
240
+ smtp: {
241
+ host: 'smtp.office365.com',
242
+ port: 587,
243
+ secure: false, // Use STARTTLS
244
+ auth: {
245
+ user: 'your-email@outlook.com',
246
+ pass: 'your-password'
247
+ }
248
+ }
249
+ }
250
+ ```
251
+
252
+ ## License
253
+
254
+ MIT
@@ -0,0 +1,77 @@
1
+ import EventEmitter from 'node:events';
2
+ import type { IEmailProviderArgs, EmailBotContext, EmailSendOptions } from '../types';
3
+ /**
4
+ * Class representing EmailCoreVendor, handles IMAP/SMTP operations.
5
+ * @extends EventEmitter
6
+ */
7
+ export declare class EmailCoreVendor extends EventEmitter {
8
+ private imapClient;
9
+ private smtpTransporter;
10
+ private config;
11
+ private isConnected;
12
+ private reconnectAttempts;
13
+ private maxReconnectAttempts;
14
+ private reconnectDelay;
15
+ constructor(config: IEmailProviderArgs);
16
+ /**
17
+ * Initialize SMTP transporter for sending emails
18
+ */
19
+ private initializeSmtp;
20
+ /**
21
+ * Connect to IMAP server and start listening for new emails
22
+ */
23
+ connect(): Promise<void>;
24
+ /**
25
+ * Handle disconnection and attempt reconnection
26
+ */
27
+ private handleDisconnect;
28
+ /**
29
+ * Start IMAP IDLE listener for real-time email notifications
30
+ */
31
+ private startIdleListener;
32
+ /**
33
+ * Fetch new emails from a sequence range
34
+ */
35
+ private fetchNewEmails;
36
+ /**
37
+ * Parse a mailparser ParsedMail object to EmailBotContext
38
+ */
39
+ private parseEmailToContext;
40
+ /**
41
+ * Extract single address from AddressObject
42
+ */
43
+ private extractAddress;
44
+ /**
45
+ * Extract array of addresses from AddressObject
46
+ */
47
+ private extractAddresses;
48
+ /**
49
+ * Send an email via SMTP
50
+ */
51
+ sendEmail(to: string, subject: string, text: string, options?: EmailSendOptions): Promise<{
52
+ messageId: string;
53
+ }>;
54
+ /**
55
+ * Reply to an existing email thread
56
+ */
57
+ replyToEmail(originalContext: EmailBotContext, text: string, options?: Omit<EmailSendOptions, 'inReplyTo' | 'references'>): Promise<{
58
+ messageId: string;
59
+ }>;
60
+ /**
61
+ * Download attachment content
62
+ */
63
+ downloadAttachment(ctx: EmailBotContext, attachmentIndex: number): Promise<Buffer | null>;
64
+ /**
65
+ * Disconnect from IMAP server
66
+ */
67
+ disconnect(): Promise<void>;
68
+ /**
69
+ * Check if connected to IMAP server
70
+ */
71
+ isImapConnected(): boolean;
72
+ /**
73
+ * Verify SMTP connection
74
+ */
75
+ verifySmtp(): Promise<boolean>;
76
+ }
77
+ //# sourceMappingURL=core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../src/email/core.ts"],"names":[],"mappings":"AAGA,OAAO,YAAY,MAAM,aAAa,CAAA;AAGtC,OAAO,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,gBAAgB,EAAmB,MAAM,UAAU,CAAA;AAEtG;;;GAGG;AACH,qBAAa,eAAgB,SAAQ,YAAY;IAC7C,OAAO,CAAC,UAAU,CAAwB;IAC1C,OAAO,CAAC,eAAe,CAA2B;IAClD,OAAO,CAAC,MAAM,CAAoB;IAClC,OAAO,CAAC,WAAW,CAAiB;IACpC,OAAO,CAAC,iBAAiB,CAAY;IACrC,OAAO,CAAC,oBAAoB,CAAa;IACzC,OAAO,CAAC,cAAc,CAAe;gBAEzB,MAAM,EAAE,kBAAkB;IAMtC;;OAEG;IACH,OAAO,CAAC,cAAc;IAkBtB;;OAEG;IACU,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA+CrC;;OAEG;YACW,gBAAgB;IAuB9B;;OAEG;YACW,iBAAiB;IAyC/B;;OAEG;YACW,cAAc;IAqC5B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAgE3B;;OAEG;IACH,OAAO,CAAC,cAAc;IAetB;;OAEG;IACH,OAAO,CAAC,gBAAgB;IAmBxB;;OAEG;IACU,SAAS,CAClB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,gBAAgB,GAC3B,OAAO,CAAC;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IAuDjC;;OAEG;IACU,YAAY,CACrB,eAAe,EAAE,eAAe,EAChC,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,WAAW,GAAG,YAAY,CAAC,GAC7D,OAAO,CAAC;QAAE,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IAuBjC;;OAEG;IACU,kBAAkB,CAAC,GAAG,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAetG;;OAEG;IACU,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAoBxC;;OAEG;IACI,eAAe,IAAI,OAAO;IAIjC;;OAEG;IACU,UAAU,IAAI,OAAO,CAAC,OAAO,CAAC;CAU9C"}
@@ -0,0 +1,92 @@
1
+ import { ProviderClass } from '@builderbot/bot';
2
+ import type { BotContext, SendOptions } from '@builderbot/bot/dist/types';
3
+ import { EmailCoreVendor } from './core';
4
+ import type { IEmailProviderArgs, EmailBotContext, EmailSendOptions } from '../types';
5
+ /**
6
+ * Email Provider for BuilderBot
7
+ * Supports receiving emails via IMAP (with IDLE) and sending via SMTP
8
+ * @extends ProviderClass
9
+ */
10
+ declare class EmailProvider extends ProviderClass<EmailCoreVendor> {
11
+ globalVendorArgs: IEmailProviderArgs;
12
+ constructor(args: IEmailProviderArgs);
13
+ /**
14
+ * Initialize the email vendor (IMAP/SMTP connections)
15
+ */
16
+ protected initVendor(): Promise<EmailCoreVendor>;
17
+ /**
18
+ * Called before HTTP server initialization
19
+ */
20
+ protected beforeHttpServerInit(): void;
21
+ /**
22
+ * Called after HTTP server initialization
23
+ */
24
+ protected afterHttpServerInit(): void;
25
+ /**
26
+ * Index home endpoint
27
+ */
28
+ private indexHome;
29
+ /**
30
+ * Webhook handler for external email notifications (optional)
31
+ */
32
+ private webhookHandler;
33
+ /**
34
+ * Map vendor events to provider events
35
+ */
36
+ protected busEvents: () => {
37
+ event: string;
38
+ func: (payload: any) => void;
39
+ }[];
40
+ /**
41
+ * Send an email message
42
+ * @param to - Recipient email address
43
+ * @param message - Email body content
44
+ * @param options - Send options (subject, attachments, etc.)
45
+ */
46
+ sendMessage(to: string, message: string, options?: SendOptions & EmailSendOptions): Promise<any>;
47
+ /**
48
+ * Send an email with media attachment
49
+ * @param to - Recipient email address
50
+ * @param message - Email body content
51
+ * @param mediaPath - Path to media file
52
+ * @param options - Additional email options
53
+ */
54
+ sendMedia(to: string, message: string, mediaPath: string, options?: EmailSendOptions): Promise<any>;
55
+ /**
56
+ * Reply to an existing email thread
57
+ * @param ctx - Original email context
58
+ * @param message - Reply message content
59
+ * @param options - Additional email options
60
+ */
61
+ reply(ctx: EmailBotContext, message: string, options?: Omit<EmailSendOptions, 'inReplyTo' | 'references'>): Promise<any>;
62
+ /**
63
+ * Save an attachment from an email to disk
64
+ * @param ctx - Email context containing attachments
65
+ * @param options - Save options (path, attachment index)
66
+ */
67
+ saveFile(ctx: Partial<EmailBotContext & BotContext>, options?: {
68
+ path?: string;
69
+ attachmentIndex?: number;
70
+ }): Promise<string>;
71
+ /**
72
+ * Get all attachments from an email
73
+ * @param ctx - Email context
74
+ */
75
+ getAttachments(ctx: EmailBotContext): import("../types").EmailAttachment[];
76
+ /**
77
+ * Check if the email is a reply
78
+ * @param ctx - Email context
79
+ */
80
+ isReply(ctx: EmailBotContext): boolean;
81
+ /**
82
+ * Get the thread ID from an email
83
+ * @param ctx - Email context
84
+ */
85
+ getThreadId(ctx: EmailBotContext): string | undefined;
86
+ /**
87
+ * Disconnect the email provider
88
+ */
89
+ disconnect(): Promise<void>;
90
+ }
91
+ export { EmailProvider };
92
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/email/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC/C,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAA;AAKzE,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAA;AACxC,OAAO,KAAK,EAAE,kBAAkB,EAAE,eAAe,EAAE,gBAAgB,EA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