Home > front end >  How to save emails in an email list on SendGrid using Laravel?
How to save emails in an email list on SendGrid using Laravel?

Time:01-13

I'm working on a functionality where once a user signs up for an account, he will start getting a series of email throughout a time period (email drips).

I'm using Laravel. I need to grab the email on sign up and save it on an email list on SendGrid. But I don't find this on the sendgrid/sendgrid-php package's docs.

So, would you please tell me how I may implement this?

CodePudding user response:

It can be done with the sendgrid-php package:

use SendGrid;

$api = new SendGrid(YOUR_API_KEY);
$contacts = [
    [
        'email' => "email@something",
        'address_line_1' => '',
        'city' => '',
        'country' => '',
        'first_name' => '',
        'last_name' => '',
        etc....
    ]
]
$request_body = [
    'contacts' => $contacts
];

$response = $api->client->marketing()->contacts()->put($request_body);
if($response->statusCode() !== 202) {
    // error has occured
}

CodePudding user response:

You can use the SendGrid PHP package for this. Here's an example of how you can do this:

In your signup controller in Laravel:

use SendGrid;
use SendGrid\Mail\To;

class SendGridController extends Controller
{
    public function register(Request $request)
    {
        // ... your rego code
        $apiKey = 'YOUR_API_KEY';
        $sg = new SendGrid($apiKey);

        $list_id = 'YOUR_LIST_ID';

        //Add an email to the list
        $email = new To();
        $email->setEmail($request->input('email'));
        $email->setFirstName($request->input('first_name'));
        $email->setLastName($request->input('last_name'));

        $response = $sg->client->marketing()->lists()->recipients()->post($list_id, $email->jsonSerialize());

        return $response->statusCode();
    }
}

You can also refer to the SendGrid API documentation for more information on how to create, update and delete lists, as well as add and remove recipients.

  • Related