solanasystems / sms-to-email

forwards incoming SMS messages to email accounts using Twilio
0 stars 0 forks source link

SMS to Email example code #1

Open t4sk opened 4 years ago

t4sk commented 4 years ago

@chishiki I hope you find this useful. This is an example code of receiving SMS and sending email

Receiving SMS message from Twilio

// https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-node-js

const http = require("http");
const express = require("express");
const bodyParser = require("body-parser");
const MessagingResponse = require("twilio").twiml.MessagingResponse;

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));

app.post("/sms", (req, res) => {
  const twiml = new MessagingResponse();

  console.log(req.body);

  if (req.body.Body == "hello") {
    twiml.message("Hi!");
  } else if (req.body.Body == "bye") {
    twiml.message("Goodbye");
  } else {
    twiml.message(
      "No Body param match, Twilio sends this in the request to your server."
    );
  }

  res.writeHead(200, { "Content-Type": "text/xml" });
  res.end(twiml.toString());
});

http.createServer(app).listen(1337, () => {
  console.log("Express server listening on port 1337");
});

Sending email to mailgun

import mailgun from "mailgun-js"

function send(
  params: { from: string; to: string; subject: string; html: string }
) {
const MAIL_GUN_API_KEY = ""
const MAIL_GUN_DOMAIN = ""

const mailer =  mailgun({ apiKey: MAIL_GUN_API_KEY, domain: MAIL_GUN_DOMAIN })

  mailer.messages().send(params, (error, body) => {
    if (error) {
      console.error(error)
    }
    //console.log(body)
  })
}
chishiki commented 4 years ago

Thanks @t4sk! I'll have a look at this.