/ src / utils / emailUtils.js
emailUtils.js
 1  const { exec } = require('child_process');
 2  const fs = require('fs').promises;
 3  
 4  async function createEmailDraft(recipients, subject, body, attachmentPath) {
 5    console.log(`Creating email draft for recipients: ${recipients.join(', ')}`);
 6    console.log(`Subject: ${subject}`);
 7    console.log(`Attachment path: ${attachmentPath}`);
 8  
 9    const recipientString = recipients.join(',');
10    const escapedSubject = subject.replace(/[\\"]/g, '\\$&');
11    const escapedBody = body.replace(/[\\"]/g, '\\$&').replace(/\n/g, '\\n');
12    
13    let applescript = `
14      tell application "Mail"
15        set newMessage to make new outgoing message
16        tell newMessage
17          set visible to true
18          set subject to "${escapedSubject}"
19          set content to "${escapedBody}"
20          repeat with recipientEmail in {"${recipientString}"}
21            make new to recipient at end of to recipients with properties {address:recipientEmail}
22          end repeat
23    `;
24  
25    if (attachmentPath) {
26      const escapedAttachmentPath = attachmentPath.replace(/[\\"]/g, '\\$&');
27      applescript += `
28          make new attachment with properties {file name:"${escapedAttachmentPath}"} at after the last paragraph
29      `;
30    }
31  
32    applescript += `
33        end tell
34      end tell
35    `;
36  
37    return new Promise((resolve, reject) => {
38      exec(`osascript -e '${applescript.replace(/'/g, "'\"'\"'")}'`, (error, stdout, stderr) => {
39        if (error) {
40          console.error(`Error creating email draft: ${error}`);
41          console.error(`Stderr: ${stderr}`);
42          reject(error);
43        } else {
44          console.log('Email draft created successfully');
45          console.log(`Stdout: ${stdout}`);
46          resolve();
47        }
48      });
49    });
50  }
51  
52  module.exports = {
53    createEmailDraft
54  };