云计算
现在阅读
Serverless experiments with Google Cloud Platform, Part 2
0

Serverless experiments with Google Cloud Platform, Part 2

由 ultracpy2018年1月20日

6. Email service

From Part 1 you should know that Google Cloud Platform (GCP) Functions are pieces of code called when something happened. For various smaller tasks you do not need to pay for own full-time server.

Problem of email sending looks like choosing one of the many Node.JS modules can do it (just search for ‘send email nodejs’). Or maybe learning of something like Gmail API https://developers.google.com/gmail/api/quickstart/nodejs, I also never tried.

But having no permanently running email server, who will receive email? Fortunately there are various services can do it instead of us. Get into k Email/SMS on https://elements.heroku.com/addons to see some.

Because of single registration I choose Mailgun https://cloud.google.com/appengine/docs/standard/go/mail/mailgun, which can both send and receive.

Actually processing of ten thousand (maybe thousands https://www.mailgun.com/google with GCP) of emails is free. If you do not need own email domain (do not try to conquest the whole gmail.com by Mailgun), it means when you are satisfied with something like sandbox1234567890abcdefghijklmnopqrst.mailgun.org, because of using emails just like occasional transformation medium between your services or few authorized email recipients, than you do not need to pay anything.

Registration needs just phone able to receive SMS and account works without entering any Payment Method with some limitations https://documentation.mailgun.com/en/latest/faqs.html#what-are-the-differences-between-free-and-paid-accounts. It is possible to set Payment Method later in account settings https://app.mailgun.com/app/account/settings.

To make it clear, Mailgun is service for sending and receiving. It does not store emails permanently, anyway it allows temporary storage https://documentation.mailgun.com/en/latest/user_manual.html#receiving-forwarding-and-storing-messages.

6.1. Send email

Being registered, enter your Mailgun dashboard https://app.mailgun.com/app/dashboard.

At the bottom you will see your sanbox Domain Name (similar to sandbox1234567890abcdefghijklmnopqrst.mailgun.org). Clicking on it appears API Base URL (something like https://api.mailgun.net/v3/sandbox1234567890abcdefghijklmnopqrst.mailgun.org/messages) and API Key (say key-abcdefghijklmnopqrst1234567890).

API Key equals to Secret API Key visible at the right side of dashboard home page.

Sandbox domains are restricted to authorized recipients only. Using button get into Authorized Recipients https://app.mailgun.com/app/account/authorized and Invite new one. Recipient must react to invitation email with Agree link, so start experiments with your own email. Assume it is yourname@gmail.com.

Switch to GCP console https://console.cloud.google.com/ and in Cloud Functions create new one with http trigger (more details are available in Part 1).

Do not forget in index.js to enter your email, API key and API Base URL.

/**
 * sends email using mailgun's https api
 *
 * @param {!Object} req Cloud Function request context.
 * @param {!Object} res Cloud Function response context.
 */
exports.sendEmailFunction = function sendEmailFunction(req, res) {
    
//based on https://github.com/shz/node-mailgun/blob/master/mailgun.js
//https://documentation.mailgun.com/quickstart-sending.html#send-via-api
var request = require("request");

var mailgunapiKey = new Buffer('api:' + "key-abcdefghijklmnopqrst1234567890").toString('base64');

var mailFormData = {
    from: "mailgun@mailgun.org",
    to: "yourname@gmail.com",
    subject: "sendEmailFunction",
    text: "Hallo from cloud"
  };
  
request({
  uri: "https://api.mailgun.net/v3/sandbox1234567890abcdefghijklmnopqrst.mailgun.org/messages",
  headers: {'User-Agent': 'request',
            'Authorization': 'Basic ' + mailgunapiKey,
           },
  method: "POST",
  form: mailFormData,
}, function(error, response, body) {
            res.status(200).send('Success: ' + error + "&" + response.statusCode + "&" + body + ' end');
});
  
};

Of course, mailFormData’s members could be filled from variables, even such received in req (where script’s caller must support it).

subject: req.body.subject,

Remember that because of require("request") inside script, you need to add request to package.json‘s dependencies.

6.2. Receive email

With services like Mailgun is receiving easy. Receving new incoming email it will call your Function. You must define which Function will be called by which email.

In your Mailgun dashboard https://app.mailgun.com/app/dashboard get into Routes. There Create Route, for begin the simplest it could be.

In Expression type choose Catch All. It means that every incoming email (actually anything sent to your info@sandbox1234567890abcdefghijklmnopqrst.mailgun.orgcontact@sandbox1234567890abcdefghijklmnopqrst.mailgun.org, etc.) will be handled by this Route.

From Actions choose Forward and enter URL triggering your GCP Function, like https://us-central1-ProjectName-123456.cloudfunctions.net/receiveEmailFunction.

Because this is the only Route we create, it does not matter if you will select to Stop the processing of emails fitting to defined filter (Catch All) or not.

How could GCP receiveEmailFunction look like?

/**
 * Receive email from Mailgun.
 *
 * @param {!Object} req Cloud Function request context.
 * @param {!Object} res Cloud Function response context.
 */
exports.receiveEmailFunction = function receiveEmailFunction(req, res) {
//https://documentation.mailgun.com/user_manual.html#routes
  if (req.body.subject === undefined) {
    // This is an error case, as "subject" is required.
    res.status(400).send('No subject defined!');
  } else {
    // Everything is okay.
    console.log(req.body['body-plain']);
    res.status(200).send('Success: ' + req.body['body-plain']);
  }
};

Take this just like a simple example. Even when email has empty title, there is no reason that Function called by Mailgun will have req.body.subject undefined.

Note that compared to sending there are different names of emails parts. The same plain body text is once text, once body-plain. Because of hyphen character inside name, it must be accessed using brackets.

Received email body is pre-parsed more ways, have a look near body-plain on https://documentation.mailgun.com/en/latest/user_manual.html#routes.

Now send email (from your yourname@gmail.com) to sandbox (something like whatever@sandbox1234567890abcdefghijklmnopqrst.mailgun.org) and voilà: for sender nothing visible happens.

To be sure that email was received, have a look at logs on Mailgun https://app.mailgun.com/app/dashboard and (after a minute) on GCP https://console.cloud.google.com/ (in Functions open your Function and click right-top VIEW LOGS).


End of Part Two. In the third part I plan to connect Functions with another web services.

出处:https://www.codeproject.com/Articles/1194360/Serverless-experiments-with-Google-Cloud-Platfor

关于作者
ultracpy
评论

    你必须 登录 提交评论