Load sent mail templates via API

As you may have noticed, if you send some custom e-mail from Post Affiliate Pro 4 merchant panel via Emails > Send message, then the particular template gets saved and you can  load it anytime by clicking the "Load email from template ..." link
 
But what if you wish to load such a saved custom e-mail template via API?

Here is a sample script that loads all the saved custom templates:
 
<?php
//the PapApi.class.php can be downloaded from the merchant panel:
// Tools > Integration > API Integration > Download PAP API

include 'PapApi.class.php'; 

//----------------------------------------------
// login (as merchant owner)

$session = new Pap_Api_Session("http://URL_TO_PAP/scripts/server.php");

if(!$session->login("merchant@example.com","demo")) {  //change it here for your username/password
  die("Cannot login. Message: ".$session->getMessage());
} 

$request = new Gpf_Rpc_GridRequest("Gpf_Mail_SentMailTemplatesGrid", "getRows", $session);

try {
  $request->sendNow();
} catch(Exception $e) {
  die("API call error: ".$e->getMessage());
}

// request was successful, get the grid result
$grid = $request->getGrid();
// get recordset from the grid
$recordset = $grid->getRecordset();

// let's display the ID of mail template, date of creation, subject and html body of each e-mail template
foreach($recordset as $rec) {
  echo 'ID: '.$rec->get('id').' || Created: ' . $rec->get('created'). ' || Subject: ' . $rec->get('subject') .
  ' <br> Email body: <br>' . getEmailBody ($rec->get('id'), $session) . '<hr><hr>';
}

//This function loads the html body of a particular e-mail template
function getEmailBody ($templateid, $session){
	$request = new Gpf_Rpc_FormRequest("Gpf_Mail_EmailTemplateEditForm", "load", $session);
	$request->setField('Id',$templateid);
	
	try {
		$request->sendNow();
	} catch(Exception $e) {
		die("API call error: ".$e->getMessage());
	}

	$responseForm = $request->getForm();
	if($responseForm->isSuccessful()) {
		return $responseForm->getFieldValue('body_html');
	}
}

?>
 
In case you wish to load only a particular e-mail template and you know its ID (the above mentioned script loads the ID) then you can use the following script (getEmailBody function from above) after you initiate a merchant session (as in the script above):
$request = new Gpf_Rpc_FormRequest("Gpf_Mail_EmailTemplateEditForm", "load", $session);
$request->setField('Id','e052cc81'); //ID of the saved custom e-mail template
	
	try {
	  $request->sendNow();

	} catch(Exception $e) {
		die("API call error: ".$e->getMessage());
	}

$responseForm = $request2->getForm();

if($responseForm->isSuccessful()) {
  echo $responseForm->getFieldValue('subject');
  echo '<br>';
  echo $responseForm->getFieldValue('body_html');
  echo '<br>';
  echo $responseForm->getFieldValue('body_text');
  echo '<br>';
  echo $responseForm->getFieldValue('classname');
  echo '<br>';
  echo $responseForm->getFieldValue('created');
  echo '<br>';
}