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

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.

ACCESS_TOKEN=access_token

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

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
# Import your dependencies
require_once('vendor/autoload.php');
# Load env variables
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
# Initialize variables
$result = "";
# If we're working with a POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
# 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( "https://api.nylas.com/send" );
# 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
curl_close($ch);
}
?>
<!-- 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">
  <br><br>
  To Email: <input type="text" name="to_email">
  <br><br>  
  Subject: <input type="text" name="subject">
  <br><br>
  Body: <textarea name="body" rows="5" cols="40"></textarea>
  <br><br>
  <input type="submit" name="submit" value="Submit"> 
  </form>

<?php
  echo "$result";
?>  

</body>
</html>

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 127.0.0.1:8000

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

http://localhost:8000/SendEmail.php

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.

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

[package]
name = "send_email"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
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
[profile.release]
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 main.rs

// 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
#[tokio::main]
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
    .post("https://api.nylas.com/send")
    .header("Authorization", _access_token.to_string())
    .header("Content-type", "application/json")
    .header("Accept", "application/json")
    .json(&_fields)
    .send()
        .await
        .unwrap() // Give the back the result of panic if it fails
        .text() // Convert it to plain text
        .await;

    println!("{:?}", response);
}

We must not forget to create the .env file

ACCESS_TOKEN=access_token

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.

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">
 <PropertyGroup>
   <OutputType>Exe</OutputType>
   <TargetFramework>net6.0</TargetFramework>
   <ImplicitUsings>enable</ImplicitUsings>
   <Nullable>enable</Nullable>
 </PropertyGroup>
 <ItemGroup>
   <PackageReference Include="DotNetEnv" Version="2.3.0" />
   <PackageReference Include="RestSharp" Version="106.15" />
 </ItemGroup>
</Project>

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
DotNetEnv.Env.Load();
DotNetEnv.Env.TraversePath().Load();
// 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("https://api.nylas.com/send");
// 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
Console.WriteLine(response.Content);
// Wait for user input before closing the terminal
Console.Read();

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: