Sendgrid mail typescript
Here is an example of how to use SendGrid with TypeScript:
Step 1: Install SendGrid
Run the following command in your terminal:
npm install sendgrid
Step 2: Import SendGrid
In your TypeScript file, import SendGrid:
import { SendGrid } from '@sendgrid/mail';
Step 3: Set up SendGrid
Create a SendGrid object and set your API key:
const sg = new SendGrid('YOUR_SENDGRID_API_KEY');
Step 4: Send an email
Use the send
method to send an email:
sg.send({
to: '[email protected]',
from: '[email protected]',
subject: 'Hello from SendGrid!',
text: 'Hello from SendGrid!',
html: '<strong>Hello from SendGrid!</strong>'
});
Step 5: Handle errors
Use a try-catch block to handle any errors that may occur:
try {
sg.send({
to: '[email protected]',
from: '[email protected]',
subject: 'Hello from SendGrid!',
text: 'Hello from SendGrid!',
html: '<strong>Hello from SendGrid!</strong>'
});
} catch (error) {
console.error(error);
}
Full example
Here is the full example:
import { SendGrid } from '@sendgrid/mail';
const sg = new SendGrid('YOUR_SENDGRID_API_KEY');
try {
sg.send({
to: '[email protected]',
from: '[email protected]',
subject: 'Hello from SendGrid!',
text: 'Hello from SendGrid!',
html: '<strong>Hello from SendGrid!</strong>'
});
} catch (error) {
console.error(error);
}
TypeScript configuration
To use TypeScript with SendGrid, you need to configure your TypeScript settings to include the @sendgrid/mail
package. You can do this by adding the following lines to your tsconfig.json
file:
{
"compilerOptions": {
//... other options...
"typeRoots": ["node_modules/@types"],
"types": ["@sendgrid/mail"]
}
}
This tells TypeScript to include the @sendgrid/mail
package in your type checks.