如何使用 Nodemailer 将保存在 s3 上的 pdf 作为附件发送

How to send a pdf save on s3 as attachment using Nodemailer

我有发送带有 pdf 附件的电子邮件的功能,但是当我尝试发送本地没有文件的 pdf 时,电子邮件到达时没有任何附件...

async sendEmailWithAtt(email, subject, message, pathAtt) {
    const transporter = nodemailer.createTransport({
        host: process.env.EMAIL_HOST,
        port: process.env.EMAIL_PORT,
        auth: {
            user: process.env.EMAIL_USERNAME,
            pass: process.env.EMAIL_PASSWORD
        },
        attachments: [
            {
                filename: 'Document',
                path: pathAtt, // URL of document save in the cloud.
                contentType: 'application/pdf'
            }
        ]
    });

    const mailOptions = {
        from: process.env.EMAIL_USERNAME,
        to: email,
        subject: subject,
        text: message
    };

    await transporter.sendMail(mailOptions);
}

Nodemailer documentation 指出,如果您想使用 URL,则必须使用 href 而不是为本地文件保留的 path

如果文件不是公开的,您可以使用 httpHeaders 属性.

传递一些 headers
attachments: [
 {
     filename: 'Document',
     href: pathAtt, // URL of document save in the cloud.
     contentType: 'application/pdf'
  }
]

除此之外,您在 .createTransport 中设置了 attachments,您应该将其放在消息中。

const mailOptions = {
    from: process.env.EMAIL_USERNAME,
    to: email,
    subject: subject,
    text: message,
    attachments: [ /* ... */]
};

await transporter.sendMail(mailOptions);
 function sendFile(){    

    let transporter = nodemailer.createTransport({
        host: '',//put email_host
        port: '', // put port 
        secure: true,
        auth: {
            user: '',//put user email
            pass: '' //put password
        }
    });

    

    let mailToUser = {
        from: 'demo@gmail.com', //replace with user_email
        to: 'test@gmail.com', // replace with that want to send it
        
        html: "Hello",
        attachments: [
            {
                filename: `test.pdf`
                path :`` //put S3 url
                
                
            }
        ]

    };

    transporter.sendMail(mailToUser, (error, info) => {
        if (error) {
             console.log(error);
        }
        console.log('Message sent: %s', info);
    });
}