37 lines
1.5 KiB
JavaScript
37 lines
1.5 KiB
JavaScript
class Email {
|
|
constructor(from, to, subject, body, html = null, attachments = []) {
|
|
this.from = from;
|
|
this.to = to;
|
|
this.subject = subject;
|
|
this.body = body;
|
|
this.html = html; // Optional HTML version
|
|
this.attachments = attachments;
|
|
this.boundary = `----Boundary${Math.random().toString(36).substring(2)}`; // Unique boundary string
|
|
}
|
|
|
|
format() {
|
|
let emailString = `From: ${this.from}\r\nTo: ${this.to}\r\nSubject: ${this.subject}\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary="${this.boundary}"\r\n\r\n`;
|
|
|
|
// Add body as text or both text and HTML parts
|
|
if (this.body) {
|
|
emailString += `--${this.boundary}\r\nContent-Type: text/plain; charset="UTF-8"\r\n\r\n${this.body}\r\n`;
|
|
}
|
|
if (this.html) {
|
|
emailString += `--${this.boundary}\r\nContent-Type: text/html; charset="UTF-8"\r\n\r\n${this.html}\r\n`;
|
|
}
|
|
|
|
// Add attachments if any
|
|
if (this.attachments.length > 0) {
|
|
this.attachments.forEach(attachment => {
|
|
emailString += `--${this.boundary}\r\nContent-Disposition: attachment; filename="${attachment.filename}"\r\nContent-Type: ${attachment.contentType}; name="${attachment.filename}"\r\nContent-Transfer-Encoding: base64\r\n\r\n${attachment.content}\r\n`;
|
|
});
|
|
}
|
|
|
|
// Close the MIME message
|
|
emailString += `--${this.boundary}--\r\n`;
|
|
return emailString;
|
|
}
|
|
}
|
|
|
|
export default Email;
|