File size: 35,228 Bytes
ff6872d
1dc28ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
# Step-by-Step Guide: Building an AI Agent to Craft High-Converting Emails with AI/ML API (2025)

## Table of Contents
- [Introduction](#introduction)
  - [AI/ML API](#aiml-api)
- [Prerequisites](#prerequisites)
- [Gradio App Building from Scratch](#gradio-app-building-from-scratch)
  - [Step 1: Set Up Your Project](#step-1-set-up-your-project)
  - [Step 2: Create python vertual environment and activate it.](#step-2-create-python-vertual-environment-and-activate-it)
  - [Step 3: Install Dependencies](#step-3-install-dependencies)
  - [Step 4: Import Libraries and Load Environment Variables](#step-4-import-libraries-and-load-environment-variables)
  - [Step 5: Map Outreach Types to Instruction Files](#step-5-map-outreach-types-to-instruction-files)
  - [Step 6: Define Additional Fields Configuration](#step-6-define-additional-fields-configuration)
  - [Step 7: Create Functions for Dynamic Behavior](#step-7-create-functions-for-dynamic-behavior)
  - [Step 8: Build the Gradio Interface](#step-8-build-the-gradio-interface)
  - [Step 9: Launch the App](#step-9-launch-the-app)
- [Setup](#setup)
- [Usage](#usage)
  - [Select Email Outreach Type](#select-email-outreach-type)
  - [Enter Additional Details](#enter-additional-details)
  - [Generate Email](#generate-email)
  - [View and Copy Email](#view-and-copy-email)
- [Example](#example)
  - [Cold Email Outreach](#cold-email-outreach)
  - [Guest Blogging Outreach](#guest-blogging-outreach)
- [Conclusion](#conclusion)

## Introduction

The AI Email Crafting Tool is a web-based app.

It uses Gradio for a friendly, interactive interface.

The tool generates hyper-personalized outreach emails.

It leverages the AI/ML API and OpenAI library for content creation.

Choose from 7 types of email outreach for different needs.

### AI/ML API

AI/ML API is a game-changing platform for developers and SaaS entrepreneurs looking to integrate cutting-edge AI capabilities into their products. It offers a single point of access to over 200 state-of-the-art AI models, covering everything from NLP to computer vision.

Key Features for Developers:

* Extensive Model Library: 200+ pre-trained models for rapid prototyping and deployment. 📚
* Customization Options: Fine-tune models to fit your specific use case. 🎯
* Developer-Friendly Integration: RESTful APIs and SDKs for seamless incorporation into your stack. 🛠️
* Serverless Architecture: Focus on coding, not infrastructure management. ☁️

![AIML API](/images/aimlapi.png)

[Get Started for FREE](https://aimlapi.com/?via=ibrohim).

Use the code `IBROHIMXAIMLAPI` and [get 1 week FREE access](https://aimlapi.com/?via=ibrohim).

[Deep Dive](https://docs.aimlapi.com/) into AI/ML API Documentation.

Here's a brief tutorial: [How to get API Key from AI/ML API. Quick step-by-step tutorial with screenshots for better understanding.](https://medium.com/@abdibrokhim/how-to-get-api-key-from-ai-ml-api-225a69d0bb25)

## Prerequisites:
- Python 3.7+ installed. 
- AI/ML API Key.

## Gradio App Building from Scratch
Follow these steps to build the Gradio app:

### Step 1: Set Up Your Project
Create a new project folder.
```bash
mkdir email-agent
cd email-agent
```

Create a Python file, e.g., `app.py`. We'll be writing our Gradio app in this file.

```bash
touch app.py
```

Save your 7 instruction `.txt` files in `prompts` folder.

```bash
mkdir prompts
```

- `cold_email_outreach.txt`

```markdown
Title: Cold Email Outreach Instructions

Objective:
Craft a hyper-personalized, professional cold outreach email for a prospect with no prior relationship. The goal is to establish an initial connection, clearly present a value proposition, and invite a conversation.

Instructions:
1. Research Deeply:
   - Investigate the recipient’s company, industry, role, recent news, or achievements.
   - Identify potential pain points or opportunities specific to their context.
2. Personalized Greeting:
   - Address the recipient by their first name.
   - Use a friendly, yet professional tone.
3. Engaging Opening:
   - Start with a personalized hook that references your research (e.g., a recent company milestone or industry trend).
4. Clear Value Proposition:
   - Explain succinctly how your offering addresses a specific need or challenge.
   - Highlight the unique benefits tailored to the recipient’s context.
5. Specific Call to Action (CTA):
   - Propose a clear next step (e.g., scheduling a call, meeting, or reply).
6. Concise and Clear Format:
   - Use short paragraphs and bullet points if needed.
   - Ensure the email is easy to scan and understand.
7. Sniper Approach:
   - Apply hyper-personalization by incorporating detailed, research-driven insights.
   - Avoid generic or template language—make every sentence relevant.
8. Professional Sign-Off:
   - End with a friendly, professional closing including your full name, title, and contact information.
```

- `warm_email_outreach.txt`

```markdown
Title: Warm Email Outreach Instructions

Objective:
Develop a hyper-personalized email that leverages previous interactions or mutual connections. The email should nurture the relationship and provide a timely update or opportunity for further engagement.

Instructions:
1. Reference Past Interactions:
   - Clearly mention any previous meeting, conversation, or mutual introduction.
   - Reference specifics from earlier interactions (e.g., shared interests or previous discussion points).
2. Warm Greeting:
   - Address the recipient by name and use a friendly, conversational tone.
3. Recap & Update:
   - Briefly remind them of your last interaction.
   - Introduce a relevant update, opportunity, or new value proposition that builds on that relationship.
4. Clear Call to Action (CTA):
   - Suggest a specific next step, such as a follow-up call or meeting.
5. Tone & Personalization:
   - Maintain an approachable yet professional tone.
   - Ensure the email feels like a continuation of an ongoing dialogue.
6. Sniper Approach:
   - Use hyper-personalization by including details that resonate with the recipient’s interests or recent activities.
7. Professional Sign-Off:
   - Conclude with your name, title, and clear contact details.
```

- `customer_development_outreach.txt`

```markdown
Title: Customer Development Outreach Instructions

Objective:
Create a hyper-personalized email aimed at understanding potential customers’ needs and gathering valuable feedback. The email should invite the recipient to share insights that can help shape your product or service.

Instructions:
1. Detailed Research:
   - Investigate the recipient’s company, industry trends, and potential challenges.
   - Identify areas where your offering might provide a solution.
2. Thoughtful Introduction:
   - Introduce yourself and your company clearly.
   - Explain the purpose of the outreach as an opportunity to gather insights.
3. Open-Ended Questions:
   - Ask questions that encourage the recipient to share their challenges, needs, or feedback.
   - Ensure the questions are clear and specific.
4. Value Proposition & Context:
   - Briefly mention how your product or service might address their challenges, without being overly salesy.
5. Specific Call to Action (CTA):
   - Invite the recipient to reply with their thoughts or schedule a short discussion.
6. Tone & Personalization:
   - Maintain an empathetic, professional tone.
   - Apply hyper-personalization by referencing industry-specific challenges or recent trends.
7. Organized Format:
   - Use clear sections or bullet points to highlight questions and key points.
8. Professional Sign-Off:
   - Close with your name, title, and relevant contact information.
```

- `link_building_outreach.txt`

```markdown
Title: Link-Building Outreach Instructions

Objective:
Craft a hyper-personalized email to request or negotiate a link placement. The email should demonstrate how linking your content is mutually beneficial while referencing specific details from the recipient’s website.

Instructions:
1. In-Depth Website Research:
   - Explore the recipient’s website to understand their niche, content style, and audience.
   - Identify specific pages or articles that relate to your content.
2. Personalized Greeting:
   - Address the recipient by name and open with a compliment or reference to their recent content.
3. Establish Relevance:
   - Explain why your content is a good fit for their site.
   - Highlight the mutual benefits, such as improved SEO or enhanced content value.
4. Clear Value Proposition:
   - Articulate the specific advantages of linking your content.
5. Specific Call to Action (CTA):
   - Propose a concrete next step, such as reviewing your content or scheduling a brief call.
6. Tone & Style:
   - Maintain a respectful, concise, and professional tone.
7. Sniper Approach:
   - Use hyper-personalization by citing specific articles or content details.
8. Clear Formatting:
   - Use bullet points or numbered lists if needed to enhance clarity.
9. Professional Sign-Off:
   - End with your name, title, and contact details.
```

- `influencer_outreach.txt`

```markdown
Title: Influencer Outreach Instructions

Objective:
Develop a hyper-personalized email designed to engage an influencer for collaboration or partnership. The email should reference specific details about their work and audience while presenting a mutually beneficial proposal.

Instructions:
1. Thorough Research:
   - Study the influencer’s social channels, content style, and audience demographics.
   - Identify specific posts, campaigns, or achievements that stand out.
2. Personalized Greeting:
   - Address the influencer by name and open with a sincere compliment referencing their work.
3. Collaboration Proposal:
   - Clearly state the purpose of the outreach.
   - Explain how a partnership or collaboration aligns with both parties’ interests.
4. Value Proposition:
   - Detail the unique benefits for the influencer (e.g., exposure to a new audience, valuable content).
5. Specific Call to Action (CTA):
   - Suggest a concrete next step, such as a meeting or call to discuss ideas.
6. Tone & Authenticity:
   - Use a friendly, genuine, and professional tone.
   - Avoid overly formal language; be authentic and engaging.
7. Sniper Approach:
   - Include hyper-personalized elements that reference recent content or specific audience insights.
8. Clear Structure:
   - Use well-organized paragraphs or bullet points for readability.
9. Professional Sign-Off:
   - Close with your name, title, and full contact information.
```

- `guest_blogging_outreach.txt`

```markdown
Title: Guest Blogging Outreach Instructions

Objective:
Compose a hyper-personalized email to inquire about guest blogging opportunities. The email should highlight your expertise, reference the target website’s content, and propose topics that add value to their audience.

Instructions:
1. Comprehensive Website Research:
   - Review the target website’s content, style, and audience interests.
   - Identify specific articles or themes that align with your expertise.
2. Personalized Greeting & Introduction:
   - Address the recipient by name and introduce yourself briefly.
   - Establish credibility by mentioning relevant experience or achievements.
3. Clear Proposal:
   - State your interest in contributing a guest post.
   - Propose specific topics or ideas that complement their existing content.
4. Value Proposition:
   - Explain how your contribution will provide added value to their readers.
5. Specific Call to Action (CTA):
   - Suggest scheduling a call or follow-up discussion to refine ideas.
6. Tone & Personalization:
   - Use a professional yet approachable tone.
   - Ensure the message feels custom-tailored by referencing recent content.
7. Sniper Approach:
   - Include details that indicate thorough research of the website (e.g., citing specific articles).
8. Organized Format:
   - Structure the email with clear paragraphs and bullet points for topic ideas.
9. Professional Sign-Off:
   - End with your name, title, and complete contact details.
```

- `review_and_rating_outreach.txt`

```markdown
Title: Review and Rating Outreach Instructions

Objective:
Create a hyper-personalized email to request reviews or ratings from customers or partners. The email should express gratitude, reference the recipient’s specific experience, and highlight how their feedback benefits both parties.

Instructions:
1. Research & Personalization:
   - Gather any available information on the recipient’s experience with your product/service.
   - Reference specific interactions or usage details if possible.
2. Warm Greeting & Gratitude:
   - Begin by thanking the recipient for their support or business.
   - Personalize the opening by mentioning any known details about their experience.
3. Clear Request:
   - Politely ask for a review or rating.
   - Explain why their feedback is valuable—for both you and potential customers.
4. Value Proposition:
   - Briefly mention how their review helps improve the service/product and aids others in making informed decisions.
5. Specific Call to Action (CTA):
   - Provide a clear link or instructions on how to submit the review.
   - Optionally, invite them to reply directly with their thoughts.
6. Tone & Style:
   - Maintain a warm, appreciative, and professional tone.
7. Sniper Approach:
   - Ensure the email reflects hyper-personalization by including any relevant usage details.
8. Clear Structure:
   - Use bullet points or numbered lists to enhance clarity.
9. Professional Sign-Off:
   - Close with your name, title, and full contact details.
```

### Step 2: Create python vertual environment and activate it.
```bash
python3 -m venv .venv
source venv/bin/activate
```
> on MacOS.

### Step 3: Install Dependencies
Open your terminal. Run:
```bash
pip install gradio openai python-dotenv
```

### Step 4: Import Libraries and Load Environment Variables

Import `gradio`, `openai`, and `dotenv`. 

Use `dotenv` to load the `.env` file with your API key.

```py
import os
import gradio as gr
from openai import OpenAI
from dotenv import load_dotenv

# -----------------------------
# Load environment variables and initialize OpenAI client
# -----------------------------
load_dotenv()
```

Initialize the OpenAI client with your AI/ML API key.

```py
client = OpenAI(
    base_url="https://api.aimlapi.com/v1",
    api_key=os.getenv("AIML_API_KEY"),
)
```

Here's a brief tutorial: [How to get API Key from AI/ML API. Quick step-by-step tutorial with screenshots for better understanding.](https://medium.com/@abdibrokhim/how-to-get-api-key-from-ai-ml-api-225a69d0bb25)

### Step 5: Map Outreach Types to Instruction Files

Create a mapping (dictionary) that links each outreach type to its corresponding `.txt` file.

This will help the app load the correct system instructions.

```py
# -----------------------------
# Mapping of Outreach Type to System Instruction File
# -----------------------------
FILE_MAPPING = {
    "Cold Email Outreach": "cold_email_outreach.txt",
    "Warm Email Outreach": "warm_email_outreach.txt",
    "Customer Development Outreach": "customer_development_outreach.txt",
    "Link-Building Outreach": "link_building_outreach.txt",
    "Influencer Outreach": "influencer_outreach.txt",
    "Guest Blogging Outreach": "guest_blogging_outreach.txt",
    "Review and Rating Outreach": "review_and_rating_outreach.txt",
}

# -----------------------------
# Directory where the system instruction files are stored
# -----------------------------
FILE_DIR = "prompts"
```

### Step 6: Define Additional Fields Configuration

List all extra fields required for each email outreach type.

This allows dynamic display of input fields based on user selection.

```py
# -----------------------------
# Configuration for Additional Fields per Outreach Type
# Each key is the outreach type and its value is a list of field keys.
# (Field keys below match the keys used for our additional input components.)
# -----------------------------
FIELDS_CONFIG = {
    "Cold Email Outreach": ["recipient_name", "recipient_company", "industry", "pain_points"],
    "Warm Email Outreach": ["reference_details"],
    "Customer Development Outreach": ["customer_insights"],
    "Link-Building Outreach": ["target_website_url", "content_reference"],
    "Influencer Outreach": ["influencer_platform", "collaboration_idea"],
    "Guest Blogging Outreach": ["proposed_topics", "your_experience"],
    "Review and Rating Outreach": ["experience_details"]
}

# -----------------------------
# The order of all possible additional field keys (to ensure consistent update order)
# -----------------------------
ALL_FIELD_KEYS = [
    "recipient_name",
    "recipient_company",
    "industry",
    "pain_points",
    "reference_details",
    "customer_insights",
    "target_website_url",
    "content_reference",
    "influencer_platform",
    "collaboration_idea",
    "proposed_topics",
    "your_experience",
    "experience_details",
]
```

### Step 7: Create Functions for Dynamic Behavior

Write a function to show/hide additional fields based on the selected outreach type.

```py
# -----------------------------
# Define the function that updates the visibility of additional fields 
# based on the selected Email Outreach type.
# -----------------------------
def update_additional_fields(selected_type):
    # For each possible field key, set visible True if it is required for this outreach type.
    updates = []
    visible_keys = FIELDS_CONFIG.get(selected_type, [])
    for key in ALL_FIELD_KEYS:
        if key in visible_keys:
            updates.append(gr.update(visible=True))
        else:
            updates.append(gr.update(visible=False, value=""))
    return tuple(updates)
```

Email Generation Function:

Write a function to load the system instruction from the selected file.

```py
# -----------------------------
# Define the function to generate the email using AI/ML API.
#
# This function will:
#  1. Load the system instruction (prompt) from the corresponding .txt file.
#  2. Combine the additional fields into a user prompt.
#  3. Send both messages to the API.
#  4. Return the generated email text (in Markdown format).
# -----------------------------
def generate_email(email_type, 
                   recipient_name, recipient_company, industry, pain_points,
                   reference_details, customer_insights,
                   target_website_url, content_reference,
                   influencer_platform, collaboration_idea,
                   proposed_topics, your_experience,
                   experience_details):
    # Load the system instruction from file
    filename = FILE_MAPPING.get(email_type)
    try:
        with open(FILE_DIR+"/"+filename, "r", encoding="utf-8") as f:
            system_instruction = f.read()
    except Exception as e:
        return f"Error reading system file '{filename}': {e}"
```

Combine user inputs into a single string.

```py
    # Combine additional field values into one additional-information string.
    # Only include fields that have non-empty values.
    additional_fields = {
        "Recipient Name": recipient_name,
        "Recipient Company": recipient_company,
        "Industry": industry,
        "Pain Points": pain_points,
        "Reference Details": reference_details,
        "Customer Insights": customer_insights,
        "Target Website URL": target_website_url,
        "Content Reference": content_reference,
        "Influencer Platform": influencer_platform,
        "Collaboration Idea": collaboration_idea,
        "Proposed Topics": proposed_topics,
        "Your Experience": your_experience,
        "Experience Details": experience_details,
    }
    additional_info = ""
    for label, value in additional_fields.items():
        if value.strip():
            additional_info += f"**{label}:** {value.strip()}\n\n"
    
    if not additional_info:
        additional_info = "No additional details provided."

    # Build the messages list.
    messages = [
        {"role": "system", "content": system_instruction},
        {"role": "user", "content": additional_info}
    ]
```

Call the AI/ML API with a system message and user message. Return the generated email in Markdown format.

```py
    try:
        response = client.chat.completions.create(
            model="gpt-4o",
            messages=messages,
        )
        email_text = response.choices[0].message.content
    except Exception as e:
        email_text = f"Error generating email: {e}"
    
    return email_text
```

### Step 8: Build the Gradio Interface

Use `gr.Blocks` to create the app layout.

```py
with gr.Blocks(title="Email Crafting Tool") as demo:
    
    gr.Markdown("# ✉️ AI Email Crafting Tool")
    gr.Markdown("Craft hyper-personalized outreach emails with ease. Select an outreach type, fill in the additional details, and let the AI generate a tailored email for you.")
```

Add a dropdown for selecting the Email Outreach type.

```py
with gr.Row():
        email_type = gr.Dropdown(
            label="Select Email Outreach Type",
            choices=list(FILE_MAPPING.keys()),
            value="Cold Email Outreach",
            interactive=True
        )
```

Add input fields for additional details.

```py
    with gr.Column(variant="panel"):
        gr.Markdown("### Additional Details")
        # Create additional fields – all initially hidden. They will be shown conditionally.
        recipient_name = gr.Textbox(label="Recipient Name", placeholder="Enter recipient's name", visible=False)
        recipient_company = gr.Textbox(label="Recipient Company", placeholder="Enter recipient's company", visible=False)
        industry = gr.Textbox(label="Industry", placeholder="Enter industry", visible=False)
        pain_points = gr.Textbox(label="Pain Points", placeholder="Enter known challenges or pain points", lines=2, visible=False)
        reference_details = gr.Textbox(label="Reference Details", placeholder="Mention any previous interactions", visible=False)
        customer_insights = gr.Textbox(label="Customer Insights / Questions", placeholder="What insights or questions do you have?", lines=2, visible=False)
        target_website_url = gr.Textbox(label="Target Website URL", placeholder="Enter the target website URL", visible=False)
        content_reference = gr.Textbox(label="Content Reference", placeholder="Mention relevant content or article details", lines=2, visible=False)
        influencer_platform = gr.Textbox(label="Influencer Platform", placeholder="Enter the influencer's platform (e.g., Instagram, YouTube)", visible=False)
        collaboration_idea = gr.Textbox(label="Collaboration Idea", placeholder="Briefly describe the collaboration idea", lines=2, visible=False)
        proposed_topics = gr.Textbox(label="Proposed Topics", placeholder="List one or more guest post topics", lines=2, visible=False)
        your_experience = gr.Textbox(label="Your Experience", placeholder="Share your expertise or experience", lines=2, visible=False)
        experience_details = gr.Textbox(label="Experience Details", placeholder="Describe your experience with the product/service", lines=2, visible=False)
    
    # When the outreach type changes, update the visibility of the additional fields.
    email_type.change(
        fn=update_additional_fields, 
        inputs=email_type, 
        outputs=[
            recipient_name, recipient_company, industry, pain_points,
            reference_details, customer_insights,
            target_website_url, content_reference,
            influencer_platform, collaboration_idea,
            proposed_topics, your_experience,
            experience_details
        ]
    )
```

Add a button to generate the email.

```py
    with gr.Row():
        generate_btn = gr.Button("Generate Email", variant="primary")
```

Add an output component (like `gr.Code`) to display the generated email in Markdown with a copy button (by default there is copy and downlaod functions).

```py
    # Use a gr.Code component to render Markdown and include a built-in copy-to-clipboard button.
    output_email = gr.Code(label="Generated Email (Markdown)", language="markdown")
```

Link the input changes and button clicks to their corresponding functions.

```py
    generate_btn.click(
        fn=generate_email,
        inputs=[
            email_type,
            recipient_name, recipient_company, industry, pain_points,
            reference_details, customer_insights,
            target_website_url, content_reference,
            influencer_platform, collaboration_idea,
            proposed_topics, your_experience,
            experience_details
        ],
        outputs=output_email,
    )
```

Optional: Add a separator line for visual clarity.

```py
    gr.Markdown("___")
    gr.Markdown("© 2025 AI Email Crafting Tool")
```

Full code snippet:

```py
# -----------------------------
# Build the Gradio App Interface
# -----------------------------
with gr.Blocks(title="Email Crafting Tool") as demo:
    
    gr.Markdown("# ✉️ AI Email Crafting Tool")
    gr.Markdown("Craft hyper-personalized outreach emails with ease. Select an outreach type, fill in the additional details, and let the AI generate a tailored email for you.")
    
    with gr.Row():
        email_type = gr.Dropdown(
            label="Select Email Outreach Type",
            choices=list(FILE_MAPPING.keys()),
            value="Cold Email Outreach",
            interactive=True
        )
    
    with gr.Column(variant="panel"):
        gr.Markdown("### Additional Details")
        # Create additional fields – all initially hidden. They will be shown conditionally.
        recipient_name = gr.Textbox(label="Recipient Name", placeholder="Enter recipient's name", visible=False)
        recipient_company = gr.Textbox(label="Recipient Company", placeholder="Enter recipient's company", visible=False)
        industry = gr.Textbox(label="Industry", placeholder="Enter industry", visible=False)
        pain_points = gr.Textbox(label="Pain Points", placeholder="Enter known challenges or pain points", lines=2, visible=False)
        reference_details = gr.Textbox(label="Reference Details", placeholder="Mention any previous interactions", visible=False)
        customer_insights = gr.Textbox(label="Customer Insights / Questions", placeholder="What insights or questions do you have?", lines=2, visible=False)
        target_website_url = gr.Textbox(label="Target Website URL", placeholder="Enter the target website URL", visible=False)
        content_reference = gr.Textbox(label="Content Reference", placeholder="Mention relevant content or article details", lines=2, visible=False)
        influencer_platform = gr.Textbox(label="Influencer Platform", placeholder="Enter the influencer's platform (e.g., Instagram, YouTube)", visible=False)
        collaboration_idea = gr.Textbox(label="Collaboration Idea", placeholder="Briefly describe the collaboration idea", lines=2, visible=False)
        proposed_topics = gr.Textbox(label="Proposed Topics", placeholder="List one or more guest post topics", lines=2, visible=False)
        your_experience = gr.Textbox(label="Your Experience", placeholder="Share your expertise or experience", lines=2, visible=False)
        experience_details = gr.Textbox(label="Experience Details", placeholder="Describe your experience with the product/service", lines=2, visible=False)
    
    # When the outreach type changes, update the visibility of the additional fields.
    email_type.change(
        fn=update_additional_fields, 
        inputs=email_type, 
        outputs=[
            recipient_name, recipient_company, industry, pain_points,
            reference_details, customer_insights,
            target_website_url, content_reference,
            influencer_platform, collaboration_idea,
            proposed_topics, your_experience,
            experience_details
        ]
    )
    
    with gr.Row():
        generate_btn = gr.Button("Generate Email", variant="primary")
    
    # Use a gr.Code component to render Markdown and include a built-in copy-to-clipboard button.
    output_email = gr.Code(label="Generated Email (Markdown)", language="markdown")
    
    generate_btn.click(
        fn=generate_email,
        inputs=[
            email_type,
            recipient_name, recipient_company, industry, pain_points,
            reference_details, customer_insights,
            target_website_url, content_reference,
            influencer_platform, collaboration_idea,
            proposed_topics, your_experience,
            experience_details
        ],
        outputs=output_email,
    )
    
    gr.Markdown("___")
    gr.Markdown("© 2025 AI Email Crafting Tool")
```

### Step 9: Launch the App

Call `demo.launch()` to run the Gradio app. 

```py
# Launch the app (use share=True if you need to generate a public link)
demo.launch(share=True)
```

Test the app locally and ensure all components work as expected.

## Setup

In the project folder, create a file named `.env`.

Insert your AIML API key in the `.env` file:
```bash
AIML_API_KEY=your_api_key_here
```

## Usage

### Select Email Outreach Type
Open the app in your browser.

Use the dropdown menu to select one of the 7 email outreach types.

Options include:
- Cold Email Outreach
- Warm Email Outreach
- Customer Development Outreach
- Link-Building Outreach
- Influencer Outreach
- Guest Blogging Outreach
- Review and Rating Outreach

### Enter Additional Details

Based on the selected type, specific input fields will appear.

Fill in the details such as recipient name, company, pain points, etc.

If no extra fields are required, a simple input field is provided.

### Generate Email

Click the **Generate Email** button.

The tool loads the corresponding system instructions.

It combines your input with the system prompt.

The AI/ML API generates a personalized email.

### View and Copy Email

The generated email is displayed in Markdown format.

Use the built-in **copy to clipboard** button to copy the email.

Paste the email into your desired platform.

## Examples

### Cold Email Outreach

User Input:

```markdown
Recipient Name: Liang Wenfeng
Recipient Company: DeepSeekAI
Industry: AI
Pain Points: Hype around DeepSeekAI. X (twitter) posts.
```

![Cold Email Outreach](/images/cold_email.png)

Resulting Email:

```markdown
**Subject:** Unlocking New Opportunities for DeepSeekAI in the Competitive AI Landscape

---

Hi Liang,

I recently came across the exciting announcement of DeepSeekAI’s latest partnership with [Partner Company's Name], which garnered quite the buzz across the AI community. Congratulations on this milestone! It’s clear that DeepSeekAI is setting new benchmarks in the industry, and I’ve been following the impressive strides your team continues to make, particularly through your insightful posts on X (Twitter).

I understand that maintaining momentum amidst the hype can be challenging, especially as industry buzz can create both opportunities and pressure for innovation. At [Your Company Name], we help AI companies like DeepSeekAI transform industry excitement into sustainable growth. Our proprietary platform can streamline [specific process] and enhance [specific benefit], freeing up your team to focus on groundbreaking innovations.

Here's how we could assist:
- **Customized Solutions:** Tailored tools that address your ongoing challenges with scalability and integration.
- **Scalable Growth:** Proven strategies to convert the market buzz into long-term partnerships and user engagement.
- **Enhanced Efficiency:** Leveraging AI-powered analytics to optimize your workflow while maintaining data integrity.

I’d love to have a conversation to see how [Your Company Name] can support DeepSeekAI’s objectives. Would you be available for a 20-minute call next week to explore potential synergies?

Wishing you continued success,

[Your Full Name]  
[Your Title]  
[Your Company Name]  
[Your Contact Information]
```

![Cold Email Outreach](/images/cold_email_result.png)

### Guest Blogging Outreach

User Input:

```markdown
Proposed Topics: The Future of AI in Marketing: Trends to Watch in 2024
Your Experience: I am a digital marketing specialist with over 5 years of experience in content strategy and SEO. I have written for top industry blogs like HubSpot and Moz, and I specialize in creating data-driven content that drives engagement and conversions.
```

![Guest Blogging Outreach](/images/guest_blogging.png)

Resulting Email:

```markdown
Subject: Guest Blogging Collaboration with [Website Name] – Exploring AI Trends in Marketing

Hi [Recipient's Name],

I hope this message finds you well. My name is [Your Name], and I am a digital marketing specialist with over five years of experience in content strategy and SEO. I've had the pleasure of writing for industry-leading platforms such as HubSpot and Moz. I specialize in crafting data-driven content that not only engages readers but also drives significant conversions.

I recently read your insightful article on "[Specific Article Title]" published on [Website Name], and I was impressed by the depth of analysis and practical advice it provided. It resonated with my interest and expertise, particularly in the evolving role of AI in marketing.

I am writing to express my interest in contributing a guest post to [Website Name]. I believe that my proposed article, "The Future of AI in Marketing: Trends to Watch in 2024," would align well with your readership and add value to your existing content. Here are a few key points I’d like to cover:

- Analyzing the impact of AI-driven tools on consumer behavior patterns
- Forecasting AI trends that marketers should prepare for in 2024
- Case studies showcasing successful integration of AI in marketing strategies

I am confident this contribution will engage your audience by providing actionable insights and expert foresight into the future of marketing technology. 

If you're open to it, I would love to schedule a call or a follow-up discussion to further explore this idea and gather your thoughts. 

Thank you for considering my proposal. I look forward to the possibility of working together to create content that captivates your readers.

Warm regards,

[Your Full Name]  
[Your Title]  
[Your Contact Information]  
[LinkedIn Profile or Personal Website]
```

![Guest Blogging Outreach](/images/guest_blogging_result.png)

## Conclusion

In this tutorial, you learned how to build an AI Email Crafting Tool using Gradio.

The AI Email Crafting Tool is simple and efficient.

It streamlines the email outreach process.

Follow the steps to generate tailored emails effortlessly.

Enjoy a hassle-free, personalized email creation experience!

If you have any questions or need further assistance, feel free to reach out at abdibrokhim[at]gmail.com.

Follow me on [LinkedIn](https://www.linkedin.com/in/abdibrokhim/) for more updates and tutorials.

Join the Open Community on [Discord](https://discord.gg/nUdcd9p8Ae). Learn and grow with fellow developers and AI enthusiasts.