node.js - 如何使用 sendgrid 转发彩信?

标签 node.js twilio sendgrid

以下代码直接来自示例。它的作用就像短信的魅力一样。 event.Body 通常不会出现在 MMS 消息中。我想要一些代码,以便可以使用 sendgrid 捕获并发送传入的 SMS 或 MMS 消息。

这是来自 twilio 网站的确切错误。

错误 - 82002 Twilio 函数响应错误 您的函数调用导致 StatusCode 5xx。

可能的原因 您的函数在响应之前超时 您的函数返回了错误响应

可能的解决方案 您的函数必须包含回调。 确保将函数回调回调(err,response)正确放置在函数代码中。 如果您使用 JavaScript Promise,请确保在 success 和 catch block 中都调用回调。 您的函数响应错误。


const got = require('got'); 

exports.handler = function(context, event, callback) { 
      const requestBody = { 
    personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }], 
    from: { email: context.FROM_EMAIL_ADDRESS }, 
    subject: `New SMS message from: ${event.From}`, 
    content: [ 
      { 
        type: 'text/plain', 
        value: event.Body 
      } 
    ] 
      }; 
    let twiml = new Twilio.twiml.MessagingResponse(); 
    
    got.post('https://api.sendgrid.com/v3/mail/send', { 
    headers: { 
      Authorization: `Bearer ${context.SENDGRID_API_KEY}`, 
      'Content-Type': 'application/json' 
    }, 
    body: JSON.stringify(requestBody) 
  }) 
    .then(response => { 
      callback(null, twiml); 
    }) 
    .catch(err => { 
      callback(err); 
    });   
    
    
}; 

寻求有关通过 twilio 传入的彩信发送电子邮件的帮助。

提前致谢。

最佳答案

这里是 Twilio 开发者布道者。

您可以通过使用 Request 保存入站图像,通过 Node.js 中的 SendGrid 和 Express 将彩信转发到电子邮件,详情请参阅 this blog post by my teammate Sam Agnew

首先,我们需要需要我们要使用的所有模块,创建一个 Express 应用程序对象并向其中添加 Body Parser 中间件。

const fs = require('fs');
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const sgMail = require('@sendgrid/mail');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));

接下来,我们需要在此 Express 应用程序中创建一条路由,以在彩信发送到您的 Twilio 号码时处理 Twilio 发送的 POST 请求。此代码保存入站图像(您可以使用 req.body.MediaUrl0 获取入站图像的 URL)并等待几秒钟(下面的代码为此使用 native Promises)以保存图像与 Node.js 文件位于同一目录中。然后,它使用 SendGrid 在电子邮件中内联发送该图像。这是通过在 attachments 下设置 disposition: 'inline' 并设置 content_id 来完成的,以便您可以在 HTML 中引用它 电子邮件正文的一部分。

将图像转换为 Base64 编码的字符串也很重要,您可以使用 readFileSync 来完成此操作,如下所示。

app.post('/sms', (req, res) => {
    sgMail.setApiKey(
        'REPLACE-WITH-YOUR-SENDGRID-API-KEY'
    );
    const filename = `${req.body.MessageSid}.png`;
    const url = req.body.MediaUrl0;
    request(url)
        .pipe(fs.createWriteStream(filename))
        .on('open', () => console.log('image downloaded'));
    const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));
    sleep(3000).then(() => {
        const msg = {
            to: `EMAIL-YOU-WANT-TO-RECEIVE-IMAGE`,
            from: `EMAIL-TO-SEND-FROM`,
            subject: `Send an image!`,
            html: `<body><p>Image is below</p><img src= "cid:mmsimg" alt='test image' /></body>`,
            attachments: [
                {
                    filename: filename,
                    type: 'image/png',
                    content_id: 'mmsimg',
                    content: fs.readFileSync(filename, { encoding: 'base64' }),
                    disposition: 'inline'
                }
            ]
        };
        sgMail.send(msg).then(result => {
            console.log(result);
        })
        .catch(err => {
            console.log(err);
        });
    });
});

最后,我们让 Express 应用监听端口 3000 上的请求。

app.listen(3000, () => console.log('Listening on port 3000!'));

希望这有帮助!

关于node.js - 如何使用 sendgrid 转发彩信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57617474/

相关文章:

node.js - 命令gulp错误 "assert.js:42 throw new errors.AssertionError"

c# - 获取调用 SID 记录可以成功完成

sms - Twilio SMS 消息未发送,出现未知错误

javascript - 使用 sendgrid 发送电子邮件 [Node.js]

python-3.x - 如何发送多个收件人sendgrid V3 api Python

.net - 包括 SendGrid 会破坏编译

node.js - 为什么我们需要 Sequelize 'seed' ?

node.js - 如何在 Auth0 中为新用户发送密码更改电子邮件而不是验证电子邮件

node.js - 当我传递多个范围时,Microsoft Graph 权限范围引发错误

Twilio 转发 "Calling Number"