Pages

Tuesday, August 9, 2016

Learning Meteor.js [Part 45]: Sending email

The last feature to implement is to send the shopping list by email. For this I'll be using the email meteor package from within a server method:
import { Email } from 'meteor/email'

export const mailShoppingList = new ValidatedMethod({
    name: 'order.mailShoppingList',
    validate: new SimpleSchema({
        orderId: { type: String },
        email: { type: String }
    }).validator({ clean: true }),
    mixins: [Mixins.authenticated, Mixins.orderOwner],
    run({ orderId, email }) {
        if (Meteor.isClient) {
            return;
        }

        var meals = Meals.find({ orderId : orderId }).fetch();
        var shoppingList = buildShoppingListFromMeals(meals);
        var html = Handlebars.templates['shoppingList'](shoppingList);

        Email.send({
          to: email,
          from: "fsilva.armas@gmail.com",
          subject: "Lunch Time: Your Shopping List",
          html: html,
        });
    }
});

The same method from my previous post is reused to build the shopping list. Next I'll use the handlebars-server package to build the HTML body of the email. Once installed, you can put handlebar templates with the .handlebars extension directly under the 'server' folder. For example these are the contents of shoppingList.handlebars:
{{#each categories}}
    <h4>{{name}}</h4>
    <ul>
        {{#each items}}
            <li>
                {{name}}
                {{#if amountText}}
                &nbsp;&nbsp;({{amountText}})
                {{/if}}
            </li>
        {{/each}}
    </ul>
{{/each}}

With this in place you can evaluate the template with 'Handlebars.template[name_of_template](view_model_object)' to create the HTML string. Finally, use Email.send() to deliver the email to whichever provider you have configured in the MAIL_URL environment variable (in my case I used Mailgun).

You can visit the live demo or view the soure code.



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.