How to Send an Email in Any Language Using the Nylas APIs

By using the Nylas APIs we can easily send emails using any language that supports REST APIs. We’re going to see examples on PHP, Rust and C#

How to Send an Email in Any Language Using the Nylas APIs

If you’ve been reading our posts, then you know how to send emails using Ruby, Python and Node.

But you may be wondering, can I use something else? Can I use PHP, Rust or C#?

Well, the simple answer is yes, we absolutely can. Nylas provides APIs, not only SDKs, so we can use any available programming language that supports Rest API calls.

We’re going to display some examples and take them more as a proof-of-concept than real applications. There are several ways to consume APIs and the intention of this blog post is just to show one way of doing that.

Sending an Email using PHP and Nylas Apis

First, we need to have PHP installed as well as Composer (A dependency manager for PHP). Using Composer, we need to install dotenv which will allow us to read .env files.

$ composer require vlucas/phpdotenv

Inside the .env file we need to pass our access token that we can easily gather from the Nylas Dashboard.


Then, we can create our script and call it SendEmail.php

# Import your dependencies

# Load env variables
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);

# Initialize variables
$result = "";
# If we're working with a POST method
# Required fields for Email API
$fields = array(
            'subject' => $_POST["subject"],
            'body' => $_POST["body"],
            'to' => array([
                 'name' => $_POST["to_name"],
                 'email' => $_POST["to_email"]

# Headers with Authorization and type
$headr = array();
$headr[] = 'Accept: application/json';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: Bearer ' . $_ENV['ACCESS_TOKEN'];

# Call the Send Email API
$ch = curl_init( "" );
# Encode the data as JSON
$payload = json_encode( $fields );
# Submit the Email information
curl_setopt( $ch, CURLOPT_POSTFIELDS, $payload );
# Submit the Headers
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headr);
# We're doing a POST
curl_setopt($ch, CURLOPT_POST, true);
# Return response instead of printing.
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($ch);
# Close request

<!-- Create the Form -->
	<h2>Send an Email using PHP and the Nylas APIs</h2>
	<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
	To Name: <input type="text" name="to_name">
	To Email: <input type="text" name="to_email">
	Subject: <input type="text" name="subject">
	Body: <textarea name="body" rows="5" cols="40"></textarea>
	<input type="submit" name="submit" value="Submit"> 
	echo "$result";

Instead of saving this on our Apache folder, we will keep it where our PHP scripts reside and simply type this on the terminal:

$ php -S

This will call PHP’s internal web server. Going to our favourite browser we can pass the following address


And a form will be displayed

PHP Send Form

We need to fill in the recipient’s name, the recipient’s email, the subject and the body of the email. Once we press Submit, we will get a raw response indicating that everything was fine.

PHP Email Sent

The email was successfully delivered.

You can check the Github repo here.

You can watch the LiveStream video here.

Sending an Email using Rust and Nylas Apis

Next, let’s use Rust. We’re going to use Cargo (Rust’s Dependency Manager) which is bundled inside Rust.

$ cargo new send_email

This will create two different files. The first one called Cargo.toml

name = "send_email"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at

reqwest = { version = "0.11", features = ["json"] } # reqwest with JSON parsing support
futures = "0.3" # for our async / await blocks
tokio = { version = "1.12.0", features = ["full"] } # for our async runtime
serde_json = "1.0" #to handle json
dotenv = "0.15.0" # for reading .env file

opt-level = 'z'     # Optimize for size.
lto = true          # Enable Link Time Optimization
codegen-units = 1   # Reduce the number of codegen units to increase optimizations.
panic = 'abort'     # Abort on panic
strip = true        # Strip symbols from binary*

The second one called

// Import your dependencies
use reqwest; //HTTP Client
use std::io;
use serde_json::json; //Json handler
use std::env;

// tokio let's us use "async" on our main function
async fn main() {

// Read the .env file
dotenv::dotenv().expect("Failed to read .env file");

// Add the ACCESS_TOKEN to the Authorization string
let mut _access_token = String::new();
_access_token = "Bearer ".to_owned() +  &env::var("ACCESS_TOKEN").expect("Not found");

// Request the parameters
println!("Enter a subject: ");
let mut _subject = String::new();
io::stdin().read_line(&mut _subject)
			 .expect("failed to read");

println!("Enter a name: ");
let mut _name = String::new();
io::stdin().read_line(&mut _name)
              .expect("failed to read");

println!("Enter an email: ");   
let mut _email = String::new();
io::stdin().read_line(&mut _email)
              .expect("failed to read");

println!("Enter the body: ");              
let mut _body = String::new();
io::stdin().read_line(&mut _body)
              .expect("failed to read");

let trim_subject = _subject.trim();
let trim_name = _name.trim();
let trim_email = _email.trim();
let trim_body = _body.trim();

// Create the JSON structure
let _fields = json!({
	"subject": &trim_subject,
	"to": [
      "email": &trim_email,
      "name": &trim_name
  "body": &trim_body,

    let client = reqwest::Client::new(); //Create HTTP client
    let response = client //Call API passing parameters
		.header("Authorization", _access_token.to_string())
		.header("Content-type", "application/json")
		.header("Accept", "application/json")
        .unwrap() // Give the back the result of panic if it fails
        .text() // Convert it to plain text
    println!("{:?}", response);

We must not forget to create the .env file


Once we have everything, we need to release our application by typing on the terminal:

$ cargo build --release

Once it’s has been built

$ ./send_email
Rust Email Sent

Just like in the PHP example, the email was successfully delivered.

You can check the Github repo here.

You can watch the LiveStream video here.

Sending an Email using C# and Nylas Apis

Finally, we’re going to use C#. And for this, we’re going to need to install Visual Studio Code.

To start, let’s head to our Terminal and type the following:

$ mkdir send_email && cd send_email

Once we created a new folder and entered that folder, we need to type:

$ dotnet new console

That will create the following files: Program.cs and send_email.csproj

Now, we need to open Visual Studio Code and press Open.

Visual Studio Code

Then, choose your folder send_email and open it.

Open folder

This will open up the editor and your files.

On send_email.csproj we need to include the following code:

<Project Sdk="Microsoft.NET.Sdk">


   <PackageReference Include="DotNetEnv" Version="2.3.0" />
   <PackageReference Include="RestSharp" Version="106.15" />


The RestSharp package will help us to consume REST APIs and the DotNetEnv will help us read .env files

This is the code for the Program.cs file

// Import packages
using RestSharp;
using System;

// Load .env file

// Ask via the user via console
Console.WriteLine("Enter subject:");
string _subject = System.Console.ReadLine();
Console.WriteLine("Enter name:");
string _name = System.Console.ReadLine();
Console.WriteLine("Enter email:");
string _email = System.Console.ReadLine();
Console.WriteLine("Enter body:");
string _body = System.Console.ReadLine();
// Create a new Rest Client and call the Nylas API endpoint
var client = new RestSharp.RestClient("");
// Wait until the connection is done
client.Timeout = -1;
// We want a POST method
var request = new RestSharp.RestRequest(Method.POST);
// Adding header and authorization
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + System.Environment.GetEnvironmentVariable("ACCESS_TOKEN"));

// Formatting the body of our request
var body = @"{"
   + "\n"
   + $@"    ""body"" : ""{_body}"","
   + "\n"
   + $@"    ""subject"": ""{_subject}"","
   + "\n"
   + $@"    ""to"": ["
   + "\n"
   + @"        {"
   + "\n"
   + $@"            ""name"": ""{_name}"","
   + "\n"
   + $@"            ""email"": ""{_email}"""
   + "\n"
   + @"        }"
   + "\n"
   + @"    ]"
   + "\n"
   + @"}";

// Adding the body as a parameter
request.AddParameter("application/json", body, ParameterType.RequestBody);
// We send the request
IRestResponse response = client.Execute(request);
// Print the response
// Wait for user input before closing the terminal

We must not forget to create the .env file

ACCESS_TOKEN = access_token

Once we have everything, we need to release our application by running it without debugging.

Run without Debugging

This will generate an executable file that we can execute by going to:

$ cd bin/Debug/net6.0

And running the application:

$ ./send_email
C# Email Sent

Just like in the PHP and Rust examples, the email was successfully delivered.

Email delivered

You can check the Github repo here.

If you want to learn more about our Email API, please go to our Email API documentation.

Don’t miss the action, watch our LiveStream Coding with Nylas:

You May Also Like

hero banner
How to Build an Email Responder with Generative AI
How to create and read Google Webhooks using Kotlin
AI solutions
Unleashing intelligence: How Nylas APIs power AI-driven solutions

Subscribe for our updates

Please enter your email address and receive the latest updates.