Quiero enviar un archivo PDF adjunto usando la función sendRawEmail (Node: aws-sdk), lo he intentado de muchas maneras, el correo electrónico se envía con éxito, pero el PDF no tiene formato. Corrija mi código y ayude a resolverlo.
El código está aquí:
try { data = fs.readFileSync('files/demo-invoice-new.pdf', 'utf8'); console.log(data.toString()); var ses_mail = "From: 'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">\n"; ses_mail = ses_mail + "To: " + toEmail + "\n"; ses_mail = ses_mail + "Subject: AWS SES Attachment Example\n"; ses_mail = ses_mail + "MIME-Version: 1.0\n"; ses_mail = ses_mail + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n"; ses_mail = ses_mail + "--NextPart\n"; ses_mail = ses_mail + "Content-Type: text/html; charset=us-ascii\n\n"; ses_mail = ses_mail + "This is the body of the email.\n\n"; ses_mail = ses_mail + "--NextPart\n"; ses_mail = ses_mail + "Content-Type: application/octet;\n"; ses_mail = ses_mail + "Content-Disposition: attachment; filename=\"demo-invoice-new.pdf\"\n\n"; ses_mail = ses_mail + data.toString('utf8') + "\n\n"; ses_mail = ses_mail + "--NextPart--"; var params = { RawMessage: { Data: new Buffer(ses_mail) }, Destinations: [toEmail], Source: "'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">'" }; console.log(params); var sendPromise = new AWS.SES(AWS_SES_CONFIG).sendRawEmail(params).promise(); return sendPromise.then( data => { console.log(data); return data; }).catch( err => { console.error(err.message); throw err; }); } catch (e) { console.log('Error:', e.stack); }Los mensajes sin procesar de SES deben estar codificados en base64 . Por lo tanto, deberá obtener el contenido del archivo como búfer y codificarlo como un archivo adjunto de cadena base64. Además, no necesita crear un nuevo búfer para datos de mensajes sin procesar, ya que acepta un tipo de datos de cadena.
OPCIONAL : también puede omitir el parámetro Destinations dado que ya está proporcionando el campo To en los datos del mensaje sin procesar. (También puede proporcionar los campos Cc y Bcc )
Podrías probar esto por ejemplo:
data = fs.readFileSync("files/demo-invoice-new.pdf"); var ses_mail = "From: 'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">\n"; ses_mail += "To: " + toEmail + "\n"; ses_mail += "Subject: AWS SES Attachment Example\n"; ses_mail += "MIME-Version: 1.0\n"; ses_mail += "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n"; ses_mail += "--NextPart\n"; ses_mail += "Content-Type: text/html\n\n"; ses_mail += "This is the body of the email.\n\n"; ses_mail += "--NextPart\n"; ses_mail += "Content-Type: application/octet-stream; name=\"demo-invoice-new.pdf\"\n"; ses_mail += "Content-Transfer-Encoding: base64\n"; ses_mail += "Content-Disposition: attachment\n\n"; ses_mail += data.toString("base64").replace(/([^\0]{76})/g, "$1\n") + "\n\n"; ses_mail += "--NextPart--"; var params = { RawMessage: {Data: ses_mail}, Source: "'AWS SES Attchament Configuration' <" + SOURCE_EMAIL + ">'" }; NOTA : El reemplazo de la expresión regular /([^\0]{76})/ rompe las líneas largas para asegurarse de que los servidores de correo no se quejen de que las líneas del mensaje son demasiado largas cuando hay un archivo adjunto codificado, lo que podría resultar en un mensaje transitorio. rebotar. (Ver RFC 5321 )
Hola, para cualquiera que se tope con este problema, logré resolverlo usando nodemailer y SESV2 , tenía datos codificados en base64, por lo que su secuencia de comandos podría ser un poco diferente a la mía, pero el fragmento a continuación debería darles una idea... Esta es mi esperanza de solución ayuda a alguien:
const MailComposer = require("nodemailer/lib/mail-composer"); const AWS = require("aws-sdk"); const generateRawMailData = (message) => { let mailOptions = { from: message.fromEmail, to: message.to, subject: message.subject, text: message.bodyTxt, html: message.bodyHtml, attachments: message.attachments.map(a => ({ filename: a.name, content: a.data, encoding: 'base64' })) }; return new MailComposer(mailOptions).compile().build(); }; const exampleSendEmail = async () => { var message = { fromEmail: "sender@server.com", to: "receiver@sender.com", subject: "Message title", bodyTxt: "Plaintext version of the message", bodyHtml: "<p>HTML version of the message</p>", attachments: [{ name: 'hello.txt', data: 'aGVsbG8gd29ybGQ=' }] }; let ses = new AWS.SESV2(), params = { Content: { Raw: { Data: await generateRawMailData(message) } }, Destination: { ToAddresses: message.to, BccAddresses: message.bcc, }, FromEmailAddress: message.fromEmail, ReplyToAddresses: message.replyTo, }; return ses.sendEmail(params).promise(); }