How to use AI for email writing
Quick answer
Use the
gpt-4o model from OpenAI's API to generate email drafts by providing prompts describing the email's purpose. Call client.chat.completions.create with your prompt to receive polished email text automatically.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the OpenAI Python SDK and set your API key as an environment variable for secure access.
pip install openai>=1.0 Step by step
This example shows how to generate a professional email draft using the gpt-4o model with the OpenAI Python SDK v1.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = "Write a professional email to schedule a meeting with a client next week."
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": prompt}]
)
email_text = response.choices[0].message.content
print(email_text) output
Subject: Meeting Scheduling for Next Week Dear [Client's Name], I hope this message finds you well. I would like to schedule a meeting with you next week to discuss our ongoing projects and next steps. Please let me know your availability so we can arrange a convenient time. Looking forward to your response. Best regards, [Your Name]
Common variations
You can customize the email style by changing the prompt or use different models like gpt-4o-mini for faster responses. Async calls and streaming completions are also supported for advanced use cases.
import asyncio
import os
from openai import OpenAI
async def generate_email():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
prompt = "Write a friendly follow-up email after a job interview."
response = await client.chat.completions.acreate(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}]
)
print(response.choices[0].message.content)
asyncio.run(generate_email()) output
Subject: Following Up on Our Interview Hi [Interviewer’s Name], Thank you again for the opportunity to interview for the [Job Title] position. I enjoyed learning more about the team and the role. Please let me know if you need any additional information from me. Looking forward to hearing from you. Best, [Your Name]
Troubleshooting
- If you get authentication errors, verify your
OPENAI_API_KEYenvironment variable is set correctly. - If responses are incomplete, increase
max_tokensin the API call. - For rate limit errors, implement exponential backoff retries.
Key Takeaways
- Use
gpt-4owith OpenAI SDK v1 for reliable email generation. - Customize prompts to tailor email tone and content precisely.
- Set
OPENAI_API_KEYsecurely in your environment variables. - Async and smaller models like
gpt-4o-minioffer flexible performance options. - Handle API errors by checking keys, token limits, and rate limits.