sendgrid / sendgrid-php

The Official Twilio SendGrid PHP API Library
https://sendgrid.com
MIT License
1.49k stars 624 forks source link

Add sections #176

Closed louposk closed 6 years ago

louposk commented 8 years ago

Hello, i am using the API key when sending and email. I have added the following:

$sendgrid = new \SendGrid(env('SENDGRID_KEY', 'sendgrid'));
$email = new \SendGrid\Email();

$email
        ->addTo(xxxxxx)
        ->setFrom('xxxxxxxxx')
        ->setFromName('Web Services')
        ->setSubject('My subject')
        // set html or text to an empty space (see http://git.io/hCNy)
        ->setHtml($serial)
        ->setText('Text Hello!') // <-- triggers the plaintext version of the template
        ->setSections(array("%office%" => "an office", "%home%" => "your house"))
        ->addFilter('templates', 'enabled', 1)
        ->addFilter('templates', 'template_id','xxxxxxxxxxxxxx');

but the sections %office% and %home% are not inserted in the template.I cannot see the text "an office" and "your home" but i see just %office% and %home% when i send the email.

What am i doing wrong?

louposk commented 8 years ago

Ok seemed that i had to add the ->addSubtitution parameters among all others.

geekdevs commented 8 years ago

This still does not seem to work for me (using ->addSection())

thinkingserious commented 8 years ago

HI @geekdevs,

Could you please reach out to our support team for assistance? https://support.sendgrid.com. Please provide the relevant source code so they can troubleshoot more easily. Thanks!

psavard commented 7 years ago

Hey @geekdevs,

Have you been able to resolve this "addSection" problem?

I seem to have the same problem here...

Thanks,

thinkingserious commented 7 years ago

Hello @psavard,

Perhaps I can help you. Could you please provide the following:

  1. Version of the library you are using.
  2. Sample code.

Thanks!

Elmer

geekdevs commented 7 years ago

@psavard no, sorry. I had to solve it urgently at that time and found some workaround.

psavard commented 7 years ago

In fact, the problem seems to be with the sendgrid API, I have extract my API call from the code and injected it in Postman to trigger the sending of the Sendgrid template and I have the exact same problem, the template don't seem to interpret the sections.

Sendgrid php version : 5.4.2

Here is the cURL export of the postman call :

curl -X POST \
  https://api.sendgrid.com/v3/mail/send \
  -H 'accept: application/json' \
  -H 'authorization: ************************** \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'postman-token: ************************** \
  -H 'user-agent: sendgrid/5.4.2;php' \
  -d '{
    "from":{
        "email":"someone@someplace.com"
    },
    "personalizations":[
        {
            "to":[
                {
                    "name":"test1",
                    "email":"anotherone@someplace.com"
                }
            ],
            "substitutions":{
                "-name-":"Another One",
                "-abs_url-":"http:\/\/someplace.com\/"
            }
        }
    ],
    "subject":"Some subject",
    "content":[
        {
            "type":"text\/html",
            "value":"Dummy content"
        }
    ],
    "sections":{
        "-salutation-":"Hello -name-",
        "-paragraph1-":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
        "-paragraph2-":"To continue, click on the link below",
        "-action_text-":"Click Here"
    },
    "template_id":"********-****-****-****-************"
}'

and my sendgrid template :

<html>
<head>
    <title></title>
</head>
<body>
    <div>
        <div>-salutation-,</div>

        <div>-paragraph1-</div>

        <div>-paragraph2-</div>

        <a href="-abs_url-/someaction.php" target="_blank">-action_text-</a>
    </div>
</body>
</html>

With this result I see 2 possibilities :

  1. Sections tag is supported with the template sytem
  2. There is a bug in the Sendgrid API

What is your though on this one?

Thanks for your help!

thinkingserious commented 7 years ago

Hi @psavard,

I have re-opened this issue so I can try to assist further. This is issue is now on our backlog.

With Best Regards,

Elmer

CyberPunkCodes commented 7 years ago

I also am having issues getting sections working. They seem to just not work. The code below is ripped from my Yii2. Once I get it pushed (very soon) the full code could be inspected. However, I have gotten everything else to work. So I am pretty sure it's on SendGrid's API end.

$mailer = Yii::$app->mailer;
$message = $mailer->compose()
    ->setTo($to)
    ->setFrom(['alerts@example.com' => 'Alerts'])
    ->setReplyTo('noreply@example.com')
    ->setSubject('Hey -username-, Read This Email')
    ->setHtmlBody('Dear -username-,<br><br>My HTML message here<br><br>%section1%')
    ->setTextBody('Dear -username-,\n\nMy Text message here\n\n%section1%')
    ->addSection('%section1%', 'This is the header')
    ->addSubstitution('-username-', $user->username)
    ->send();

From my Message class:

public $sections;

public function addSection($key, $val)
{
    $this->sections[$key] = (string) $val;
    return $this;
}

// --- down where i build the message

if ( isset($this->sections) && is_array($this->sections) ) {
    foreach ($this->sections as $key => $val) {
        $this->getSendGridMail()->addSection($key, $val);
    }
}

I apologize for the Yii2 reference. My code will be viewable soon. However, I am confident that this isn't on my end and this library or the SendGrid API is not handling it properly.

The full code can be seen here: https://github.com/WadeShuler/yii2-sendgrid

thinkingserious commented 7 years ago

Thanks for the additional feedback @WadeShuler, I've added your vote to this issue.

Since this likely not a library issue, you will get the best assistance from our support team. That said, this is still on our backlog and will continue to gain priority as we get more reactions and comments.

psavard commented 7 years ago

@thinkingserious : is there a way for me to view the sendgrid support ticket?

thinkingserious commented 7 years ago

Hello @psavard,

When you submit your support request, you should receive an email with that information. If you did not receive an email, can you please provide your sendgrid username and when you reached out to dx@sendgrid.com? Thanks!

psavard commented 7 years ago

I've dug a little more on this problem and I've finally made it worked correctly. In order to work, the sections should be referenced in the substitution section and we should reference this substitution in the template instead of using the section directly.

So, the JSON should looks like this :

{
    "from":{
        "email":"someone@someplace.com"
    },
    "personalizations":[
        {
            "to":[
                {
                    "name":"test1",
                    "email":"anotherone@someplace.com"
                }
            ],
            "substitutions":{
                "-name-":"Another One",
                "-abs_url-":"http:\/\/someplace.com\/",
                "-salutation_section-":"-salutation-",
                "-p1_section-":"-paragraph1-",
                "-p2_section-":"-paragraph2-",
                "-action_section-":"-action_text-",
            }
        }
    ],
    "subject":"Some subject",
    "content":[
        {
            "type":"text\/html",
            "value":"Dummy content"
        }
    ],
    "sections":{
        "-salutation-":"Hello -name-",
        "-paragraph1-":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
        "-paragraph2-":"To continue, click on the link below",
        "-action_text-":"Click Here"
    },
    "template_id":"********-****-****-****-************"
}

and the template shoud contains something like :

<html>
<head>
    <title></title>
</head>
<body>
    <div>
        <div>-salutation_section-,</div>

        <div>-p1_section-</div>

        <div>-p2_section-</div>

        <a href="-abs_url-/someaction.php" target="_blank">-action_section-</a>
    </div>
</body>
</html>

ref : https://sendgrid.com/docs/Classroom/Build/Add_Content/substitution_and_section_tags.html#-Complex-Section-and-Substitution-01

thinkingserious commented 7 years ago

Thanks for sharing the solution @psavard. Please email us at dx@sendgrid.com referencing this issue so we can send you some swag :)

CyberPunkCodes commented 7 years ago

@psavard This seems to be a work around hack, not "properly".

The sections should work simply by passing them as:

"sections":{
    "-section1-": "This is my section",
},

Then of course, referencing -section1- in the template/content.

While your way might work, SendGrid should actually fix it so they work like they are supposed to.

mbernier commented 7 years ago

@WadeShuler The substitution method is the only way to get a section into the mail/send call. The reason that sections are passed via substitutions is to allow for greater flexibility. I am very familiar with the extra confusion that this causes...

The substitutions method allows you to set the same substitution parameter for everyone, but pass in different sections as the value of the substitutions using logic on your side. I will give an example:

Use Case: Real Estate emails for a customer:

"substitutions":{
    "-propertySearchUpdate-": "-customerUpdate",
},

Substitutions for the Agent:

//on the email for the seller
"substitutions":{
    "-propertySearchUpdate-": "-agentUpdate",
},

Sections for the send:

"sections":{
    "-customerUpdate-": "Properties <HTML for buyer of houses>",
    "-agentUpdate-": "We sent the following properties to your customer and here are all the internal notes for each property: <HTML of properties>"
}

This would allow you to perform the same send, with different sections - using the same substitution.