1
votes

I am using the Email::SendGrid::V3 Perl library and my goal is to send one e-mail to many recipients by greeting them using their first name. I however cannot figure out how to perform the personalization using their online documentation:

https://metacpan.org/pod/Email::SendGrid::V3#$self-%3Eset_section($key,-$value);

I can send a single email to two different persons but I lack information on how to approach the body substitutions.

use Email::SendGrid::V3;

my $sg = Email::SendGrid::V3->new(api_key => 'ABCDE');

my $result = $sg->from('[email protected]')
->subject('This is a subject line')
->add_envelope( to => [ {email => '[email protected]', name => 'John Smith' }] )
->set_section('-NAME-', 'John')
->add_content('text/html', 'Hello -NAME-, how are you?')
->send;

print $result->{success} ? "It worked" : "It failed: " . $result->{reason};

Any hint will be greatly appreciated.

2

2 Answers

2
votes

I had the chance to get quick feedback from the developer, and the solution is the following:

my $result = $sg->from('[email protected]')
->subject('This is a subject line')
->add_content('text/html', 'Hello -NAME-, how are you?')
->add_envelope( to => [ {email => '[email protected]', name => 'Fred Smith' }], substitutions => { '-NAME-' => 'Fred' } )
->add_envelope( to => [ {email => '[email protected]', name => 'John Smith' }], substitutions => { '-NAME-' => 'John' } )
->send;
1
votes

This is just templating; you have a template, and you want to fill in values. Text::Template is a straightforward implementation of this, though since your result is HTML, you want an HTML-aware template engine like Text::Xslate or Mojo::Template so you don't have to remember to HTML-escape each value. There is also Template::Toolkit that is the overall most-used and most configurable templating system. Below is an example using Mojo::Template.

use strict;
use warnings;
use Mojo::Template;

my $mt = Mojo::Template->new(vars => 1, auto_escape => 1);
my $template = 'Hello <%= $name %>, how are you?';
my $rendered = $mt->render($template, {name => 'John'});