Twilio で 電話受信時にメールを送信するサンプル
ブログ記事
Twilio で 電話受信時にメールを送信するサンプル
ブログ記事
exports.handler = function(context, event, callback) { | |
//let twiml = new Twilio.twiml.VoiceResponse(); | |
//// twiml.say("Hello World"); | |
//callback(null, twiml); | |
console.log('debug: context : ' + JSON.stringify(context)); | |
console.log('debug: event : ' + JSON.stringify(event)); | |
console.log('debug: callback: ' + JSON.stringify(callback)); | |
if ('completed' != event.RecordingStatus) { | |
console.log('failed tel recorded'); | |
console.log('tel sid: ' + event.CallSid); | |
console.log('status: ' + event.RecordingStatus); | |
//console.log('from: ' + event.From); | |
console.log('errCode: ' + event.ErrorCode); | |
console.log('errMessage: ' + event.ErrorMessage); | |
callback(null, 'no tel recorded'); | |
return; | |
} | |
// 1. 発信元の電話番号を取得 | |
// 2. メールを送信 | |
const callSid = event.CallSid; | |
const client = context.getTwilioClient(); | |
client.calls(callSid).fetch().then(function(call) { | |
console.log("from: " + call.from); | |
return sendEmail(event.RecordingUrl, call.from); | |
}).then(function(info) { | |
console.log('success: ' + info); | |
callback(null, 'email success'); | |
}).catch(function(err){ | |
console.log('failed: ' + JSON.stringify(err)); | |
callback(null, 'email failed'); | |
}); | |
// メールの送信 | |
// url : 録音ファイルのurl | |
// fromNumber : 発信元電話番号 | |
function sendEmail(url, fromNumber) { | |
console.log("url: " + url); | |
var nodemailer = require('nodemailer'); | |
var transporter = nodemailer.createTransport({ | |
host: 'SMTP サーバー名', | |
port: 587, | |
secure: false, | |
auth: { | |
user: 'ユーザー名', | |
pass: 'パスワード' | |
}, | |
tls: { | |
rejectUnauthorized: false | |
} | |
}); | |
var message = { | |
from: '発信者のメールアドレス', | |
to: '宛先メールアドレス', | |
subject: 'Tel received from ' + event.From, | |
text: 'Tel received from ' + event.From, | |
attachments: [{ | |
filename: 'record.wav', | |
path: url | |
}] | |
}; | |
console.log('message: ' + JSON.stringify(message)); | |
console.log("finish preparation to send mail"); | |
return new Promise(function(resolve, reject) { | |
transporter.sendMail(message, function(error, info) { | |
if (error) { | |
console.log('error: ' + error); | |
reject(error); | |
} else { | |
console.log('email sent, message id: ' + info.messageId); | |
resolve(info); | |
} | |
}); | |
}); | |
} | |
}; |