Content is user-generated and unverified.

How to Automate Email Replies with AI When You Can't Access Corporate APIs

Many professionals face the same frustrating limitation: you receive repetitive emails that could easily be automated, but your corporate IT policies prevent you from adding API integrations to your work email system.

If you're stuck manually crafting the same responses over and over again, there's a clever workaround that combines email forwarding, Google Apps Script, and AI to create a powerful automation system that works around corporate restrictions.

The Problem

As a non-365 administrator, you can't add API calls to Outlook to automate email replies using an LLM. But you still need to respond to dozens of similar requests efficiently while maintaining a professional, personalized touch.

The Solution

This automation uses a simple but effective approach:

  1. Corporate email forwards specific emails to Gmail (using Outlook rules)
  2. Google Apps Script monitors Gmail for forwarded messages
  3. AI generates personalized replies using your standard templates
  4. Generated responses are sent back to your work email for review and forwarding

The entire system runs for free (or nearly free) and bypasses corporate API restrictions entirely.

Step-by-Step Implementation

Phase 1: Initial Setup

1. Create a dedicated Gmail account

  • Go to gmail.com and create a new personal account
  • Choose something like yourname.automation@gmail.com
  • Select "Personal" (not Business) to avoid Google Workspace fees

2. Set up Google Cloud Project

  • Visit console.cloud.google.com
  • Create a new project (name it "Email Automation")
  • Navigate to "APIs & Services" > "Library"
  • Enable both "Gmail API" and "Generative Language API"

3. Configure OAuth credentials

  • Go to "APIs & Services" > "Credentials"
  • Click "Create Credentials" > "OAuth client ID"
  • Configure OAuth consent screen (External user type)
  • Create desktop application credentials
  • Download the JSON credentials file

4. Set up Outlook forwarding rule

  • In Outlook: File > Manage Rules & Alerts > New Rule
  • Choose "Apply rule on messages I receive"
  • Set conditions for emails you want automated (specific senders, keywords, etc.)
  • Action: "Forward it to people or public group" → your new Gmail address
  • Important: Add exception to prevent forwarding emails FROM your Gmail address (to avoid loops)

Phase 2: Apps Script Development

5. Create Google Apps Script project

  • Visit script.google.com
  • Create new project, name it "Email Reply Automation"
  • Link it to your Google Cloud project in Project Settings

6. Get Gemini API key

  • Go to aistudio.google.com/app/apikey
  • Create API key (starts with "AIza...")
  • In Apps Script: Project Settings > Script Properties
  • Add property: Name = GEMINI_API_KEY, Value = your API key

7. Implement the automation code

Here's the complete automation script (customize the templates for your use case):

javascript
function processForwardedEmails() {
  try {
    console.log("Starting email processing...");
    
    // Look for unread forwarded emails
    var threads = GmailApp.search('is:unread subject:"FW:" OR subject:"Fwd:"', 0, 10);
    console.log("Found " + threads.length + " unread forwarded threads");
    
    for (var i = 0; i < threads.length; i++) {
      var thread = threads[i];
      var messages = thread.getMessages();
      var latestMessage = messages[messages.length - 1];
      var emailBody = latestMessage.getPlainBody();
      
      console.log("Processing email " + (i+1) + ": " + thread.getFirstMessageSubject());
      
      // Check for template keyword at start of email
      var templateType = 'standard'; // default
      if (emailBody.toLowerCase().startsWith('template2')) {
        templateType = 'alternative';
        emailBody = emailBody.substring(9).trim(); // Remove keyword
      }
      
      var originalSubject = extractOriginalSubject(emailBody, thread.getFirstMessageSubject());
      
      console.log("Generating reply with template:", templateType);
      var reply = generateReply(emailBody, templateType);
      
      console.log("Sending reply to work email...");
      sendReplyToSelf(originalSubject, emailBody, reply);
      
      thread.markRead();
    }
    
    console.log("Processing complete!");
  } catch (error) {
    console.log("Error: " + error.toString());
  }
}

function generateReply(emailBody, templateType) {
  try {
    var apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
    
    var template = '';
    var instructions = '';
    
    if (templateType === 'alternative') {
      template = `Hi {NAME_OF_ORIGINAL_SENDER},

Thank you for your inquiry. I'd be happy to help you with this request.

[Your alternative template content here]

Please let me know if you have any questions.

Best regards,
[Your Name]`;
      
      instructions = 'Use this alternative template and replace {NAME_OF_ORIGINAL_SENDER} with the sender\'s first name only.';
      
    } else {
      template = `Hi {NAME_OF_ORIGINAL_SENDER},

Thank you for reaching out.

[Your standard template content here]

I look forward to hearing from you.

Best regards,
[Your Name]`;
      
      instructions = 'Use this standard template and replace {NAME_OF_ORIGINAL_SENDER} with the sender\'s first name only.';
    }
    
    var prompt = `${instructions}

TEMPLATE:
${template}

EMAIL TO RESPOND TO:
${emailBody}

CUSTOMIZED REPLY:`;

    var payload = {
      'contents': [{
        'parts': [{
          'text': prompt
        }]
      }]
    };
    
    var options = {
      'method': 'POST',
      'headers': {
        'Content-Type': 'application/json',
      },
      'payload': JSON.stringify(payload)
    };
    
    var response = UrlFetchApp.fetch(
      `https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key=${apiKey}`,
      options
    );
    
    var data = JSON.parse(response.getContentText());
    
    if (data.candidates && data.candidates[0] && data.candidates[0].content) {
      return data.candidates[0].content.parts[0].text;
    } else {
      return "Error generating reply - please check manually";
    }
    
  } catch (error) {
    console.log("Gemini API error: " + error.toString());
    return "Error generating reply: " + error.toString();
  }
}

function extractOriginalSubject(emailBody, forwardedSubject) {
  // Try to find original subject in forwarded email body
  var subjectMatch = emailBody.match(/Subject:\s*(.+)/i);
  
  if (subjectMatch && subjectMatch[1]) {
    return subjectMatch[1].trim();
  }
  
  // Fallback: remove "Fw:" from Gmail subject
  return forwardedSubject.replace(/^(Fw:|Fwd:)\s*/i, '').trim();
}

function sendReplyToSelf(originalSubject, originalBody, generatedReply) {
  var subject = "AUTOMATED REPLY - " + originalSubject;
  var body = "Generated Reply:\n" + generatedReply + "\n\n--- Original Email ---\n" + originalBody;
  
  // Replace with your work email address
  GmailApp.sendEmail("your.work.email@company.com", subject, body);
}

Phase 3: Testing and Deployment

8. Test the system

  • Send a test email to your work address that matches your forwarding rule
  • Verify it gets forwarded to Gmail
  • Run processForwardedEmails() in Apps Script
  • Check that you receive the generated reply at your work email

9. Set up automatic execution

  • In Apps Script: Triggers > Add Trigger
  • Choose processForwardedEmails function
  • Time-driven trigger: every 5-15 minutes
  • Save the trigger

10. Customize for your workflow

  • Replace template content with your actual standard replies
  • Adjust the Outlook forwarding rule criteria
  • Modify template selection keywords as needed

Advanced Features

Multiple Templates

To use different templates, add keywords to the beginning of forwarded emails:

  • Standard template: forward normally
  • Alternative template: add "template2" at the start of the email body before forwarding

Template Selection Strategy

You can expand this system to handle various scenarios:

  • Customer support inquiries
  • Partnership requests
  • Student questions
  • Vendor communications

Cost Considerations

  • Google Apps Script: Free
  • Gmail API: Free for personal use
  • Gemini API: Free tier covers most usage (15 requests/minute, 1,500/day)
  • Total monthly cost: $0-5 even with heavy usage

Key Benefits

  1. Works around corporate restrictions - no API access needed to your work email
  2. Maintains personal touch - AI customizes responses with sender names and context
  3. Full control - you review every response before sending
  4. Scalable - easily add new templates and rules
  5. Cost-effective - runs for free or nearly free
  6. Time-saving - reduces repetitive email tasks by 80-90%

Troubleshooting Tips

  • Infinite loops: Ensure your Outlook rule excludes emails from your Gmail address
  • API errors: Double-check your Gemini API key in Script Properties
  • Permission issues: Make sure your Gmail account is added as a test user in Google Cloud Console
  • No emails processed: Verify your forwarding rule is working and emails are marked as unread

Security Considerations

  • Keep your OAuth credentials secure and never share them
  • Your automation only processes emails you explicitly forward
  • All generated responses go to your work email for review before sending
  • The system runs in Google Cloud's secure environment

Conclusion

This automation solution demonstrates that corporate IT restrictions don't have to limit your productivity. By creatively combining existing tools and services, you can build powerful workflow automations that save hours of manual work while maintaining professional standards.

The key is thinking outside the box - sometimes the best solution isn't a direct API integration, but a clever workaround that achieves the same result. With this system in place, you can focus on higher-value work while AI handles your routine email responses.

Ready to implement this for your own workflow? Start with the setup steps above and customize the templates for your specific use case. The entire system can be built and deployed in under an hour.

Content is user-generated and unverified.
    How to Automate Email Replies with AI When You Can't Access Corporate APIs | Claude