Search code examples
rusthandlebars.js

Send Email with lettre and body with Handlebars.js


This is on my Rust the handlebar initialization. There are not errors.

  let mut reg = Handlebars::new();
  let order_email_content = reg.render_template("src/emails/order_email.hbs", &serde_json::json!({"data" : email_order.body, "orderNumber": 3333, "amount": 555})).unwrap();

Here is lettre for sending emails:

let host_email = Message::builder()
      .from(config.email.serverEmail.email.parse().unwrap())
      .to(config.email.recipient.parse().unwrap())
      .subject("Rust Order für FlyerandPrint")
      .multipart(
        MultiPart::alternative() // This is composed of two parts.
            .singlepart(
                SinglePart::builder()
                    .header(header::ContentType::TEXT_PLAIN)
                    .body(String::from("Hello from Lettre! A mailer library for Rust")), 
            )
            .singlepart(
                SinglePart::builder()
                    .header(header::ContentType::TEXT_HTML)
                    .body(order_email_content),
            ),
    )
    .unwrap();

This passes but the email received includes only the string of the path.

I am newbie to Rust. Thanks.

Question: How could i include the html from handlebars(order_email_content) to use it on body of lettre?

Note: Printing reg (the handlebare variable) gives:

Handlebars { templates: {}, helpers: ["if", "lt", "raw", "or", "len", "unless", "with", "log", "lookup", "lte", "ne", "and", "not", "gt", "eq", "gte", "each"], decorators: ["inline"], strict_mode: false, dev_mode: false }

But printing order_email_content gives string "src/emails/order_email.hbs"


Solution

  • Looking at the examples in the handlebar documentation, something like this should work:

    let mut reg = Handlebars::new();
    reg.register_template_file ("email", "src/emails/order_email.hbs").unwrap();
    let order_email_content = reg.render ("email", &serde_json::json!({"data" : email_order.body, "orderNumber": 3333, "amount": 555})).unwrap();
    

    Or:

    let mut reg = Handlebars::new();
    let order_email_content = reg.render_template (
       include_str!("src/emails/order_email.hbs"),
       &serde_json::json!({"data": email_order.body, "orderNumber": 3333, "amount": 555})).unwrap();