Auto_mailing / app.py
sbgonenc96's picture
attachment added, Dockerfile added
6ea0c6b
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
)