How to Send an Email in Any Language Using the Nylas APIs
Tags: php, rust, csharp
Published: 2022-12-14 08:49:31

If you’ve been reading our posts, then you know how to send emails using [Ruby](https://www.nylas.com/blog/how-to-send-emails-with-the-nylas-ruby-sdk/), [Python](https://www.nylas.com/blog/how-to-send-emails-with-the-nylas-python-sdk/) and [Node](https://www.nylas.com/blog/how-to-send-emails-with-nylas-node-sdk/).

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](https://www.php.net) installed as well as [Composer](https://getcomposer.org) (A dependency manager for PHP). Using Composer, we need to install [dotenv](https://github.com/vlucas/phpdotenv) which will allow us to read .env files.

```bash
$ composer require vlucas/phpdotenv
```

Inside the .env file we need to pass our access token that we can easily gather from the [Nylas Dashboard](https://dashboard.nylas.com).

```bash
ACCESS_TOKEN=access_token
```

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

```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:

```bash
$ 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:

```bash
http://localhost:8000/SendEmail.php
```

And a form will be displayed:

![PHP Email Form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hl9c0a0zwqgy2a598h3r.png)

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 Delivered](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q8of011143068vps8ak3.png)

The email was successfully delivered.

You can check the Github repo [here](https://github.com/nylas-samples/php_send_and_read_emails).

You can watch the LiveStream video [here](https://www.youtube.com/watch?v=MteeGtWaK54&list=PLk-4iahO3b-xd42-RL4DJQyuEoFFYwTbC&index=6&t=750s).

## Sending an Email using Rust and Nylas Apis

Next, let’s use [Rust](https://www.rust-lang.org). We’re going to use Cargo (Rust’s Dependency Manager) which is bundled inside Rust.

```bash
$ cargo new send_email
```

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

```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**:

```rust
// 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:

```bash
ACCESS_TOKEN=access_token
```

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

```bash
$ cargo build --release
```

Once it’s has been built:

```bash
$ ./send_email
```

![Rust Sent Email](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1bwa9o27p7hj5joc66y.png)

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

You can check the Github repo [here](https://github.com/nylas-samples/send_emails_rust_csharp).

You can watch the LiveStream video [here](https://www.youtube.com/watch?v=7gqnMf15fAA&list=PLk-4iahO3b-xd42-RL4DJQyuEoFFYwTbC&index=7&t=863s).

## Sending an Email using C# and Nylas Apis

Finally, we’re going to use [C#](https://dotnet.microsoft.com/en-us/languages/csharp). And for this, we’re going to need to install [Visual Studio Code](https://code.visualstudio.com).

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

```bash
$ mkdir send_email && cd send_email
```

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

```bash
$ 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**:

![VSCode Open File](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hmgmpb4dceav292m0p0l.png)

Then, choose your folder send_email and open it:

![VSCode choose folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6qvudfqbzr4w59iwwvw1.png)

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:

```csharp
// 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:

```bash
ACCESS_TOKEN = access_token
```

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

![Run without debugging](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k5l61402snmft781e7t3.png)

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

```bash
$ cd bin/Debug/net6.0
```

And running the application:

```bash
$ ./send_email
```

![CSharp Email Sent](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eavsl35htvmxu62o5aex.png)

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

![Email received](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y0487rndxc7xsoaw5aag.png)

You can check the Github repo [here](https://github.com/nylas-samples/send_emails_rust_csharp).

You can check the Github repo [here](https://www.youtube.com/watch?v=7gqnMf15fAA&list=PLk-4iahO3b-xd42-RL4DJQyuEoFFYwTbC&index=7&t=863s).

If you want to learn more about our Email API, please go to our [Email API documentation](https://developer.nylas.com/docs/connectivity/email/).