Practice: (M)ai(l) Replies

Oil painting of an ai writing mails.

In an era where digital communication predominates, our inboxes often resemble a daunting fortress besieged by a relentless wave of messages. Amid this digital deluge, a revolutionary ally has emerged: AI-generated email response suggestions.
Today, I’ll walk you through how to set up this, using a web server capable of hosting PHP scripts and a Google Mail account. It’s simpler than you might think, and the benefits are substantial.

Setting the Stage with a Web Server and PHP

First things first, you’ll need an OpenAI API-Key and a web server that can run PHP scripts. On this server, you’ll deploy two crucial PHP files: credentials.php and mailResponseServer.php.

  • The former is straightforward – it securely stores your OpenAI API key, the golden ticket to accessing powerful AI capabilities, as $api_key = "sk-...";.
  • The latter, mailResponseServer.php, is the workhorse that processes incoming emails, consults the OpenAI API for a sparkling, AI-crafted response, and sends this suggestion back to an email address of your choosing.

Getting the code you can easily clone my repo or find the code below.

Code of mailResponseServer.php

<?php
require_once 'credentials.php';

$emailSubject = $_POST['subject'] ?? 'empty subject';
$emailSubjectEncoded = mb_encode_mimeheader($emailSubject, 'UTF-8', 'B');
$emailBody = $_POST['body'] ?? 'empty mail text';
$senderEmail = $_POST['sender'] ?? 'empty sender';

$receiverEmail = 'SenderToBeProcssed@anymail.net';  // Mail adress the AIs response-mailtext should be sent to
// Description of you personally to create better fitting mail responses
$whoAmI = "You are a helpful assistant answering the mails in the role of a 40 year old software developer, married with a beautiful wife. You have 2 kids and live in Germany near Bielefeld."

function getChatGptResponse($text) {
    global $api_key;
    $curl = curl_init('https://api.openai.com/v1/chat/completions');
    
    $postData = json_encode([
        'model' => 'gpt-4-turbo-preview',
        'messages' => [
            ["role" => "system", "content" => $whoAmI],
            ["role" => "user", "content" => $text]
        ],
    ]);
    
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $api_key,
        ],
    ]);
    
    $response = curl_exec($curl);
    curl_close($curl);
    $decodedResponse = json_decode($response, true);
    
    return $decodedResponse['choices'][0]['message']['content'] ?? 'Sorry, I could not process that.';
}

if ($senderEmail == 'SenderToBeProcssed@anymail.net') { // The php script only processes mails from this sender(s)
    
    $emailBody = getChatGptResponse($emailBody);

    $headers = 'From: ' . $senderEmail . "\r\n" .
    'Reply-To: ' . $senderEmail . "\r\n" .
    'Content-Type: text/plain; charset=UTF-8' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

    mail($receiverEmail, $emailSubjectEncoded, $emailBody, $headers);
}
?>

Enlisting Google’s Help

The next step involves a bit of teamwork with your Google Mail account. Here, you’ll set up a Google Apps Script triggered (Trigger > Add new Trigger) every minute to scout for new messages.

Code of Google Apps Scrip

function checkEmailsAndCallPhp() {
  var threads = GmailApp.getInboxThreads(0, 5); // Get first 5 threads from inbox
  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    for (var j = 0; j < messages.length; j++) {
      var message = messages[j];
      var sender = message.getFrom();
      if (sender.includes("SenderToBeProcssed@anymail.net")) { // The Google Apps Script only processes mails from this sender
        if (message.isUnread()) {   // Only process unread messages to not process a mail twice
          var subject = message.getSubject();
          var body = message.getPlainBody();
          var emailFrom = sender;
          var url = 'https://www.....com/mailResponseServer.php'; // Path to php-script on your web server
          var payload = {
            'subject': subject,
            'body': body,
            'sender': emailFrom
          };
          var options = {
            'method': 'post',
            'contentType': 'application/x-www-form-urlencoded',
            'payload': payload
          };
          
          UrlFetchApp.fetch(url, options);
          message.markRead();  // Mark processed message as read to not process it twice
        }
      }
    }
  }
}

When this Google Apps Script detects one unread mail from your specified mail account, it hands off the email’s text to your mailResponseServer.php script on you web server, kickstarting the process of generating an AI-powered reply suggestion.

The Magic Unfolds

Imagine this: An email arrives, and within moments an AI presents you with an reply suggestion. This isn’t just about saving time; it’s about enhancing the quality of your communication.

Revolution at Your Fingertips

In summary, with a simple web server setup and a sprinkle of Google magic, AI-generated email reply suggestions are not just a futuristic fantasy. They’re a practical, attainable tool that can significantly enhance your digital communication experience.

Feedback

If you have any comments, ideas, suggestions or other feedback about this article, feel free to send me an email at Feedback[at]scrummastersmind.com.