Community Knowledge Base

Automating Login to SmarterMail

Companies using SmarterMail can easily automate user entry into the mail application by configuring auto-login functionality and the SmarterMail API. The code samples (Python and PHP) shown below demonstrate how you can make a text link or button on a website (e.g. "Log into your mail") that automatically logs a user in to the SmarterMail site. This implementation of auto-login works seamlessly across domains, so the two applications do not have to be hosted on the same server. (Though the code should run on the SmarterMail server.)

Some notes about the example code listed below:

IMPORTANT: Code provided is for informational purposes only. It is not guaranteed to work, especially without input by a seasoned or knowledgeable programmer. In addition, if other languages are required, the provided code can be used as a guideline. However, SmarterTools will not generate sample code in other languages. Finally, autoLoginTokens are one-time use and only last 10 minutes.

We have the form values set to generic text (e.g. "domain@example.com") to show where you would hard coded values that are submitted to the login page. You could also dynamically generate these values using a scripting language like .NET, PHP, or any other. You'd simply substitute hard coded values using variables generated by your code.

The serverEndpoint, https://mail.example.com, uses the default hostname of the SmarterMail web interface. If you have created a separate website for SmarterMail or if you assign a different IP address for SmarterMail within IIS, this action would have to be altered to reflect this change. In addition, this code assumes that your SmarterMail site is secured with SSL/TLS, which it should be.

Auto-Login Sample Python Code

    
import requests  # run 'pip install requests' to get this 

# All the code here should be happening SERVER SIDE
# Once you have 'autoLoginUrl' you can render an html page with a button or redirect the user to this URL.


serverEndpoint = "https://mail.example.com"
userEmail = "domain@example.com"
systemAdminUser = "admin"
systemAdminPass = "admin"

def handle_response_error"("prefix, response):
# Checks if the response indicates success; prints message and exits if not.
if not response.status_code == 200:
print(f"Error: [{prefix}] Received status code {response.status_code}")
return True
data = response.json()
if not data.get('success', True): # Assuming 'success' key indicates success status
print(f"Error: [{prefix}] {data.get('message', 'Unknown error')}")
return True
return False

# STEP 1: Login to System Admin
login_response = requests.post(f"{serverEndpoint}/api/v1/auth/authenticate-user",
json={
"username": systemAdminUser,
"password": systemAdminPass
},
headers={'Content-Type': 'application/json'})

if handle_response_error("SystemAdminLogin", login_response):
exit(1) # Exits if there was an error

login_response_data = login_response.json()
accessToken = login_response_data['accessToken']

# Splitting user and domain from email
user, domain = userEmail.split("@")

# STEP 2: Make a login token
login_token_response = requests.post(f"{serverEndpoint}/api/v1/auth/retrieve-login-token",
json={
"username": user,
"domain": domain
},
headers={
'Content-Type': 'application/json',
'Authorization': f'Bearer {accessToken}'
})

if handle_response_error("RetrieveLoginToken", login_token_response):
exit(1) # Exits if there was an error

login_token_data = login_token_response.json()

autoLoginUrl = login_token_data['autoLoginUrl']

# For demonstration purposes, printing the auto login URL
print("Auto Login URL:", autoLoginUrl)

Auto-Login Sample PHP Code

                                             
                                                 <?php 

$serverEndpoint = "https://mail.example.com";
$userEmail = "domain@example.com";
$systemAdminUser = "admin";
$systemAdminPass = "admin";

function handle_response_error($prefix, $response) {
if ($response['statusCode'] != 200) {
echo "Error: [$prefix] Received status code " . $response['statusCode'] . "\n";
return true;
}
$data = $response['data'];
if (isset($data->success) && !$data->success) { // Assuming 'success' key indicates success status
echo "Error: [$prefix] " . ($data->message ?? 'Unknown error') . "\n";
return true;
}
return false;
}

function make_request($url, $payload, $headers) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

return [
'data' => json_decode($response),
'statusCode' => $statusCode
];
}

// STEP 1: Login to System Admin
$loginResponse = make_request("$serverEndpoint/api/v1/auth/authenticate-user", [
"username" => $systemAdminUser,
"password" => $systemAdminPass
], ['Content-Type: application/json']);

if (handle_response_error("SystemAdminLogin", $loginResponse)) {
exit(1); // Exits if there was an error
}

$accessToken = $loginResponse['data']->accessToken;

// Splitting user and domain from email
list($user, $domain) = explode("@", $userEmail);

// STEP 2: Make a login token
$loginTokenResponse = make_request("$serverEndpoint/api/v1/auth/retrieve-login-token", [
"username" => $user,
"domain" => $domain
], [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken
]);

if (handle_response_error("RetrieveLoginToken", $loginTokenResponse)) {
exit(1); // Exits if there was an error
}

$autoLoginUrl = $loginTokenResponse['data']->autoLoginUrl;

// For demonstration purposes, printing the auto login URL
echo "Auto Login URL: " . $autoLoginUrl . "\n";

?>