How do I retrieve the Twilio fax PDF and attach it to an email using Node.js inside a Twilio function?

[亡魂溺海] 提交于 2020-08-26 07:51:09

问题


Is there any way I can use Twilio's serverless options to retrieve a PDF that was faxed earlier and attach it to an email?

I've learned how to do this in PHP in WordPress on my own personal web server by looking at examples. Here's a snippet of WordPress PHP code that retrieves a PDF that was faxed using Twilio and then sends an email with the PDF as an attachment:

<?php
  $mediaurl = $_GET["MediaUrl"];
  $path = '/some/path/on/your/web/server/where/to/save/the/PDF';
  $attachment = $filename = $path . $_GET["FaxSid"] . '.pdf';
  require_once('wp-load.php');
  $response = wp_remote_get( $mediaurl, array( 'timeout' => '300', 'stream' => true, 'filename' => $filename ) );
  wp_mail( 'somebody@somewhere.com', 'You have a fax', 'See attached PDF', 'From: <someone@someplace.com>', $attachment );
?>

In case someone is learning about these things, I have the above code saved in a twilio-fax-receive.php file on my web server. And to run it every time a fax comes in, I have a TwiML Bin set up on Twilio -- I called it receive-fax -- with this code in it:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Receive action="https://www.somewhere.com/twilio-fax-receive.php" method="GET"/>
</Response>

Then, on the "Configure" page for the fax number that receives faxes, I selected TwiML where it says "A FAX COMES IN" and then selected my receive-fax TwiML Bin.

But back to my issue.

Can I replicate that using Node.js inside a Twilio function? Or some other way using only Twilio, without my own web server? Is there a way to get the contents of the PDF, encode it with base64 and attach to an email using SendGrid or some other service on the fly in Node.js?

Does anybody have a working example? I've tried a lot of things I found on the Web that involved request.get and got.stream and pipe and Buffer and fs, but to no avail...

I am not a developer, and I think I am in way over my head. Your help would be very much appreciated.


回答1:


Twilio developer evangelist here.

Yes, you can replicate this using Node.js in a Twilio Function. Here's how using SendGrid to send the email:

  1. Add request to your Runtime dependencies. I used version 2.88.0
  2. Add the following environment variables to your Functions config:
    • TO_EMAIL_ADDRESS: the email address you want to deliver faxes to.
    • FROM_EMAIL_ADDRESS: the email address you want to receive faxes from.
    • SENDGRID_API_KEY: Your SendGrid API key
  3. Save the config section
  4. Create a new function and add the following code:

    const request = require('request');
    
    exports.handler = function(context, event, callback) {
      const faxUrl = event.MediaUrl;
    
      const email = {
        personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],
        from: { email: context.FROM_EMAIL_ADDRESS },
        subject: `New fax from ${event.From}`,
        content: [
          {
            type: 'text/plain',
            value: 'Your fax is attached.'
          }
        ],
        attachments: []
      };
    
      request.get({ uri: faxUrl, encoding: null }, (error, response, body) => {
        if (!error && response.statusCode == 200) {
          email.attachments.push({
            content: body.toString('base64'),
            filename: `${event.FaxSid}.pdf`,
            type: response.headers['content-type']
          });
        }
        request.post(
          {
            uri: 'https://api.sendgrid.com/v3/mail/send',
            body: email,
            auth: {
              bearer: context.SENDGRID_API_KEY
            },
            json: true
          },
          (error, response, body) => {
            if (error) {
              return callback(error);
            } else {
              if (response.statusCode === 202) {
                return callback(null, new Twilio.twiml.VoiceResponse());
              } else {
                return callback(body);
              }
            }
          }
        );
      });
    };
    
  5. Give the Function a path and save it.

  6. Add the path as the action attribute to your <Receive> element in your TwiML bin.
  7. Send in the fax and watch it arrive in your inbox.

Let me know if this works for you, I'll write up how the code works in more detail when I get the time.




回答2:


There's another easy way to do it if you're using Gmail.

create a google apps script which sends an email to wherever you want using MailApp. Use the "MediaUrl" parameter to send it as an attachment.

function doGet(e) {
        var emailAddress = "EMAIL_ADDR_TO_SEND_TO";
        var from = e.parameter.From;
        var subject = "New Fax from  " + from;
        var body = "New fax attached";
        var fileUrl = e.parameter.MediaUrl;
        var file = UrlFetchApp.fetch(fileUrl);

          MailApp.sendEmail(emailAddress, subject, body, {
        attachments: [file.getAs(MimeType.PDF)]
      });
      }

Deploy it as a webapp that's public.

Copy Url and insert it in the "action" attribute of your TwiML <Receive/> tag. make sure you set "method" to "GET"

TwiML should look like this

<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Receive action="YOUR_GOOGLE_WEBAPP_URL" method="GET"/>
</Response>

Then configure you're Twilio number to that TwiML file



来源:https://stackoverflow.com/questions/53426243/how-do-i-retrieve-the-twilio-fax-pdf-and-attach-it-to-an-email-using-node-js-ins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!