【问题标题】:Sending mails with attachment via NodeJS通过 NodeJS 发送带有附件的邮件
【发布时间】:2011-06-08 01:23:33
【问题描述】:

是否有任何 NodeJS 库用于发送带附件的邮件?

【问题讨论】:

    标签: email node.js attachment


    【解决方案1】:

    答案没有更新最新版nodemailer@6.x

    这里是一个更新的例子:

    const fs = require('fs')
    const path = require('path')
    
    const nodemailer = require('nodemailer')
    const transport = nodemailer.createTransport({
      host: 'smtp.libero.it',
      port: 465,
      secure: true,
      auth: {
        user: 'email@libero.it',
        pass: 'HelloWorld'
      }
    })
    
    
    fs.readFile(path.join(__dirname, 'test22.csv'), function (err, data) {
      transport.sendMail({
        from: 'email_from@libero.it',
        to: 'email_to@libero.it',
        subject: 'Attachment',
        text: 'mail content...', // or body: field
        attachments: [{ filename: 'attachment.txt', content: data }]
      }, function (err, success) {    
        if (err) {
          // Handle error
          console.log(err)
          return
        }
        console.log({ success })
      })
    })
    

    【讨论】:

      【解决方案2】:

      你试过Nodemailer吗?

      Nodemailer 支持

      • Unicode 可以使用任何字符
      • HTML 内容以及纯文本替代方式
      • 附件
      • HTML 中的嵌入图像
      • SSL(但不是 STARTTLS)

      【讨论】:

        【解决方案3】:

        你可以使用谷歌的官方api。 他们为此目的提供了节点包。 google official api

        我附上了为我做附件的部分代码

        function makeBody(subject, message) {
        var boundary = "__myapp__";
        var nl = "\n";
        var attach = new Buffer(fs.readFileSync(__dirname + "/../"+fileName)) .toString("base64");
        // console.dir(attach);
        var str = [
        
                "MIME-Version: 1.0",
                "Content-Transfer-Encoding: 7bit",
                "to: " + receiverId,
                "subject: " + subject,
                "Content-Type: multipart/alternate; boundary=" + boundary + nl,
                "--" + boundary,
                "Content-Type: text/plain; charset=UTF-8",
                "Content-Transfer-Encoding: 7bit" + nl,
                message+ nl,
                "--" + boundary,
                "--" + boundary,
                "Content-Type: Application/pdf; name=myPdf.pdf",
                'Content-Disposition: attachment; filename=myPdf.pdf',
                "Content-Transfer-Encoding: base64" + nl,
                attach,
                "--" + boundary + "--"
        
            ].join("\n");
        
            var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
            return encodedMail;
        }

        P.S 感谢 himanshu 对此的深入研究

        【讨论】:

          【解决方案4】:

          使用特快专递 (https://www.npmjs.com/package/express-mailer) 发送

          发送 PDF -->

          var pdf="data:application/pdf;base64,JVBERi0xLjM..etc"
          
          attachments: [  {  filename: 'archive.pdf',
                            contents: new Buffer(pdf.replace(/^data:application\/(pdf);base64,/,''), 'base64')
                           }   
                       ]
          

          发送图片 -->

          var img = 'data:image/jpeg;base64,/9j/4AAQ...etc'
          attachments: [  
                       {  
                         filename: 'myImage.jpg',
                         contents: new Buffer(img.replace(/^data:image\/(png|gif|jpeg);base64,/,''), 'base64')
                         }   
                       ]
          

          发送txt -->

          attachments: [  
                       {  
                         filename: 'Hello.txt',
                         contents: 'hello world!'
                         }   
                       ]
          

          【讨论】:

          • 能否也提供一个最小的示例代码。像这样,答案不是很有帮助,因为我不知道应该将attachments 放在哪里。
          【解决方案5】:

          另一个可以尝试的替代库是emailjs

          我在这里尝试了一些建议,但运行代码抱怨 send_mail() 和 sendMail() 未定义(即使我只是复制和粘贴代码并稍作调整)。我正在使用节点 0.12.4 和 npm 2.10.1。我对 emailjs 没有任何问题,它对我来说是现成的。并且它对附件有很好的包装,因此与此处的 nodemailer 示例相比,您可以根据自己的喜好轻松地以各种方式附加它。

          【讨论】:

            【解决方案6】:

            是的,很简单, 我使用nodemailer:npm install nodemailer --save

            var mailer = require('nodemailer');
            mailer.SMTP = {
                host: 'host.com', 
                port:587,
                use_authentication: true, 
                user: 'you@example.com', 
                pass: 'xxxxxx'
            };
            

            然后读取文件并发送电子邮件:

            fs.readFile("./attachment.txt", function (err, data) {
            
                mailer.send_mail({       
                    sender: 'sender@sender.com',
                    to: 'dest@dest.com',
                    subject: 'Attachment!',
                    body: 'mail content...',
                    attachments: [{'filename': 'attachment.txt', 'content': data}]
                }), function(err, success) {
                    if (err) {
                        // Handle error
                    }
            
                }
            });
            

            【讨论】:

            • 最后一行缺少 '})'。我不能直接编辑,因为它少于 6 个字符...
            • 附件属性有一个类型。 “内容”不正确。应该是“内容”。
            • 这段代码 sn-p 处理二进制文件还是只处理文本?
            • 旧版本的 nodemailer 用户“内容”。请务必检查您正在使用的版本,并与nodemailer.com的 nodemailer 文档进行比较
            • 无论如何发送 db 文件。我正在使用部署在 Heroku 上的 sqlite,并且在每次部署时,应用程序都会被格式化。我的目录中有 database.db 文件,并希望使用电子邮件发送它。因为这样我需要实现 cronjob。任何帮助将不胜感激
            【解决方案7】:

            我没用过,但是 nodemailer(npm install nodemailer) 看起来像你想要的。

            【讨论】:

              【解决方案8】:

              使用mailer包,非常灵活方便。

              【讨论】:

                【解决方案9】:

                Nodemailer 可满足任何 nodejs 邮件需求。这是目前最好的:D

                【讨论】:

                  【解决方案10】:

                  用 nodemailer 试试,例如试试这个:

                    var nodemailer = require('nodemailer');
                    nodemailer.SMTP = {
                       host: 'mail.yourmail.com',
                       port: 25,
                       use_authentication: true,
                       user: 'info@youdomain.com',
                       pass: 'somepasswd'
                     };
                  
                    var message = {   
                          sender: "sender@domain.com",    
                          to:'somemail@somedomain.com',   
                          subject: '',    
                          html: '<h1>test</h1>',  
                          attachments: [  
                          {   
                              filename: "somepicture.jpg",    
                              contents: new Buffer(data, 'base64'),   
                              cid: cid    
                          }   
                          ]   
                      };
                  

                  最后,发送消息

                      nodemailer.send_mail(message,   
                        function(err) {   
                          if (!err) { 
                              console.log('Email send ...');
                          } else console.log(sys.inspect(err));       
                      });
                  

                  【讨论】:

                  • ReferenceError: data is not defined -- 我是否缺少要求?
                  【解决方案11】:

                  您还可以使用 AwsSum 的 Amazon SES 库:

                  里面有一个叫做SendEmail和SendRawEmail的操作,后者可以通过服务发送附件。

                  【讨论】:

                  • 别忘了充分披露您与推荐项目的关系 :)
                  【解决方案12】:

                  我个人使用Amazon SESrest API 或Sendgridrest API,这是最一致的方式。

                  如果您需要一种低级方法,请使用 https://github.com/Marak/node_mailer 并设置您自己的 smtp 服务器(或您也有权访问的服务器)

                  http://blog.nodejitsu.com/sending-emails-in-node

                  【讨论】:

                  • 旧答案,但是 API 如何比本地 sendmail 服务器更一致...?
                  【解决方案13】:

                  您可以使用nodejs-phpmailer

                  【讨论】:

                  • 他使用node.js,为什么建议他使用php解决方案?
                  • 我认为使用 node.js 但基于 php,有点慢而且很糟糕.. 但我认为可以。
                  猜你喜欢
                  • 2019-12-18
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2014-07-23
                  • 1970-01-01
                  相关资源
                  最近更新 更多