File size: 7,155 Bytes
2dcc3b2
 
 
2f2a434
 
2dcc3b2
6ea0c6b
 
 
 
2dcc3b2
6ea0c6b
 
2f2a434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ea0c6b
 
 
 
 
2f2a434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dcc3b2
 
 
2f2a434
 
2dcc3b2
 
2f2a434
 
 
 
 
2dcc3b2
 
2f2a434
 
 
 
 
 
 
 
 
 
 
2dcc3b2
 
2f2a434
 
 
 
 
92fe50b
 
2f2a434
 
 
 
 
 
2dcc3b2
6ea0c6b
 
 
 
 
 
 
2dcc3b2
2f2a434
 
 
 
2dcc3b2
2f2a434
 
 
6ea0c6b
2f2a434
2dcc3b2
2f2a434
 
 
 
 
 
 
 
 
 
 
 
 
 
f69f054
2f2a434
2dcc3b2
f69f054
 
 
 
 
 
 
 
 
 
 
 
 
2dcc3b2
2f2a434
6ea0c6b
 
 
 
 
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
import yagmail
import gradio as gr
import os
import time
import smtplib

# Get server configuration from environment variables with defaults
SERVER_NAME = os.getenv("GRADIO_SERVER_NAME", "0.0.0.0")
SERVER_PORT = int(os.getenv("GRADIO_SERVER_PORT", "7860"))
SHARE_APP = os.getenv("GRADIO_SHARE", "false").lower() == "true"


def execute(file_txt, user_mail, google_api_key, subject_text, content, attachments=None):
    # Validate inputs
    if not file_txt:
        raise gr.Error("Lütfen mail listesi dosyasını yükleyin")
    
    if not user_mail:
        raise gr.Error("Lütfen gönderen mail adresini girin")
    
    if not google_api_key:
        raise gr.Error("Lütfen Google API anahtarını girin")
    
    if not subject_text:
        raise gr.Error("Lütfen mail konusunu girin")
    
    if not content:
        raise gr.Error("Lütfen mail içeriğini girin")
    
    try:
        # Parse mail list
        mail_list = str(file_txt.decode("utf-8")).strip().split("\n")
        #print(mail_list)
        if mail_list[-1] == "":
            mail_list = mail_list[:-1]
        
        if not mail_list:
            raise gr.Error("Mail listesi boş")
        
        print(f"Mail listesi: {mail_list}")
        
        # Initialize yagmail with proper error handling
        try:
            yag = yagmail.SMTP(user_mail, google_api_key)
        except smtplib.SMTPAuthenticationError as e:
            error_msg = str(e)
            if "Username and Password not accepted" in error_msg:
                raise gr.Error(f"Gmail kimlik doğrulama hatası:\n\nKullanıcı adı veya şifre kabul edilmedi.\n\nLütfen şunları kontrol edin:\n1. Gmail adresinizin doğru olduğunu\n2. App Password kullandığınızı (normal şifre değil)\n3. 2-Factor Authentication'ın aktif olduğunu\n\nDetaylar: {error_msg}")
            else:
                raise gr.Error(f"SMTP kimlik doğrulama hatası:\n{error_msg}")
        except smtplib.SMTPException as e:
            raise gr.Error(f"SMTP bağlantı hatası:\n{str(e)}")
        except Exception as e:
            raise gr.Error(f"Mail servisi bağlantı hatası:\n{str(e)}")
        
        # Send emails
        successful_sends = 0
        failed_sends = []
        
        for i, mail in enumerate(mail_list):
            mail = mail.strip()
            if not mail:  # Skip empty lines
                continue
                
            try:
                # Handle attachments if any
                if attachments:
                    yag.send(mail, subject_text, content, attachments=attachments)
                else:
                    yag.send(mail, subject_text, content)
                successful_sends += 1
                print(f"Mail gönderildi: {mail}")
                time.sleep(0.2)  # Rate limiting
            except Exception as e:
                failed_sends.append(f"{mail}: {str(e)}")
                print(f"Mail gönderilemedi {mail}: {str(e)}")
        
        # Close connection
        try:
            yag.close()
        except:
            pass  # Ignore close errors
        
        # Prepare result message
        if failed_sends:
            error_details = "\n".join(failed_sends)
            if successful_sends > 0:
                raise gr.Warning(f"Kısmi başarı: {successful_sends} mail gönderildi, {len(failed_sends)} başarısız.\n\nBaşarısız mailler:\n{error_details}")
            else:
                raise gr.Error(f"Hiçbir mail gönderilemedi:\n{error_details}")
        else:
            return f"✅ Başarılı! {successful_sends} mail gönderildi."
            
    except gr.Error:
        # Re-raise Gradio errors
        raise
    except gr.Warning:
        # Re-raise Gradio warnings
        raise
    except Exception as e:
        # Catch any other unexpected errors
        raise gr.Error(f"Beklenmeyen hata:\n{str(e)}")


with gr.Blocks() as demo:
    gr.Markdown('# Auto Mailing Tool')
    gr.Markdown('Gmail üzerinden toplu mail gönderme aracı')

    with gr.Row():
        file_input = gr.File(
            label='Mail listesini yükle (her satırda bir mail adresi)', 
            type='binary',
            file_types=['.txt']
        )

    with gr.Row():
        user_mail = gr.Text(
            label='Gönderen Gmail adresi', 
            placeholder='ornek@gmail.com',
            value=None
        )
        google_api_key = gr.Text(
            label="Google App Password (16 haneli)", 
            placeholder='abcd efgh ijkl mnop',
            type='password',
            value=None
        )

    with gr.Row():
        subject_text = gr.Text(
            label='Mail konusu', 
            placeholder='Mail konunuzu buraya yazın',
            value=""
        )
    
    with gr.Row():
        content = gr.Textbox(
            label='Gönderilecek mail metni', 
            placeholder='Mail içeriğinizi buraya yazın...',
            value="", 
            lines=5
        )

    with gr.Row():
        attachments = gr.File(
            label='Eklenecek dosyalar (birden fazla seçebilirsiniz)',
            file_count='multiple',
            file_types=['.pdf', '.doc', '.docx', '.txt', '.jpg', '.jpeg', '.png', '.zip']
        )

    with gr.Row():
        create_button = gr.Button('📧 Mail Gönder', variant='primary')
        
    with gr.Row():
        output = gr.Textbox(label='Sonuç', interactive=False)

    # Connect the button click to the function
    create_button.click(
        fn=execute,
        inputs=[file_input, user_mail, google_api_key, subject_text, content, attachments],
        outputs=output
    )

    # Add helpful information
    gr.Markdown("""
    ### 📋 Kullanım Talimatları:
    1. **Gmail App Password alın**: Gmail hesabınızda 2-Factor Authentication aktif olmalı ve App Password oluşturmalısınız
    2. **Mail listesi**: Her satırda bir mail adresi olan .txt dosyası yükleyin
    3. **Gönderen adres**: Kendi Gmail adresinizi girin
    4. **App Password**: Normal şifrenizi değil, App Password'u girin
    5. **Konu ve içerik**: Mail konusu ve içeriğini doldurun
    
    ### ⚠️ Önemli Notlar:
    - Google App Password kullanmanız gerekiyor (normal şifre çalışmaz)
    - 2-Factor Authentication aktif olmalı
    - Günlük gönderim limitlerine dikkat edin
    - Daha fazla bilgi için https://support.google.com/accounts/answer/185833
    """)

    donation_html = """
    <div style="text-align: center; margin-top: 20px; padding: 10px; border-top: 1px solid #ddd;">
        <p style="font-weight: bold;">If you find this tool useful, consider supporting its development:</p>
        <div style="text-align: center; display: flex; justify-content: center;">
            <a href="https://ko-fi.com/sbgonenc" target="_blank">
                <img src="https://cdn.ko-fi.com/cdn/kofi2.png?v=3" height="36" width="auto" alt="Buy Me a Coffee on ko-fi.com" style="margin: 0 auto;" />
            </a>
        </div>
    </div>
    """

    gr.HTML(donation_html)


if __name__ == "__main__":
    demo.launch(
        server_name=SERVER_NAME,
        server_port=SERVER_PORT,
        share=SHARE_APP
    )