Api sendgrid com v3 mail send with atahcemnrt php
To send an email using the SendGrid API v3 with PHP, you'll need to follow these steps:
Step 1: Create a SendGrid account and obtain an API key
- Go to the SendGrid website and sign up for an account.
- Once you've created an account, go to the "Settings" > "API Keys" page.
- Click on the "Create API Key" button and choose the "v3" API version.
- Note down the API key, you'll need it later.
Step 2: Install the SendGrid PHP library
You can install the SendGrid PHP library using Composer:
composer require sendgrid/sendgrid
Step 3: Set up the SendGrid API client
Create a new PHP file and add the following code:
require 'vendor/autoload.php';
use SendGrid\Mail\Mail;
use SendGrid\Email;
// Set your SendGrid API key
$apiKey = 'YOUR_API_KEY_HERE';
// Create a new SendGrid API client
$client = new \SendGrid($apiKey);
Replace YOUR_API_KEY_HERE
with your actual SendGrid API key.
Step 4: Create a new email message
Create a new email message using the Mail
class:
$mail = new Mail();
$mail->setFrom('[email protected]', 'Your Name');
$mail->setSubject('Test email from SendGrid');
$mail->addContent('text/plain', 'Hello, this is a test email!');
Step 5: Add attachments (optional)
If you want to add attachments to your email, you can use the addAttachment
method:
$mail->addAttachment('path/to/attachment.txt', 'text/plain', 'attachment.txt');
Step 6: Send the email
Finally, send the email using the send
method:
$response = $client->send($mail);
The send
method returns a response object that contains information about the email send, such as the message ID and the status of the send.
Full code example
Here's the full code example:
<?php
require 'vendor/autoload.php';
use SendGrid\Mail\Mail;
use SendGrid\Email;
// Set your SendGrid API key
$apiKey = 'YOUR_API_KEY_HERE';
// Create a new SendGrid API client
$client = new \SendGrid($apiKey);
// Create a new email message
$mail = new Mail();
$mail->setFrom('[email protected]', 'Your Name');
$mail->setSubject('Test email from SendGrid');
$mail->addContent('text/plain', 'Hello, this is a test email!');
// Add an attachment (optional)
$mail->addAttachment('path/to/attachment.txt', 'text/plain', 'attachment.txt');
// Send the email
$response = $client->send($mail);
// Print the response
print_r($response);
?>
Make sure to replace YOUR_API_KEY_HERE
with your actual SendGrid API key.