@stacksjs/email 0.70.258 → 0.70.259
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/dist/css-inliner.js +4 -170
- package/dist/drivers/base.js +1 -128
- package/dist/drivers/capture.js +1 -30
- package/dist/drivers/index.js +1 -6
- package/dist/drivers/log.js +3 -80
- package/dist/drivers/mailgun.js +1 -127
- package/dist/drivers/mailtrap.js +1 -129
- package/dist/drivers/sendgrid.js +1 -136
- package/dist/drivers/ses.js +4 -110
- package/dist/drivers/smtp.js +5 -224
- package/dist/email.js +1 -198
- package/dist/idempotency.js +1 -56
- package/dist/index.js +1 -21
- package/dist/mailable.js +1 -145
- package/dist/mime-preview.js +4 -69
- package/dist/mime.js +3 -89
- package/dist/preview-ui.js +18 -45
- package/dist/preview.js +1 -97
- package/dist/sdk/index.js +1 -221
- package/dist/suppression.js +1 -104
- package/dist/template.js +4 -169
- package/dist/unsubscribe.js +1 -65
- package/dist/utils/config.js +1 -3
- package/dist/validation.js +1 -22
- package/dist/webhook-dedup.js +1 -33
- package/dist/webhook-events.js +1 -37
- package/dist/webhook-handlers.js +1 -264
- package/dist/webhook-signatures.js +2 -148
- package/package.json +15 -8
package/dist/drivers/mailtrap.js
CHANGED
|
@@ -1,129 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { config } from "@stacksjs/config";
|
|
3
|
-
import { log } from "@stacksjs/logging";
|
|
4
|
-
import { template } from "../template";
|
|
5
|
-
import { filterStringHeaders } from "../validation";
|
|
6
|
-
import { BaseEmailDriver } from "./base";
|
|
7
|
-
|
|
8
|
-
export class MailtrapDriver extends BaseEmailDriver {
|
|
9
|
-
name = "mailtrap";
|
|
10
|
-
host = null;
|
|
11
|
-
token = null;
|
|
12
|
-
inboxId = null;
|
|
13
|
-
getConfig() {
|
|
14
|
-
if (this.host === null || this.token === null || this.inboxId === null) {
|
|
15
|
-
this.host = config.services.mailtrap?.host ?? "https://sandbox.api.mailtrap.io/api/send";
|
|
16
|
-
this.token = config.services.mailtrap?.token ?? "";
|
|
17
|
-
this.inboxId = config.services.mailtrap?.inboxId ? Number(config.services.mailtrap.inboxId) : void 0;
|
|
18
|
-
}
|
|
19
|
-
return {
|
|
20
|
-
host: this.host,
|
|
21
|
-
token: this.token,
|
|
22
|
-
inboxId: this.inboxId
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
async send(message, options) {
|
|
26
|
-
const { inboxId } = this.getConfig(), logContext = {
|
|
27
|
-
provider: this.name,
|
|
28
|
-
to: message.to,
|
|
29
|
-
subject: message.subject,
|
|
30
|
-
inboxId
|
|
31
|
-
};
|
|
32
|
-
log.info("Sending email via Mailtrap...", logContext);
|
|
33
|
-
try {
|
|
34
|
-
this.validateMessage(message);
|
|
35
|
-
let templ;
|
|
36
|
-
if (message.template)
|
|
37
|
-
templ = await template(message.template, options);
|
|
38
|
-
const htmlContent = templ?.html || message.html, replyTo = this.firstMailtrapAddress(message.replyTo), customHeaders = filterStringHeaders(message.headers), mailtrapPayload = {
|
|
39
|
-
from: {
|
|
40
|
-
email: message.from?.address || config.email.from?.address || "",
|
|
41
|
-
name: message.from?.name || config.email.from?.name
|
|
42
|
-
},
|
|
43
|
-
to: this.formatMailtrapAddresses(message.to),
|
|
44
|
-
...message.cc && { cc: this.formatMailtrapAddresses(message.cc) },
|
|
45
|
-
...message.bcc && { bcc: this.formatMailtrapAddresses(message.bcc) },
|
|
46
|
-
...replyTo ? { reply_to: replyTo } : {},
|
|
47
|
-
...customHeaders ? { headers: customHeaders } : {},
|
|
48
|
-
subject: message.subject,
|
|
49
|
-
...htmlContent && { html: htmlContent },
|
|
50
|
-
...message.text && { text: message.text },
|
|
51
|
-
...message.attachments && {
|
|
52
|
-
attachments: message.attachments.map((attachment) => ({
|
|
53
|
-
filename: attachment.filename,
|
|
54
|
-
content: typeof attachment.content === "string" ? attachment.content : this.arrayBufferToBase64(attachment.content),
|
|
55
|
-
type: attachment.contentType || "application/octet-stream"
|
|
56
|
-
}))
|
|
57
|
-
}
|
|
58
|
-
}, response = await this.sendWithRetry(mailtrapPayload);
|
|
59
|
-
return this.handleSuccess(message, response.message_ids?.[0]);
|
|
60
|
-
} catch (error) {
|
|
61
|
-
return this.handleError(error, message);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
formatMailtrapAddresses(addresses) {
|
|
65
|
-
if (!addresses)
|
|
66
|
-
return [];
|
|
67
|
-
if (typeof addresses === "string")
|
|
68
|
-
return [{ email: addresses }];
|
|
69
|
-
return addresses.map((addr) => {
|
|
70
|
-
if (typeof addr === "string")
|
|
71
|
-
return { email: addr };
|
|
72
|
-
return { email: addr.address, ...addr.name && { name: addr.name } };
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
firstMailtrapAddress(value) {
|
|
76
|
-
if (!value)
|
|
77
|
-
return;
|
|
78
|
-
if (typeof value === "string")
|
|
79
|
-
return { email: value };
|
|
80
|
-
if (Array.isArray(value)) {
|
|
81
|
-
const first = value[0];
|
|
82
|
-
if (first === void 0)
|
|
83
|
-
return;
|
|
84
|
-
if (typeof first === "string")
|
|
85
|
-
return { email: first };
|
|
86
|
-
return { email: first.address, ...first.name && { name: first.name } };
|
|
87
|
-
}
|
|
88
|
-
return { email: value.address, ...value.name && { name: value.name } };
|
|
89
|
-
}
|
|
90
|
-
arrayBufferToBase64(buffer) {
|
|
91
|
-
let binary = "";
|
|
92
|
-
const bytes = new Uint8Array(buffer), len = bytes.byteLength;
|
|
93
|
-
for (let i = 0;i < len; i++)
|
|
94
|
-
binary += String.fromCharCode(bytes[i] ?? 0);
|
|
95
|
-
return typeof btoa === "function" ? btoa(binary) : Buffer.from(binary).toString("base64");
|
|
96
|
-
}
|
|
97
|
-
async sendWithRetry(payload, attempt = 1) {
|
|
98
|
-
const { host, token, inboxId } = this.getConfig();
|
|
99
|
-
if (!inboxId)
|
|
100
|
-
throw Error("Mailtrap inbox ID is required but not provided. Please set MAILTRAP_INBOX_ID in your environment variables.");
|
|
101
|
-
const endpoint = `${host}/${inboxId}`;
|
|
102
|
-
try {
|
|
103
|
-
const response = await fetch(endpoint, {
|
|
104
|
-
method: "POST",
|
|
105
|
-
headers: {
|
|
106
|
-
Authorization: `Bearer ${token}`,
|
|
107
|
-
"Content-Type": "application/json"
|
|
108
|
-
},
|
|
109
|
-
body: JSON.stringify(payload)
|
|
110
|
-
});
|
|
111
|
-
if (!response.ok) {
|
|
112
|
-
const errorData = await response.json();
|
|
113
|
-
throw Error(`Mailtrap API error: ${response.status} - ${JSON.stringify(errorData)}`);
|
|
114
|
-
}
|
|
115
|
-
const data = await response.json();
|
|
116
|
-
log.info(`[${this.name}] Email sent successfully`, { attempt, messageId: data.message_ids?.[0] });
|
|
117
|
-
return data;
|
|
118
|
-
} catch (error) {
|
|
119
|
-
if (attempt < (config.services.mailtrap?.maxRetries ?? 3)) {
|
|
120
|
-
const retryTimeout = config.services.mailtrap?.retryTimeout ?? 1000;
|
|
121
|
-
log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${config.services.mailtrap?.maxRetries ?? 3})`);
|
|
122
|
-
await new Promise((resolve) => setTimeout(resolve, retryTimeout));
|
|
123
|
-
return this.sendWithRetry(payload, attempt + 1);
|
|
124
|
-
}
|
|
125
|
-
throw error;
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
export default MailtrapDriver;
|
|
1
|
+
import{Buffer}from"node:buffer";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{template}from"../template";import{filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";export class MailtrapDriver extends BaseEmailDriver{name="mailtrap";host=null;token=null;inboxId=null;getConfig(){if(this.host===null||this.token===null||this.inboxId===null){this.host=config.services.mailtrap?.host??"https://sandbox.api.mailtrap.io/api/send";this.token=config.services.mailtrap?.token??"";this.inboxId=config.services.mailtrap?.inboxId?Number(config.services.mailtrap.inboxId):void 0}return{host:this.host,token:this.token,inboxId:this.inboxId}}async send(message,options){const{inboxId}=this.getConfig(),logContext={provider:this.name,to:message.to,subject:message.subject,inboxId};log.info("Sending email via Mailtrap...",logContext);try{this.validateMessage(message);let templ;if(message.template)templ=await template(message.template,options);const htmlContent=templ?.html||message.html,replyTo=this.firstMailtrapAddress(message.replyTo),customHeaders=filterStringHeaders(message.headers),mailtrapPayload={from:{email:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name},to:this.formatMailtrapAddresses(message.to),...message.cc&&{cc:this.formatMailtrapAddresses(message.cc)},...message.bcc&&{bcc:this.formatMailtrapAddresses(message.bcc)},...replyTo?{reply_to:replyTo}:{},...customHeaders?{headers:customHeaders}:{},subject:message.subject,...htmlContent&&{html:htmlContent},...message.text&&{text:message.text},...message.attachments&&{attachments:message.attachments.map((attachment)=>({filename:attachment.filename,content:typeof attachment.content==="string"?attachment.content:this.arrayBufferToBase64(attachment.content),type:attachment.contentType||"application/octet-stream"}))}},response=await this.sendWithRetry(mailtrapPayload);return this.handleSuccess(message,response.message_ids?.[0])}catch(error){return this.handleError(error,message)}}formatMailtrapAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[{email:addresses}];return addresses.map((addr)=>{if(typeof addr==="string")return{email:addr};return{email:addr.address,...addr.name&&{name:addr.name}}})}firstMailtrapAddress(value){if(!value)return;if(typeof value==="string")return{email:value};if(Array.isArray(value)){const first=value[0];if(first===void 0)return;if(typeof first==="string")return{email:first};return{email:first.address,...first.name&&{name:first.name}}}return{email:value.address,...value.name&&{name:value.name}}}arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer),len=bytes.byteLength;for(let i=0;i<len;i++)binary+=String.fromCharCode(bytes[i]??0);return typeof btoa==="function"?btoa(binary):Buffer.from(binary).toString("base64")}async sendWithRetry(payload,attempt=1){const{host,token,inboxId}=this.getConfig();if(!inboxId)throw Error("Mailtrap inbox ID is required but not provided. Please set MAILTRAP_INBOX_ID in your environment variables.");const endpoint=`${host}/${inboxId}`;try{const response=await fetch(endpoint,{method:"POST",headers:{Authorization:`Bearer ${token}`,"Content-Type":"application/json"},body:JSON.stringify(payload)});if(!response.ok){const errorData=await response.json();throw Error(`Mailtrap API error: ${response.status} - ${JSON.stringify(errorData)}`)}const data=await response.json();log.info(`[${this.name}] Email sent successfully`,{attempt,messageId:data.message_ids?.[0]});return data}catch(error){if(attempt<(config.services.mailtrap?.maxRetries??3)){const retryTimeout=config.services.mailtrap?.retryTimeout??1000;log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${config.services.mailtrap?.maxRetries??3})`);await new Promise((resolve)=>setTimeout(resolve,retryTimeout));return this.sendWithRetry(payload,attempt+1)}throw error}}}export default MailtrapDriver;
|
package/dist/drivers/sendgrid.js
CHANGED
|
@@ -1,136 +1 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { config } from "@stacksjs/config";
|
|
3
|
-
import { log } from "@stacksjs/logging";
|
|
4
|
-
import { template } from "../template";
|
|
5
|
-
import { filterStringHeaders } from "../validation";
|
|
6
|
-
import { BaseEmailDriver } from "./base";
|
|
7
|
-
|
|
8
|
-
export class SendGridDriver extends BaseEmailDriver {
|
|
9
|
-
name = "sendgrid";
|
|
10
|
-
apiKey = null;
|
|
11
|
-
getApiKey() {
|
|
12
|
-
if (!this.apiKey)
|
|
13
|
-
this.apiKey = config.services.sendgrid?.apiKey ?? "";
|
|
14
|
-
return this.apiKey;
|
|
15
|
-
}
|
|
16
|
-
async send(message, options) {
|
|
17
|
-
const logContext = {
|
|
18
|
-
provider: this.name,
|
|
19
|
-
to: message.to,
|
|
20
|
-
subject: message.subject
|
|
21
|
-
};
|
|
22
|
-
log.info("Sending email via SendGrid...", logContext);
|
|
23
|
-
try {
|
|
24
|
-
this.validateMessage(message);
|
|
25
|
-
let htmlContent;
|
|
26
|
-
if (message.template) {
|
|
27
|
-
const templ = await template(message.template, options);
|
|
28
|
-
if (templ && "html" in templ)
|
|
29
|
-
htmlContent = templ.html;
|
|
30
|
-
}
|
|
31
|
-
const finalHtml = htmlContent || message.html, content = [];
|
|
32
|
-
if (finalHtml)
|
|
33
|
-
content.push({
|
|
34
|
-
type: "text/html",
|
|
35
|
-
value: finalHtml
|
|
36
|
-
});
|
|
37
|
-
if (message.text)
|
|
38
|
-
content.push({
|
|
39
|
-
type: "text/plain",
|
|
40
|
-
value: message.text
|
|
41
|
-
});
|
|
42
|
-
if (content.length === 0)
|
|
43
|
-
throw Error("Email must have either HTML or text content");
|
|
44
|
-
const replyTo = this.firstSendGridAddress(message.replyTo), customHeaders = filterStringHeaders(message.headers), sendgridPayload = {
|
|
45
|
-
personalizations: [
|
|
46
|
-
{
|
|
47
|
-
to: this.formatSendGridAddresses(message.to),
|
|
48
|
-
...message.cc && { cc: this.formatSendGridAddresses(message.cc) },
|
|
49
|
-
...message.bcc && { bcc: this.formatSendGridAddresses(message.bcc) },
|
|
50
|
-
subject: message.subject
|
|
51
|
-
}
|
|
52
|
-
],
|
|
53
|
-
from: {
|
|
54
|
-
email: message.from?.address || config.email.from?.address || "",
|
|
55
|
-
name: message.from?.name || config.email.from?.name
|
|
56
|
-
},
|
|
57
|
-
...replyTo ? { reply_to: replyTo } : {},
|
|
58
|
-
...customHeaders ? { headers: customHeaders } : {},
|
|
59
|
-
content,
|
|
60
|
-
...message.attachments && {
|
|
61
|
-
attachments: message.attachments.map((attachment) => ({
|
|
62
|
-
filename: attachment.filename,
|
|
63
|
-
content: typeof attachment.content === "string" ? attachment.content : this.arrayBufferToBase64(attachment.content),
|
|
64
|
-
type: attachment.contentType,
|
|
65
|
-
disposition: "attachment"
|
|
66
|
-
}))
|
|
67
|
-
}
|
|
68
|
-
}, response = await this.sendWithRetry(sendgridPayload);
|
|
69
|
-
return this.handleSuccess(message, response.headers?.get("x-message-id") ?? void 0);
|
|
70
|
-
} catch (error) {
|
|
71
|
-
return this.handleError(error, message);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
formatSendGridAddresses(addresses) {
|
|
75
|
-
if (!addresses)
|
|
76
|
-
return [];
|
|
77
|
-
if (typeof addresses === "string")
|
|
78
|
-
return [{ email: addresses }];
|
|
79
|
-
return addresses.map((addr) => {
|
|
80
|
-
if (typeof addr === "string")
|
|
81
|
-
return { email: addr };
|
|
82
|
-
return { email: addr.address, ...addr.name && { name: addr.name } };
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
firstSendGridAddress(value) {
|
|
86
|
-
if (!value)
|
|
87
|
-
return;
|
|
88
|
-
if (typeof value === "string")
|
|
89
|
-
return { email: value };
|
|
90
|
-
if (Array.isArray(value)) {
|
|
91
|
-
const first = value[0];
|
|
92
|
-
if (first === void 0)
|
|
93
|
-
return;
|
|
94
|
-
if (typeof first === "string")
|
|
95
|
-
return { email: first };
|
|
96
|
-
return { email: first.address, ...first.name && { name: first.name } };
|
|
97
|
-
}
|
|
98
|
-
return { email: value.address, ...value.name && { name: value.name } };
|
|
99
|
-
}
|
|
100
|
-
arrayBufferToBase64(buffer) {
|
|
101
|
-
let binary = "";
|
|
102
|
-
const bytes = new Uint8Array(buffer), len = bytes.byteLength;
|
|
103
|
-
for (let i = 0;i < len; i++)
|
|
104
|
-
binary += String.fromCharCode(bytes[i] ?? 0);
|
|
105
|
-
return typeof btoa === "function" ? btoa(binary) : Buffer.from(binary).toString("base64");
|
|
106
|
-
}
|
|
107
|
-
async sendWithRetry(payload, attempt = 1) {
|
|
108
|
-
try {
|
|
109
|
-
const response = await fetch("https://api.sendgrid.com/v3/mail/send", {
|
|
110
|
-
method: "POST",
|
|
111
|
-
headers: {
|
|
112
|
-
Authorization: `Bearer ${this.getApiKey()}`,
|
|
113
|
-
"Content-Type": "application/json"
|
|
114
|
-
},
|
|
115
|
-
body: JSON.stringify(payload)
|
|
116
|
-
});
|
|
117
|
-
if (!response.ok) {
|
|
118
|
-
const errorData = await response.json(), err = Error(`SendGrid API error: ${response.status} - ${JSON.stringify(errorData)}`);
|
|
119
|
-
err.status = response.status;
|
|
120
|
-
throw err;
|
|
121
|
-
}
|
|
122
|
-
log.info(`[${this.name}] Email sent successfully`, { attempt });
|
|
123
|
-
return response;
|
|
124
|
-
} catch (error) {
|
|
125
|
-
const status = error?.status;
|
|
126
|
-
if (!(typeof status === "number" && status >= 400 && status < 500 && status !== 429) && attempt < (config.services.sendgrid?.maxRetries ?? 3)) {
|
|
127
|
-
const retryTimeout = config.services.sendgrid?.retryTimeout ?? 1000;
|
|
128
|
-
log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${config.services.sendgrid?.maxRetries ?? 3})`);
|
|
129
|
-
await new Promise((resolve) => setTimeout(resolve, retryTimeout));
|
|
130
|
-
return this.sendWithRetry(payload, attempt + 1);
|
|
131
|
-
}
|
|
132
|
-
throw error;
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
export default SendGridDriver;
|
|
1
|
+
import{Buffer}from"node:buffer";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{template}from"../template";import{filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";export class SendGridDriver extends BaseEmailDriver{name="sendgrid";apiKey=null;getApiKey(){if(!this.apiKey)this.apiKey=config.services.sendgrid?.apiKey??"";return this.apiKey}async send(message,options){const logContext={provider:this.name,to:message.to,subject:message.subject};log.info("Sending email via SendGrid...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await template(message.template,options);if(templ&&"html"in templ)htmlContent=templ.html}const finalHtml=htmlContent||message.html,content=[];if(finalHtml)content.push({type:"text/html",value:finalHtml});if(message.text)content.push({type:"text/plain",value:message.text});if(content.length===0)throw Error("Email must have either HTML or text content");const replyTo=this.firstSendGridAddress(message.replyTo),customHeaders=filterStringHeaders(message.headers),sendgridPayload={personalizations:[{to:this.formatSendGridAddresses(message.to),...message.cc&&{cc:this.formatSendGridAddresses(message.cc)},...message.bcc&&{bcc:this.formatSendGridAddresses(message.bcc)},subject:message.subject}],from:{email:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name},...replyTo?{reply_to:replyTo}:{},...customHeaders?{headers:customHeaders}:{},content,...message.attachments&&{attachments:message.attachments.map((attachment)=>({filename:attachment.filename,content:typeof attachment.content==="string"?attachment.content:this.arrayBufferToBase64(attachment.content),type:attachment.contentType,disposition:"attachment"}))}},response=await this.sendWithRetry(sendgridPayload);return this.handleSuccess(message,response.headers?.get("x-message-id")??void 0)}catch(error){return this.handleError(error,message)}}formatSendGridAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[{email:addresses}];return addresses.map((addr)=>{if(typeof addr==="string")return{email:addr};return{email:addr.address,...addr.name&&{name:addr.name}}})}firstSendGridAddress(value){if(!value)return;if(typeof value==="string")return{email:value};if(Array.isArray(value)){const first=value[0];if(first===void 0)return;if(typeof first==="string")return{email:first};return{email:first.address,...first.name&&{name:first.name}}}return{email:value.address,...value.name&&{name:value.name}}}arrayBufferToBase64(buffer){let binary="";const bytes=new Uint8Array(buffer),len=bytes.byteLength;for(let i=0;i<len;i++)binary+=String.fromCharCode(bytes[i]??0);return typeof btoa==="function"?btoa(binary):Buffer.from(binary).toString("base64")}async sendWithRetry(payload,attempt=1){try{const response=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{Authorization:`Bearer ${this.getApiKey()}`,"Content-Type":"application/json"},body:JSON.stringify(payload)});if(!response.ok){const errorData=await response.json(),err=Error(`SendGrid API error: ${response.status} - ${JSON.stringify(errorData)}`);err.status=response.status;throw err}log.info(`[${this.name}] Email sent successfully`,{attempt});return response}catch(error){const status=error?.status;if(!(typeof status==="number"&&status>=400&&status<500&&status!==429)&&attempt<(config.services.sendgrid?.maxRetries??3)){const retryTimeout=config.services.sendgrid?.retryTimeout??1000;log.warn(`[${this.name}] Email send failed, retrying (${attempt}/${config.services.sendgrid?.maxRetries??3})`);await new Promise((resolve)=>setTimeout(resolve,retryTimeout));return this.sendWithRetry(payload,attempt+1)}throw error}}}export default SendGridDriver;
|
package/dist/drivers/ses.js
CHANGED
|
@@ -1,113 +1,7 @@
|
|
|
1
|
-
import { config } from "
|
|
2
|
-
import { SESClient } from "@stacksjs/ts-cloud";
|
|
3
|
-
import { template } from "../template";
|
|
4
|
-
import { buildMimeMessage } from "../mime";
|
|
5
|
-
import { filterStringHeaders } from "../validation";
|
|
6
|
-
import { BaseEmailDriver } from "./base";
|
|
1
|
+
import{config}from"@stacksjs/config";import{SESClient}from"@stacksjs/ts-cloud";import{template}from"../template";import{buildMimeMessage}from"../mime";import{filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";export class SESDriver extends BaseEmailDriver{name="ses";client=null;getClient(){if(!this.client){const sesConfig=config?.services?.ses,explicit=sesConfig?.credentials,hasExplicit=!!(explicit?.accessKeyId&&explicit?.secretAccessKey);this.client=new SESClient(sesConfig?.region||"us-east-1",hasExplicit?{accessKeyId:explicit.accessKeyId,secretAccessKey:explicit.secretAccessKey,sessionToken:explicit.sessionToken}:void 0)}return this.client}async send(message,options){try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await template(message.template,options);if(templ&&"html"in templ)htmlContent=templ.html}const finalHtml=htmlContent||message.html;if(!finalHtml&&!message.text)throw Error("Email must have either HTML or text content");const fromAddress=this.formatSourceAddress({address:message.from?.address||config.email.from?.address||"",name:message.from?.name||config.email.from?.name}),toAddresses=this.formatAddresses(message.to),ccAddresses=this.formatAddresses(message.cc),bccAddresses=this.formatAddresses(message.bcc),replyToAddresses=message.replyTo?this.formatAddressList(message.replyTo):[],customHeaders=filterStringHeaders(message.headers);if(!!(message.attachments&&message.attachments.length>0)||!!customHeaders){const raw=buildMimeMessage({from:fromAddress,to:toAddresses.join(", "),cc:ccAddresses.length>0?ccAddresses.join(", "):void 0,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):void 0,customHeaders,subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain}),result=await this.getClient().sendRawEmail({source:fromAddress,destinations:[...toAddresses,...ccAddresses,...bccAddresses],rawMessage:raw});return this.handleSuccess(message,result.MessageId)}const body={};if(finalHtml)body.Html={Charset:config.email.charset||"UTF-8",Data:finalHtml};if(message.text)body.Text={Charset:config.email.charset||"UTF-8",Data:message.text};const result=await this.getClient().sendEmail({FromEmailAddress:fromAddress,Destination:{ToAddresses:toAddresses,CcAddresses:ccAddresses,BccAddresses:bccAddresses},...replyToAddresses.length>0?{ReplyToAddresses:replyToAddresses}:{},Content:{Simple:{Subject:{Charset:config.email.charset||"UTF-8",Data:message.subject},Body:body}}});return this.handleSuccess(message,result.MessageId)}catch(error){return this.handleError(this.enrichSesError(error),message)}}formatSourceAddress(from){if(!from.name)return from.address;return`${/[",()<>[\]:;@\\]/.test(from.name)?`"${from.name.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`:from.name} <${from.address}>`}enrichSesError(error){const err=error instanceof Error?error:Error(String(error)),text=`${err.message} ${err.name??""}`.toLowerCase(),region=config?.services?.ses?.region||"us-east-1";if(text.includes("email address is not verified")||text.includes("not authorized to send")||text.includes("messagerejected")&&text.includes("verified")){err.message=`${err.message}
|
|
7
2
|
|
|
8
|
-
|
|
9
|
-
name = "ses";
|
|
10
|
-
client = null;
|
|
11
|
-
getClient() {
|
|
12
|
-
if (!this.client) {
|
|
13
|
-
const sesConfig = config?.services?.ses, explicit = sesConfig?.credentials, hasExplicit = !!(explicit?.accessKeyId && explicit?.secretAccessKey);
|
|
14
|
-
this.client = new SESClient(sesConfig?.region || "us-east-1", hasExplicit ? {
|
|
15
|
-
accessKeyId: explicit.accessKeyId,
|
|
16
|
-
secretAccessKey: explicit.secretAccessKey,
|
|
17
|
-
sessionToken: explicit.sessionToken
|
|
18
|
-
} : void 0);
|
|
19
|
-
}
|
|
20
|
-
return this.client;
|
|
21
|
-
}
|
|
22
|
-
async send(message, options) {
|
|
23
|
-
try {
|
|
24
|
-
this.validateMessage(message);
|
|
25
|
-
let htmlContent;
|
|
26
|
-
if (message.template) {
|
|
27
|
-
const templ = await template(message.template, options);
|
|
28
|
-
if (templ && "html" in templ)
|
|
29
|
-
htmlContent = templ.html;
|
|
30
|
-
}
|
|
31
|
-
const finalHtml = htmlContent || message.html;
|
|
32
|
-
if (!finalHtml && !message.text)
|
|
33
|
-
throw Error("Email must have either HTML or text content");
|
|
34
|
-
const fromAddress = this.formatSourceAddress({
|
|
35
|
-
address: message.from?.address || config.email.from?.address || "",
|
|
36
|
-
name: message.from?.name || config.email.from?.name
|
|
37
|
-
}), toAddresses = this.formatAddresses(message.to), ccAddresses = this.formatAddresses(message.cc), bccAddresses = this.formatAddresses(message.bcc), replyToAddresses = message.replyTo ? this.formatAddressList(message.replyTo) : [], customHeaders = filterStringHeaders(message.headers);
|
|
38
|
-
if (!!(message.attachments && message.attachments.length > 0) || !!customHeaders) {
|
|
39
|
-
const raw = buildMimeMessage({
|
|
40
|
-
from: fromAddress,
|
|
41
|
-
to: toAddresses.join(", "),
|
|
42
|
-
cc: ccAddresses.length > 0 ? ccAddresses.join(", ") : void 0,
|
|
43
|
-
replyTo: replyToAddresses.length > 0 ? replyToAddresses.join(", ") : void 0,
|
|
44
|
-
customHeaders,
|
|
45
|
-
subject: message.subject,
|
|
46
|
-
text: message.text,
|
|
47
|
-
html: finalHtml,
|
|
48
|
-
attachments: message.attachments,
|
|
49
|
-
messageIdDomain: config.email.domain
|
|
50
|
-
}), result = await this.getClient().sendRawEmail({
|
|
51
|
-
source: fromAddress,
|
|
52
|
-
destinations: [...toAddresses, ...ccAddresses, ...bccAddresses],
|
|
53
|
-
rawMessage: raw
|
|
54
|
-
});
|
|
55
|
-
return this.handleSuccess(message, result.MessageId);
|
|
56
|
-
}
|
|
57
|
-
const body = {};
|
|
58
|
-
if (finalHtml)
|
|
59
|
-
body.Html = { Charset: config.email.charset || "UTF-8", Data: finalHtml };
|
|
60
|
-
if (message.text)
|
|
61
|
-
body.Text = { Charset: config.email.charset || "UTF-8", Data: message.text };
|
|
62
|
-
const result = await this.getClient().sendEmail({
|
|
63
|
-
FromEmailAddress: fromAddress,
|
|
64
|
-
Destination: {
|
|
65
|
-
ToAddresses: toAddresses,
|
|
66
|
-
CcAddresses: ccAddresses,
|
|
67
|
-
BccAddresses: bccAddresses
|
|
68
|
-
},
|
|
69
|
-
...replyToAddresses.length > 0 ? { ReplyToAddresses: replyToAddresses } : {},
|
|
70
|
-
Content: {
|
|
71
|
-
Simple: {
|
|
72
|
-
Subject: {
|
|
73
|
-
Charset: config.email.charset || "UTF-8",
|
|
74
|
-
Data: message.subject
|
|
75
|
-
},
|
|
76
|
-
Body: body
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
});
|
|
80
|
-
return this.handleSuccess(message, result.MessageId);
|
|
81
|
-
} catch (error) {
|
|
82
|
-
return this.handleError(this.enrichSesError(error), message);
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
formatSourceAddress(from) {
|
|
86
|
-
if (!from.name)
|
|
87
|
-
return from.address;
|
|
88
|
-
return `${/[",()<>[\]:;@\\]/.test(from.name) ? `"${from.name.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"` : from.name} <${from.address}>`;
|
|
89
|
-
}
|
|
90
|
-
enrichSesError(error) {
|
|
91
|
-
const err = error instanceof Error ? error : Error(String(error)), text = `${err.message} ${err.name ?? ""}`.toLowerCase(), region = config?.services?.ses?.region || "us-east-1";
|
|
92
|
-
if (text.includes("email address is not verified") || text.includes("not authorized to send") || text.includes("messagerejected") && text.includes("verified")) {
|
|
93
|
-
err.message = `${err.message}
|
|
3
|
+
SES sandbox restriction: the From and (in sandbox) every To address must be verified. Verify identities in the SES console under "Verified identities" (region: ${region}), or request production access to lift the recipient restriction.`;return err}if(text.includes("signaturedoesnotmatch")||text.includes("invalidclienttokenid")||text.includes("unable to locate credentials")||text.includes("the security token included in the request is invalid")){err.message=`${err.message}
|
|
94
4
|
|
|
95
|
-
SES
|
|
96
|
-
return err;
|
|
97
|
-
}
|
|
98
|
-
if (text.includes("signaturedoesnotmatch") || text.includes("invalidclienttokenid") || text.includes("unable to locate credentials") || text.includes("the security token included in the request is invalid")) {
|
|
99
|
-
err.message = `${err.message}
|
|
5
|
+
SES authentication failed. Check AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY (or services.ses.credentials), and confirm the IAM principal has \`ses:SendEmail\` permission for the From identity.`;return err}if(text.includes("could not be reached")||text.includes("econnrefused")||text.includes("enotfound")){err.message=`${err.message}
|
|
100
6
|
|
|
101
|
-
SES
|
|
102
|
-
return err;
|
|
103
|
-
}
|
|
104
|
-
if (text.includes("could not be reached") || text.includes("econnrefused") || text.includes("enotfound")) {
|
|
105
|
-
err.message = `${err.message}
|
|
106
|
-
|
|
107
|
-
SES endpoint unreachable. The configured region (\`${region}\`) must match the region where the From identity is verified.`;
|
|
108
|
-
return err;
|
|
109
|
-
}
|
|
110
|
-
return err;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
export default SESDriver;
|
|
7
|
+
SES endpoint unreachable. The configured region (\`${region}\`) must match the region where the From identity is verified.`;return err}return err}}export default SESDriver;
|
package/dist/drivers/smtp.js
CHANGED
|
@@ -1,225 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import * as net from "node:net";
|
|
5
|
-
import { config } from "@stacksjs/config";
|
|
6
|
-
import { log } from "@stacksjs/logging";
|
|
7
|
-
import { template } from "../template";
|
|
8
|
-
import { buildMimeMessage } from "../mime";
|
|
9
|
-
import { ENVELOPE_ADDRESS, filterStringHeaders } from "../validation";
|
|
10
|
-
import { BaseEmailDriver } from "./base";
|
|
11
|
-
function assertEnvelopeAddress(addr, role) {
|
|
12
|
-
if (typeof addr !== "string" || !ENVELOPE_ADDRESS.test(addr))
|
|
13
|
-
throw Error(`[smtp] Refusing to send: ${role} envelope address contains forbidden characters or is malformed: ${JSON.stringify(addr)}`);
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export class SMTPDriver extends BaseEmailDriver {
|
|
17
|
-
static SMTP_TIMEOUT = 30000;
|
|
18
|
-
name = "smtp";
|
|
19
|
-
getConfig() {
|
|
20
|
-
const smtp = config.services?.smtp, env = process.env, host = smtp?.host || env.MAIL_HOST || "127.0.0.1", port = smtp?.port || (env.MAIL_PORT ? Number(env.MAIL_PORT) : void 0) || 587, fromAddress = typeof config.email?.from?.address === "string" ? config.email.from.address : "", username = smtp?.username || env.MAIL_USERNAME || fromAddress || "", localPart = (username.includes("@") ? username.split("@")[0] : username).toUpperCase().replace(/[^A-Z0-9]/g, "_"), password = smtp?.password || env.MAIL_PASSWORD || (localPart ? env[`MAIL_PASSWORD_${localPart}`] : void 0) || "", rawEncryption = smtp?.encryption ?? env.MAIL_ENCRYPTION ?? null;
|
|
21
|
-
return {
|
|
22
|
-
host,
|
|
23
|
-
port,
|
|
24
|
-
username,
|
|
25
|
-
password,
|
|
26
|
-
encryption: rawEncryption === "tls" ? "starttls" : rawEncryption || null
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
async send(message, options) {
|
|
30
|
-
const smtpConfig = this.getConfig();
|
|
31
|
-
if (!smtpConfig.host || smtpConfig.host === "")
|
|
32
|
-
throw Error("[SMTP] Host is not configured. Set MAIL_HOST in your .env file.");
|
|
33
|
-
const logContext = {
|
|
34
|
-
provider: this.name,
|
|
35
|
-
to: message.to,
|
|
36
|
-
subject: message.subject,
|
|
37
|
-
host: smtpConfig.host,
|
|
38
|
-
port: smtpConfig.port
|
|
39
|
-
};
|
|
40
|
-
log.info("Sending email via SMTP...", logContext);
|
|
41
|
-
try {
|
|
42
|
-
this.validateMessage(message);
|
|
43
|
-
let htmlContent;
|
|
44
|
-
if (message.template) {
|
|
45
|
-
const templ = await template(message.template, options);
|
|
46
|
-
if (templ && "html" in templ)
|
|
47
|
-
htmlContent = templ.html;
|
|
48
|
-
}
|
|
49
|
-
const finalHtml = htmlContent || message.html, fromAddress = message.from?.address || config.email.from?.address || "", fromName = message.from?.name || config.email.from?.name || "", toAddresses = this.formatAddresses(message.to), replyToAddresses = this.formatAddressList(message.replyTo), emailContent = buildMimeMessage({
|
|
50
|
-
from: fromName ? `${fromName} <${fromAddress}>` : fromAddress,
|
|
51
|
-
to: toAddresses.join(", "),
|
|
52
|
-
cc: message.cc ? this.formatAddresses(message.cc).join(", ") : void 0,
|
|
53
|
-
replyTo: replyToAddresses.length > 0 ? replyToAddresses.join(", ") : void 0,
|
|
54
|
-
customHeaders: filterStringHeaders(message.headers),
|
|
55
|
-
subject: message.subject,
|
|
56
|
-
text: message.text,
|
|
57
|
-
html: finalHtml,
|
|
58
|
-
attachments: message.attachments,
|
|
59
|
-
messageIdDomain: config.email.domain
|
|
60
|
-
}), messageId = await this.sendViaSMTP(smtpConfig, fromAddress, toAddresses, emailContent);
|
|
61
|
-
return this.handleSuccess(message, messageId);
|
|
62
|
-
} catch (error) {
|
|
63
|
-
return this.handleError(error, message);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
async sendViaSMTP(smtpConfig, from, to, content) {
|
|
67
|
-
return new Promise((resolve, reject) => {
|
|
68
|
-
const timeout = setTimeout(() => {
|
|
69
|
-
reject(Error(`SMTP connection timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`));
|
|
70
|
-
}, SMTPDriver.SMTP_TIMEOUT), originalResolve = resolve, originalReject = reject;
|
|
71
|
-
resolve = (value) => {
|
|
72
|
-
clearTimeout(timeout);
|
|
73
|
-
originalResolve(value);
|
|
74
|
-
};
|
|
75
|
-
reject = (reason) => {
|
|
76
|
-
clearTimeout(timeout);
|
|
77
|
-
originalReject(reason);
|
|
78
|
-
};
|
|
79
|
-
let socket, buffer = "";
|
|
80
|
-
const _currentCommand = "", commandQueue = [], _isProcessing = !1;
|
|
81
|
-
let completed = !1;
|
|
82
|
-
const processResponse = (response) => {
|
|
83
|
-
log.debug(`[SMTP] Server: ${response.trim()}`);
|
|
84
|
-
if (parseInt(response.substring(0, 3), 10) >= 400) {
|
|
85
|
-
const error = Error(`SMTP Error: ${response.trim()}`);
|
|
86
|
-
if (commandQueue.length > 0)
|
|
87
|
-
commandQueue.shift()?.reject(error);
|
|
88
|
-
return;
|
|
89
|
-
}
|
|
90
|
-
if (commandQueue.length > 0)
|
|
91
|
-
commandQueue.shift()?.resolve(response);
|
|
92
|
-
}, sendCommand = (cmd) => {
|
|
93
|
-
return new Promise((res, rej) => {
|
|
94
|
-
commandQueue.push({ cmd, resolve: res, reject: rej });
|
|
95
|
-
log.debug(`[SMTP] Client: ${cmd}`);
|
|
96
|
-
socket.write(`${cmd}\r
|
|
97
|
-
`);
|
|
98
|
-
});
|
|
99
|
-
}, handleData = (data) => {
|
|
100
|
-
buffer += data.toString();
|
|
101
|
-
const lines = buffer.split(`\r
|
|
102
|
-
`);
|
|
103
|
-
buffer = lines.pop() || "";
|
|
104
|
-
for (const line of lines)
|
|
105
|
-
if (line.length >= 3) {
|
|
106
|
-
if (line.length === 3 || line[3] === " ")
|
|
107
|
-
processResponse(line);
|
|
108
|
-
}
|
|
109
|
-
}, runSmtpSession = async () => {
|
|
110
|
-
try {
|
|
111
|
-
await new Promise((res, rej) => {
|
|
112
|
-
commandQueue.push({ cmd: "GREETING", resolve: res, reject: rej });
|
|
113
|
-
});
|
|
114
|
-
const _ehloResponse = await sendCommand(`EHLO ${config.email.domain || "localhost"}`);
|
|
115
|
-
if (smtpConfig.encryption === "starttls" && !(socket instanceof tls.TLSSocket)) {
|
|
116
|
-
await sendCommand("STARTTLS");
|
|
117
|
-
const plainSocket = socket;
|
|
118
|
-
plainSocket.removeAllListeners("data");
|
|
119
|
-
socket = await new Promise((res, rej) => {
|
|
120
|
-
const tlsSocket = tls.connect({
|
|
121
|
-
socket: plainSocket,
|
|
122
|
-
host: smtpConfig.host,
|
|
123
|
-
servername: smtpConfig.host
|
|
124
|
-
}, () => {
|
|
125
|
-
log.debug("[SMTP] TLS connection established");
|
|
126
|
-
res(tlsSocket);
|
|
127
|
-
});
|
|
128
|
-
tlsSocket.on("error", (err) => {
|
|
129
|
-
log.error("[SMTP] TLS socket error:", err);
|
|
130
|
-
rej(err);
|
|
131
|
-
});
|
|
132
|
-
tlsSocket.on("data", handleData);
|
|
133
|
-
tlsSocket.on("close", (hadError) => {
|
|
134
|
-
log.debug(`[SMTP] TLS socket closed (hadError: ${hadError})`);
|
|
135
|
-
while (commandQueue.length > 0)
|
|
136
|
-
commandQueue.shift()?.reject(Error("TLS connection closed unexpectedly"));
|
|
137
|
-
});
|
|
138
|
-
});
|
|
139
|
-
await sendCommand(`EHLO ${config.email.domain || "localhost"}`);
|
|
140
|
-
}
|
|
141
|
-
if (smtpConfig.username && smtpConfig.password) {
|
|
142
|
-
await sendCommand("AUTH LOGIN");
|
|
143
|
-
await sendCommand(Buffer.from(smtpConfig.username).toString("base64"));
|
|
144
|
-
await sendCommand(Buffer.from(smtpConfig.password).toString("base64"));
|
|
145
|
-
}
|
|
146
|
-
assertEnvelopeAddress(from, "MAIL FROM");
|
|
147
|
-
for (const recipient of to)
|
|
148
|
-
assertEnvelopeAddress(recipient, "RCPT TO");
|
|
149
|
-
await sendCommand(`MAIL FROM:<${from}>`);
|
|
150
|
-
for (const recipient of to)
|
|
151
|
-
await sendCommand(`RCPT TO:<${recipient}>`);
|
|
152
|
-
await sendCommand("DATA");
|
|
153
|
-
socket.write(`${content}\r
|
|
1
|
+
import{Buffer}from"node:buffer";import process from"node:process";import*as tls from"node:tls";import*as net from"node:net";import{config}from"@stacksjs/config";import{log}from"@stacksjs/logging";import{template}from"../template";import{buildMimeMessage}from"../mime";import{ENVELOPE_ADDRESS,filterStringHeaders}from"../validation";import{BaseEmailDriver}from"./base";function assertEnvelopeAddress(addr,role){if(typeof addr!=="string"||!ENVELOPE_ADDRESS.test(addr))throw Error(`[smtp] Refusing to send: ${role} envelope address contains forbidden characters or is malformed: ${JSON.stringify(addr)}`)}export class SMTPDriver extends BaseEmailDriver{static SMTP_TIMEOUT=30000;name="smtp";getConfig(){const smtp=config.services?.smtp,env=process.env,host=smtp?.host||env.MAIL_HOST||"127.0.0.1",port=smtp?.port||(env.MAIL_PORT?Number(env.MAIL_PORT):void 0)||587,fromAddress=typeof config.email?.from?.address==="string"?config.email.from.address:"",username=smtp?.username||env.MAIL_USERNAME||fromAddress||"",localPart=(username.includes("@")?username.split("@")[0]:username).toUpperCase().replace(/[^A-Z0-9]/g,"_"),password=smtp?.password||env.MAIL_PASSWORD||(localPart?env[`MAIL_PASSWORD_${localPart}`]:void 0)||"",rawEncryption=smtp?.encryption??env.MAIL_ENCRYPTION??null;return{host,port,username,password,encryption:rawEncryption==="tls"?"starttls":rawEncryption||null}}async send(message,options){const smtpConfig=this.getConfig();if(!smtpConfig.host||smtpConfig.host==="")throw Error("[SMTP] Host is not configured. Set MAIL_HOST in your .env file.");const logContext={provider:this.name,to:message.to,subject:message.subject,host:smtpConfig.host,port:smtpConfig.port};log.info("Sending email via SMTP...",logContext);try{this.validateMessage(message);let htmlContent;if(message.template){const templ=await template(message.template,options);if(templ&&"html"in templ)htmlContent=templ.html}const finalHtml=htmlContent||message.html,fromAddress=message.from?.address||config.email.from?.address||"",fromName=message.from?.name||config.email.from?.name||"",toAddresses=this.formatAddresses(message.to),replyToAddresses=this.formatAddressList(message.replyTo),emailContent=buildMimeMessage({from:fromName?`${fromName} <${fromAddress}>`:fromAddress,to:toAddresses.join(", "),cc:message.cc?this.formatAddresses(message.cc).join(", "):void 0,replyTo:replyToAddresses.length>0?replyToAddresses.join(", "):void 0,customHeaders:filterStringHeaders(message.headers),subject:message.subject,text:message.text,html:finalHtml,attachments:message.attachments,messageIdDomain:config.email.domain}),messageId=await this.sendViaSMTP(smtpConfig,fromAddress,toAddresses,emailContent);return this.handleSuccess(message,messageId)}catch(error){return this.handleError(error,message)}}async sendViaSMTP(smtpConfig,from,to,content){return new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{reject(Error(`SMTP connection timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))},SMTPDriver.SMTP_TIMEOUT),originalResolve=resolve,originalReject=reject;resolve=(value)=>{clearTimeout(timeout);originalResolve(value)};reject=(reason)=>{clearTimeout(timeout);originalReject(reason)};let socket,buffer="";const _currentCommand="",commandQueue=[],_isProcessing=!1;let completed=!1;const processResponse=(response)=>{log.debug(`[SMTP] Server: ${response.trim()}`);if(parseInt(response.substring(0,3),10)>=400){const error=Error(`SMTP Error: ${response.trim()}`);if(commandQueue.length>0)commandQueue.shift()?.reject(error);return}if(commandQueue.length>0)commandQueue.shift()?.resolve(response)},sendCommand=(cmd)=>{return new Promise((res,rej)=>{commandQueue.push({cmd,resolve:res,reject:rej});log.debug(`[SMTP] Client: ${cmd}`);socket.write(`${cmd}\r
|
|
2
|
+
`)})},handleData=(data)=>{buffer+=data.toString();const lines=buffer.split(`\r
|
|
3
|
+
`);buffer=lines.pop()||"";for(const line of lines)if(line.length>=3){if(line.length===3||line[3]===" ")processResponse(line)}},runSmtpSession=async()=>{try{await new Promise((res,rej)=>{commandQueue.push({cmd:"GREETING",resolve:res,reject:rej})});const _ehloResponse=await sendCommand(`EHLO ${config.email.domain||"localhost"}`);if(smtpConfig.encryption==="starttls"&&!(socket instanceof tls.TLSSocket)){await sendCommand("STARTTLS");const plainSocket=socket;plainSocket.removeAllListeners("data");socket=await new Promise((res,rej)=>{const tlsSocket=tls.connect({socket:plainSocket,host:smtpConfig.host,servername:smtpConfig.host},()=>{log.debug("[SMTP] TLS connection established");res(tlsSocket)});tlsSocket.on("error",(err)=>{log.error("[SMTP] TLS socket error:",err);rej(err)});tlsSocket.on("data",handleData);tlsSocket.on("close",(hadError)=>{log.debug(`[SMTP] TLS socket closed (hadError: ${hadError})`);while(commandQueue.length>0)commandQueue.shift()?.reject(Error("TLS connection closed unexpectedly"))})});await sendCommand(`EHLO ${config.email.domain||"localhost"}`)}if(smtpConfig.username&&smtpConfig.password){await sendCommand("AUTH LOGIN");await sendCommand(Buffer.from(smtpConfig.username).toString("base64"));await sendCommand(Buffer.from(smtpConfig.password).toString("base64"))}assertEnvelopeAddress(from,"MAIL FROM");for(const recipient of to)assertEnvelopeAddress(recipient,"RCPT TO");await sendCommand(`MAIL FROM:<${from}>`);for(const recipient of to)await sendCommand(`RCPT TO:<${recipient}>`);await sendCommand("DATA");socket.write(`${content}\r
|
|
154
4
|
.\r
|
|
155
|
-
`);
|
|
156
|
-
|
|
157
|
-
commandQueue.push({ cmd: "DATA_END", resolve: res, reject: rej });
|
|
158
|
-
});
|
|
159
|
-
completed = !0;
|
|
160
|
-
const messageId = `${Date.now()}.${Math.random().toString(36).substring(2)}@${smtpConfig.host}`;
|
|
161
|
-
try {
|
|
162
|
-
socket.write(`QUIT\r
|
|
163
|
-
`);
|
|
164
|
-
} catch {}
|
|
165
|
-
socket.end();
|
|
166
|
-
resolve(messageId);
|
|
167
|
-
} catch (error) {
|
|
168
|
-
if (completed) {
|
|
169
|
-
socket.end();
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
socket.end();
|
|
173
|
-
reject(error);
|
|
174
|
-
}
|
|
175
|
-
};
|
|
176
|
-
if (smtpConfig.encryption === "ssl")
|
|
177
|
-
socket = tls.connect({
|
|
178
|
-
host: smtpConfig.host,
|
|
179
|
-
port: smtpConfig.port,
|
|
180
|
-
servername: smtpConfig.host
|
|
181
|
-
}, () => {
|
|
182
|
-
log.debug(`[SMTP] TLS connected to ${smtpConfig.host}:${smtpConfig.port}`);
|
|
183
|
-
runSmtpSession();
|
|
184
|
-
});
|
|
185
|
-
else
|
|
186
|
-
socket = net.connect({
|
|
187
|
-
host: smtpConfig.host,
|
|
188
|
-
port: smtpConfig.port
|
|
189
|
-
}, () => {
|
|
190
|
-
log.debug(`[SMTP] Connected to ${smtpConfig.host}:${smtpConfig.port}`);
|
|
191
|
-
runSmtpSession();
|
|
192
|
-
});
|
|
193
|
-
socket.on("data", handleData);
|
|
194
|
-
socket.setTimeout(SMTPDriver.SMTP_TIMEOUT);
|
|
195
|
-
socket.on("timeout", () => {
|
|
196
|
-
socket.destroy(Error(`SMTP socket timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`));
|
|
197
|
-
});
|
|
198
|
-
socket.on("error", (error) => {
|
|
199
|
-
if (completed)
|
|
200
|
-
return;
|
|
201
|
-
log.error(`[SMTP] Connection error to ${smtpConfig.host}:${smtpConfig.port}:`, error);
|
|
202
|
-
reject(error);
|
|
203
|
-
});
|
|
204
|
-
socket.on("close", (hadError) => {
|
|
205
|
-
log.debug(`[SMTP] Connection closed (hadError: ${hadError})`);
|
|
206
|
-
if (completed)
|
|
207
|
-
return;
|
|
208
|
-
while (commandQueue.length > 0)
|
|
209
|
-
commandQueue.shift()?.reject(Error("Connection closed unexpectedly"));
|
|
210
|
-
});
|
|
211
|
-
});
|
|
212
|
-
}
|
|
213
|
-
formatAddresses(addresses) {
|
|
214
|
-
if (!addresses)
|
|
215
|
-
return [];
|
|
216
|
-
if (typeof addresses === "string")
|
|
217
|
-
return [addresses];
|
|
218
|
-
return addresses.map((addr) => {
|
|
219
|
-
if (typeof addr === "string")
|
|
220
|
-
return addr;
|
|
221
|
-
return addr.address;
|
|
222
|
-
});
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
export default SMTPDriver;
|
|
5
|
+
`);await new Promise((res,rej)=>{commandQueue.push({cmd:"DATA_END",resolve:res,reject:rej})});completed=!0;const messageId=`${Date.now()}.${Math.random().toString(36).substring(2)}@${smtpConfig.host}`;try{socket.write(`QUIT\r
|
|
6
|
+
`)}catch{}socket.end();resolve(messageId)}catch(error){if(completed){socket.end();return}socket.end();reject(error)}};if(smtpConfig.encryption==="ssl")socket=tls.connect({host:smtpConfig.host,port:smtpConfig.port,servername:smtpConfig.host},()=>{log.debug(`[SMTP] TLS connected to ${smtpConfig.host}:${smtpConfig.port}`);runSmtpSession()});else socket=net.connect({host:smtpConfig.host,port:smtpConfig.port},()=>{log.debug(`[SMTP] Connected to ${smtpConfig.host}:${smtpConfig.port}`);runSmtpSession()});socket.on("data",handleData);socket.setTimeout(SMTPDriver.SMTP_TIMEOUT);socket.on("timeout",()=>{socket.destroy(Error(`SMTP socket timed out after ${SMTPDriver.SMTP_TIMEOUT}ms`))});socket.on("error",(error)=>{if(completed)return;log.error(`[SMTP] Connection error to ${smtpConfig.host}:${smtpConfig.port}:`,error);reject(error)});socket.on("close",(hadError)=>{log.debug(`[SMTP] Connection closed (hadError: ${hadError})`);if(completed)return;while(commandQueue.length>0)commandQueue.shift()?.reject(Error("Connection closed unexpectedly"))})})}formatAddresses(addresses){if(!addresses)return[];if(typeof addresses==="string")return[addresses];return addresses.map((addr)=>{if(typeof addr==="string")return addr;return addr.address})}}export default SMTPDriver;
|