使用 sendgrid 和 node.js 将日志文件附加到电子邮件

Posted

技术标签:

【中文标题】使用 sendgrid 和 node.js 将日志文件附加到电子邮件【英文标题】:Attach log file to email using sendgrid and node.js 【发布时间】:2019-12-25 21:56:07 【问题描述】:

我正在尝试在一个简单的 node.js 应用程序中发送一封电子邮件,其中包含刚刚使用 log4js 创建的日志文件。我可以用 sendgrid 发送一封电子邮件,它有一个附件,但附件是空的。任何帮助,将不胜感激。这是 app.js 代码:

const fs = require('fs');
require('dotenv').config();
const sub = require('./app-sub');
const log = require('./logger').logger.getLogger('app');

// Make some log entries out to console and to app.log
log.info('******************************')
log.info('Start test1')
log.info('')
log.trace("trace message")
log.debug("Some debug messages");
log.info("some info")
log.warn("a warning")
log.error("an error")
log.fatal("a fatal error")

// Call a function in another file to test
sub.sub_funct1();

log.info('')
log.info('******************************')
log.info('End test1')

// Send email with log as attachment
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

// Read log file base 64
path = 'app.log';
attachment = fs.readFileSync(path,  encoding: 'base64' );

const msg = 
  to: 'dgarvin57@gmail.com',
  from: 'darvin57@gmail.com',
  subject: 'Test email 1',
  text: 'Results sent from log_test',
  html: '<strong>and easy to do anywhere, even with Node.js</strong>',
  attachments: [
    
      content: attachment,
      filename: 'app.log',
      type: 'text/html', // plain/text application/pdf
      disposition: 'attachment',
      content_id: 'app.log'
      // inline, attachment
    ,
  ],

;
sgMail.send(msg)
  .then(result =>  )
  .catch(err => console.log(err.response.body));

以及 logger.js 中的 log4js 记录器配置:

const log4js = require('log4js');
const level = process.env.NODE_LOGGING_LEVEL || 'debug';

log4js.configure(
  appenders: 
    app:  type: 'file', filename: 'app.log', flags: 'w' ,
    out:  type: 'stdout' ,
  ,
  categories:  default:  appenders: ['out', 'app'], level: level  
);

module.exports.logger = log4js;

当我运行它时,我会在终端中看到日志输出,并且在与 app.js 位于同一文件夹中的 app.log 文件中:

[2019-12-25T15:43:46.677] [INFO] app - ******************************
[2019-12-25T15:43:46.679] [INFO] app - Start test1
[2019-12-25T15:43:46.680] [INFO] app -  
[2019-12-25T15:43:46.688] [DEBUG] app - Some debug messages 
[2019-12-25T15:43:46.689] [INFO] app - some info 
[2019-12-25T15:43:46.690] [WARN] app - a warning 
[2019-12-25T15:43:46.691] [ERROR] app - an error
[2019-12-25T15:43:46.691] [FATAL] app - a fatal error
[2019-12-25T15:43:46.692] [INFO] app - some info from app-sub
[2019-12-25T15:43:46.692] [INFO] app -  
[2019-12-25T15:43:46.692] [INFO] app - ****************************** 
[2019-12-25T15:43:46.693] [INFO] app - End test1

电子邮件会发送到我的 gmail 帐户,并带有一个名为 app.log 的附件。但是当我打开它时,它是空白的。因此,不确定在发送电子邮件时我是否在文本文件或附件部分的 base64 转换上失败。提前致谢。

【问题讨论】:

【参考方案1】:

我当时能够让它工作,并想记录一个解决方案。我认为关键是先关闭日志文件,因为它仍在使用时无法附加。这是关闭日志文件并调用我的 sendEmail 实用程序函数的代码:

log.shutown;
email.sendEmail(to, subject, body, logPath)

这里是 sendMail 函数:

require('dotenv').config();
const sgMail = require('@sendgrid/mail');
const fs = require('fs');

function sendEmail(to, subject, body, attachmentPath) 

  // Send email with log as attachment
  sgMail.setApiKey(process.env.SENDGRID_API_KEY);

  const msg = 
    to: to,
    from: 'myEmail@gmail.com',
    subject: subject,
    text: 'Results:',
    html: body
  ;

  // Read log file base 64
  if (attachmentPath != undefined) 
    attachment = fs.readFileSync(attachmentPath,  encoding: 'base64' );
    msg.attachments = [
      
        content: attachment,
        filename: attachmentPath,
        type: 'text/plain',
        disposition: 'attachment'
      ,
    ]
   else 
    msg.attachments = undefined;
  

  sgMail.send(msg)
    .then(result =>  )
    .catch(err => console.log(err.response.body));

【讨论】:

以上是关于使用 sendgrid 和 node.js 将日志文件附加到电子邮件的主要内容,如果未能解决你的问题,请参考以下文章

如何使用SendGrid将图像嵌入到Node.js中的html邮件中

node.js @sendgrid/mail 错误:未经授权

在 Node.js 的 SendGrid 中向“发件人”字段添加名称

转发入站电子邮件 sendgrid

Sendgrid 中的替换令牌列表

Node js从电子邮件地址发送网格空(必需)