How to Build an AI Email Generator WordPress Plugin Using Gemini AI

Welcome to ApyCoder. I’m Asif Khan, and in today’s blog, we’re diving into something exciting. In our fast-paced digital age, automation has become essential for boosting productivity. Whether you’re a business professional, a marketer, or just someone looking to simplify your workflow, automating tasks like email generation can save you time and effort.

In this post, I’ll walk you through building a custom WordPress plugin that uses the Gemini AI API to generate emails based on user input, including the subject, tone, and length.

Let’s jump into the details of creating this AI-powered email generator tool.

What You’ll Learn

  • Setting up a custom WordPress plugin
  • Integrating the Gemini AI API to generate content
  • Building a simple form to collect user input
  • Handling form submissions to generate AI-based email content
  • Styling and adding functionality with HTML, CSS, and JavaScript

Prerequisites

Before getting started, you need the following:

  • Basic knowledge of WordPress development (creating plugins, shortcodes, etc.)
  • Familiarity with PHP, HTML, CSS, and JavaScript
  • An API key from the Gemini AI platform

Step 1: Creating the WordPress Plugin

To create the plugin, start by creating a new folder in your WordPress wp-content/plugins/ directory and name it email-generator-tool. Inside this folder, create a PHP file called email-generator-tool.php.

Here’s the full code for the plugin:

<?php
/*
Plugin Name: Email Generator Tool
Description: A plugin to generate emails based on subject, tone, and length.
Version: 1.2
Author: Asif Khan
*/

function email_generator_tool_shortcode() {
    ob_start();
    ?>
    <div class="email-generator-tool-container">
        <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['subject']) && isset($_POST['tone']) && isset($_POST['length'])) {
            echo '<script>document.getElementById("email-generator-tool-loading-spinner").style.display = "block";</script>';
            $api_key = "YOUR_GEMINI_API_KEY"; // Replace with your actual API key
            $url = "https://generativelanguage.googleapis.com/v1/models/gemini-pro:generateContent?key={$api_key}";

            $subject = sanitize_text_field($_POST['subject']);
            $tone = sanitize_text_field($_POST['tone']);
            $length = sanitize_text_field($_POST['length']);

            if (!empty($subject) && !empty($tone) && !empty($length)) {
                $data = array(
                    "contents" => array(
                        array(
                            "role" => "user",
                            "parts" => array(
                                array(
                                    "text" => "Generate an email with the following details:\nSubject: \"$subject\"\nTone: \"$tone\"\nLength: \"$length\""
                                )
                            )
                        )
                    )
                );

                $json_data = json_encode($data);

                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
                curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $response = curl_exec($ch);
                $error = curl_error($ch);
                curl_close($ch);

                echo '<script>document.getElementById("email-generator-tool-loading-spinner").style.display = "none";</script>';

                if ($error) {
                    echo '<div class="email-generator-tool-error">Curl error: ' . esc_html($error) . '</div>';
                } else {
                    $responseData = json_decode($response, true);

                    if (isset($responseData['candidates'][0]['content']['parts'][0]['text'])) {
                        $generated_email = $responseData['candidates'][0]['content']['parts'][0]['text'];

                        echo '<div class="email-generator-tool-result" id="email-generator-tool-result">';
                        echo '<button class="email-generator-tool-close-btn" onclick="emailGeneratorToolCloseResult()">Close</button>';
                        echo '<h2>Generated Email</h2>';
                        echo '<textarea id="email-generator-tool-generated-text" class="email-generator-tool-textarea">' . esc_textarea($generated_email) . '</textarea>';
                        echo '<button class="email-generator-tool-copy-btn" onclick="emailGeneratorToolCopyToClipboard()">Copy to Clipboard</button>';
                        echo '<button class="email-generator-tool-download-btn" onclick="emailGeneratorToolDownloadAsTxt()">Download as TXT</button>';
                        echo '</div>';
                    } else {
                        echo '<div class="email-generator-tool-error">Failed to generate email. Please try again.</div>';
                    }
                }
            } else {
                echo '<div class="email-generator-tool-error">All fields are required.</div>';
            }
        }
        ?>
        <form id="email-generator-tool-form" method="post">
            <label for="email-generator-tool-subject">Subject:</label>
            <input type="text" id="email-generator-tool-subject" name="subject" placeholder="Enter the subject" required>
            <label for="email-generator-tool-tone">Tone:</label>
            <select id="email-generator-tool-tone" name="tone" required>
                <option value="">Select tone</option>
                <option value="Formal">Formal</option>
                <option value="Casual">Casual</option>
                <option value="Friendly">Friendly</option>
                <option value="Professional">Professional</option>
            </select>
            <label for="email-generator-tool-length">Length:</label>
            <select id="email-generator-tool-length" name="length" required>
                <option value="">Select length</option>
                <option value="Short">Short</option>
                <option value="Medium">Medium</option>
                <option value="Long">Long</option>
            </select>
            <input type="submit" value="Generate Email">
        </form>
        <div class="email-generator-tool-loading-spinner" id="email-generator-tool-loading-spinner"></div>
    </div>
    <style>
        .email-generator-tool-container {
            font-family: Arial, sans-serif;
            background-color: #fff;
            padding: 2rem;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            max-width: 900px;
            width: 90%;
            margin: 2rem auto;
            background-color: #f4f4f4;
            color: #333;
            position: relative;
        }
        .email-generator-tool-container h1 {
            color: #007bff;
            text-align: center;
            margin-bottom: 1rem;
        }
        .email-generator-tool-container label {
            display: block;
            margin-bottom: 0.5rem;
        }
        .email-generator-tool-container textarea,
        .email-generator-tool-container select,
        .email-generator-tool-container input[type="text"] {
            width: 100%;
            padding: 1rem;
            border: 1px solid #ddd;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            box-sizing: border-box;
            font-size: 1rem;
        }
        .email-generator-tool-container input[type="submit"] {
            background-color: #007bff;
            color: #fff;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1.1rem;
            width: 100%;
            transition: background-color 0.3s;
        }
        .email-generator-tool-container input[type="submit"]:hover {
            background-color: #0056b3;
        }
        .email-generator-tool-result {
            margin-top: 1.5rem;
            padding: 1.5rem;
            background-color: #e9ecef;
            border: 1px solid #ddd;
            border-radius: 8px;
            position: relative;
            animation: emailGeneratorToolFadeIn 0.5s ease-in-out;
            max-width: 100%;
        }
        .email-generator-tool-close-btn,
        .email-generator-tool-copy-btn,
        .email-generator-tool-download-btn {
            background-color: #28a745;
            color: #fff;
            border: none;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            cursor: pointer;
            font-size: 0.9rem;
            margin-top: 10px;
            margin-right: 10px;
        }
        .email-generator-tool-close-btn:hover,
        .email-generator-tool-copy-btn:hover,
        .email-generator-tool-download-btn:hover {
            background-color: #218838;
        }
        .email-generator-tool-download-btn {
            background-color: #17a2b8;
        }
        .email-generator-tool-download-btn:hover {
            background-color: #138496;
        }
        .email-generator-tool-error {
            color: #dc3545;
            text-align: center;
            margin-top: 1rem;
        }
        .email-generator-tool-loading-spinner {
            display: none;
            width: 50px;
            height: 50px;
            border: 6px solid #f3f3f3;
            border-top: 6px solid #007bff;
            border-radius: 50%;
            animation: emailGeneratorToolSpin 1s linear infinite;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
        @keyframes emailGeneratorToolSpin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        @keyframes emailGeneratorToolFadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        .email-generator-tool-textarea {
            width: 100%;
            height: 400px;
            padding: 1rem;
            border: 1px solid #ddd;
            border-radius: 8px;
            margin-bottom: 10px;
            box-sizing: border-box;
            font-size: 1rem;
            resize: vertical;
        }
        @media (max-width: 768px) {
            .email-generator-tool-container {
                padding: 1rem;
            }
            .email-generator-tool-textarea {
                height: 300px;
            }
            .email-generator-tool-close-btn,
            .email-generator-tool-copy-btn,
            .email-generator-tool-download-btn {
                width: 100%;
                margin: 5px 0;
            }
        }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('email-generator-tool-form').addEventListener('submit', function() {
                document.getElementById('email-generator-tool-loading-spinner').style.display = 'block';
            });
        });

        function emailGeneratorToolCloseResult() {
            document.getElementById('email-generator-tool-result').style.display = 'none';
        }

        function emailGeneratorToolCopyToClipboard() {
            const emailText = document.getElementById('email-generator-tool-generated-text').value;
            navigator.clipboard.writeText(emailText).then(function() {
                alert('Email content copied to clipboard!');
            });
        }

        function emailGeneratorToolDownloadAsTxt() {
            const emailText = document.getElementById('email-generator-tool-generated-text').value;
            const blob = new Blob([emailText], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'generated-email.txt';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }
    </script>
    <?php
    return ob_get_clean();
}

add_shortcode('email_generator_tool', 'email_generator_tool_shortcode');

Explanation

  • WordPress Plugin Setup: We start by defining the plugin name, version, and description in the header section of the PHP file.
  • Form Handling: A form allows users to input email subject, tone, and length.
  • API Request to Gemini AI: Once the form is submitted, the API is triggered using cURL to generate the email content based on the user’s input.
  • Response Handling: The generated email is then displayed on the page, with additional options to copy the email to the clipboard or download it as a .txt file.

Step 2: Getting Your Gemini AI API Key

To use Gemini AI for email generation, you’ll need to get an API key from the Google Cloud Console. After getting your key, replace YOUR_GEMINI_API_KEY in the code above with your actual API key.

Step 3: Installing and Using the Plugin

  1. Save the email-generator-tool.php file inside the email-generator-tool folder.
  2. Visit WordPress admin site by navigating to Plugins > Installed Plugins> and Activate AI email Generator Plugin
  3. Use the shortcode [emailgenerator_tool] to display the email generator form on any page or post.
Live Check : https://apycoder.com/email-generator-tool/

Conclusion

By following the steps outlined, you can create a fully functional AI-powered email generator tool using the Gemini AI API. This tool allows you to streamline your email writing process by generating emails quickly and efficiently, customized to your needs. Whether you’re looking to draft formal business emails, casual messages, or detailed communications, the Gemini AI API provides the flexibility to tailor each email to specific parameters, such as tone, style, and length.

The ability to personalize your emails while reducing the time spent drafting them makes this tool incredibly valuable for professionals and businesses alike. From sales outreach to client follow-ups or internal communications, the AI-powered tool can significantly improve productivity and communication consistency.

By integrating this tool into your daily workflow, you can ensure that your emails are not only well-crafted but also aligned with the specific requirements of each message. The efficiency and precision of the Gemini AI API make it an excellent addition to any professional toolkit.

If you found this guide helpful, I encourage you to explore more of my content on YouTube and my blog. There, you’ll discover additional tutorials and insights into leveraging AI for everyday tasks, as well as tips on how to implement AI-based tools to improve efficiency in both personal and business settings. Stay tuned for more valuable content designed to help you enhance your productivity through technology!

Leave a Comment

Your email address will not be published. Required fields are marked *


Shopping Basket
Scroll to Top