Arun
Arun

Reputation: 51

How to call the name and mail address in dynamic html file using Sendgrid?

What I Need!

I need to include the mail address wherever I want in my HTML mail template.

What I do!

Sending around 1000 mail per day, so my mail template should be dynamic.

I have to upload an HTML design which should fetch name and email address from the CSV file.

Fetching the information is working fine for me, but I need to use data which i need in HTML template.

Please let me know how to do it? Thanks

      <?php 
        require 'vendor/autoload.php'; 
        use Exception;
        use SendGrid;
        use SendGrid\Mail\Subject;
        use SendGrid\Mail\From;
        use SendGrid\Mail\Content;
        use SendGrid\Mail\Mail;
        use SendGrid\Mail\TypeException;
        use SendGrid\Mail\Personalization;
        use SendGrid\Mail\To;
        use SendGrid\Response;

        //  Define API key first (must be a string) - or quit if you don't have the API key for SendGrid
        $apiKey = "xxxxxxxx";

        //  This collection is for email addresses
        //  Maybe better to verify entries first
        $text= file_get_contents('design.html');
        $content =  $text;

        $file = 'info.csv';
        $content = file($file);

        $array = array();

        for($i = 0; $i < count($content); $i++) {
            $line = explode(',', $content[$i]);
            for($j = 0; $j < count($line); $j++) {
                $array[$i][$j + 1] = $line[$j];
            }
        }
        $emailAddresses = array_column($array, 1);
        $username = array_column($array, 2);

        //  Verify first if you really have addresses!
        if (count($emailAddresses) === 0) {
            die("Nope");
        }

        //  Create the initial mail to send to every recipient
        try {
            $mailFrom = new From("xxxxxxx");
            $mailSubject = new Subject("This is my subject");
            $mailContent = new Content("text/html", $text);

            //  Create the message
            $mail = new Mail($mailFrom);
            $mail->setSubject($mailSubject);
            $mail->addContent($mailContent);
            } catch (TypeException $e) {
            die("Your parameter is failing: " . $e->getMessage());
        }

        //  Iterate for every recipient
        foreach ($emailAddresses as $address) {
            try {
                //  Create new Personalization instance
                $personalization = new Personalization();
                //  Append To recipient
                $personalization->addTo(new To($address) ,
                [
                    "name" => $username,
                    "email" => $address
                ]);

                //  Append onto Mail
                $mail->addPersonalization($personalization);
                } catch (TypeException $e) {
                //  This address is failing!
                //  (Just ignore this address)
                echo "\nThis address is failing: " . $e->getMessage();
            }
        }

        //  Not having Personalizations added? Quit
        if ($mail->getPersonalizationCount() === 0) {
            die("No recipients for your mail. Sorry");
        }

        try {
            //  Create SendGrid instance
            $client = new SendGrid($apiKey);

            //  Send the mail and fetch Response
            // $response = $client->send($mail);

            //  Not having expected response?
            if (($response instanceof Response) === false) {
                //  Unknown response given
                die("Unclear response");
            }

            //  Review/evaluate response status and body (json formatted)
            echo "Got HTTP " . $response->statusCode() . ":\n" . $response->body();
            } catch (Exception $e) {
            die("It failed! " . $e->getMessage());
        }
     ?>

"design.html"

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>{{name}}</h1>
    <h1>{{email}}</h1>
</body>
</html>

What I got in the mail

enter image description here

Upvotes: 0

Views: 774

Answers (1)

Paul Denisevich
Paul Denisevich

Reputation: 2414

Add this to your code after $personalization->addTo line:

$personalization->addSubstitution('%name%', "John Doe");

You can then use that variable.

You can also try this:

$mail->addDynamicTemplateDatas([
    '%name%' => 'John Doe',
]);

After that, use it in your HTML:

Hello, %name%!

Upvotes: 1

Related Questions