import os
import requests
url = "https://api.sendgrid.com/v3/mail/send"
headers = {
"Authorization": f"Bearer {os.environ['SENDGRID_API_KEY']}",
"Content-Type": "application/json"
}
data = {
"personalizations": [{"to": [{"email": "user@example.com"}]}],
"from": {"email": "noreply@example.com"},
"subject": "Test email",
"content": [{"type": "text/plain", "value": "Hello world"}]
}
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.text)
import os
import httpx
url = "https://api.sendgrid.com/v3/mail/send"
headers = {
"Authorization": f"Bearer {os.environ['SENDGRID_API_KEY']}",
"Content-Type": "application/json"
}
data = {
"personalizations": [{"to": [{"email": "user@example.com"}]}],
"from": {"email": "noreply@example.com"},
"subject": "Test email",
"content": [{"type": "text/plain", "value": "Hello world"}]
}
with httpx.Client() as client:
response = client.post(url, headers=headers, json=data)
response.raise_for_status()
print(response.text)
import fetch from 'node-fetch';
import { env } from 'process';
const url = 'https://api.sendgrid.com/v3/mail/send';
const headers = {
'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
'Content-Type': 'application/json'
};
const data = {
personalizations: [{ to: [{ email: 'user@example.com' }] }],
from: { email: 'noreply@example.com' },
subject: 'Test email',
content: [{ type: 'text/plain', value: 'Hello world' }]
};
(async () => {
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify(data)
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const text = await response.text();
console.log(text);
})();
import axios from 'axios';
import { env } from 'process';
const url = 'https://api.sendgrid.com/v3/mail/send';
const headers = {
'Authorization': `Bearer ${env.SENDGRID_API_KEY}`,
'Content-Type': 'application/json'
};
const data = {
personalizations: [{ to: [{ email: 'user@example.com' }] }],
from: { email: 'noreply@example.com' },
subject: 'Test email',
content: [{ type: 'text/plain', value: 'Hello world' }]
};
(async () => {
try {
const response = await axios.post(url, data, { headers });
console.log(response.data);
} catch (error) {
if (error.response) {
console.error('Error:', error.response.status, error.response.data);
} else {
console.error('Error:', error.message);
}
}
})();
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
)
type Personalization struct {
To []struct {
Email string `json:"email"`
} `json:"to"`
}
type Email struct {
Email string `json:"email"`
}
type Content struct {
Type string `json:"type"`
Value string `json:"value"`
}
type RequestBody struct {
Personalizations []Personalization `json:"personalizations"`
From Email `json:"from"`
Subject string `json:"subject"`
Content []Content `json:"content"`
}
func main() {
url := "https://api.sendgrid.com/v3/mail/send"
apiKey := os.Getenv("SENDGRID_API_KEY")
if apiKey == "" {
log.Fatal("SENDGRID_API_KEY environment variable not set")
}
body := RequestBody{
Personalizations: []Personalization{{
To: []struct{ Email string `json:"email"` }{
{Email: "user@example.com"},
},
}},
From: Email{Email: "noreply@example.com"},
Subject: "Test email",
Content: []Content{{
Type: "text/plain",
Value: "Hello world",
}},
}
jsonData, err := json.Marshal(body)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
log.Fatalf("Request failed with status %d: %s", resp.StatusCode, string(body))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(body))
}
<?php
$url = 'https://api.sendgrid.com/v3/mail/send';
$apiKey = getenv('SENDGRID_API_KEY');
if (empty($apiKey)) {
die('SENDGRID_API_KEY environment variable not set');
}
$data = [
'personalizations' => [
['to' => [['email' => 'user@example.com']]]
],
'from' => ['email' => 'noreply@example.com'],
'subject' => 'Test email',
'content' => [
['type' => 'text/plain', 'value' => 'Hello world']
]
];
$options = [
'http' => [
'header' => [
"Authorization: Bearer $apiKey",
"Content-Type: application/json"
],
'method' => 'POST',
'content' => json_encode($data),
'ignore_errors' => true
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
$error = error_get_last();
die('Request failed: ' . $error['message']);
}
$httpResponse = $http_response_header;
if (strpos($httpResponse[0], 'HTTP/') === 0 && strpos($httpResponse[0], '20') !== 0) {
die('Request failed with status: ' . $httpResponse[0]);
}
echo $result;
require 'net/http'
require 'json'
require 'uri'
url = URI.parse('https://api.sendgrid.com/v3/mail/send')
api_key = ENV.fetch('SENDGRID_API_KEY')
body = {
personalizations: [{ to: [{ email: 'user@example.com' }] }],
from: { email: 'noreply@example.com' },
subject: 'Test email',
content: [{ type: 'text/plain', value: 'Hello world' }]
}
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url.path, 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{api_key}")
request.body = body.to_json
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
raise "Request failed with status #{response.code}: #{response.body}"
end
puts response.body
import Foundation
let url = URL(string: "https://api.sendgrid.com/v3/mail/send")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(ProcessInfo.processInfo.environment["SENDGRID_API_KEY"] ?? "")", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let body: [String: Any] = [
"personalizations": [["to": ["email": "user@example.com"]]],
"from": ["email": "noreply@example.com"],
"subject": "Test email",
"content": [["type": "text/plain", "value": "Hello world"]]
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Error: \(error)")
return
}
guard let httpResponse = response as? HTTPURLResponse else {
print("Invalid response")
return
}
guard (200...299).contains(httpResponse.statusCode) else {
print("Request failed with status \(httpResponse.statusCode)")
return
}
if let data = data, let responseBody = String(data: data, encoding: .utf8) {
print(responseBody)
}
}
task.resume()
RunLoop.main.run()
use reqwest::blocking::Client;
use std::env;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = "https://api.sendgrid.com/v3/mail/send";
let api_key = env::var("SENDGRID_API_KEY")?;
let client = Client::new();
let body = serde_json::json!({
"personalizations": [{"to": [{"email": "user@example.com"}]}],
"from": {"email": "noreply@example.com"},
"subject": "Test email",
"content": [{"type": "text/plain", "value": "Hello world"}]
});
let response = client
.post(url)
.header("Authorization", format!("Bearer {}", api_key))
.header("Content-Type", "application/json")
.json(&body)
.send()?;
if !response.status().is_success() {
return Err(format!("Request failed with status: {}", response.status()).into());
}
let body = response.text()?;
println!("{}", body);
Ok(())
}
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
var url = "https://api.sendgrid.com/v3/mail/send";
var apiKey = Environment.GetEnvironmentVariable("SENDGRID_API_KEY");
if (string.IsNullOrEmpty(apiKey))
{
Console.WriteLine("SENDGRID_API_KEY environment variable not set");
return;
}
var body = new
{
personalizations = new[] { new { to = new[] { new { email = "user@example.com" } } } },
from = new { email = "noreply@example.com" },
subject = "Test email",
content = new[] { new { type = "text/plain", value = "Hello world" } }
};
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync(url, body);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}