Python ile mail gönderme maceraları

Kahramanımız geliştirdiği web sitesi üzerinden kullanıcılara mail gönderme olanağı sunmak istiyordu. Nasıl yapayım nasıl yapayım derken, python’a bir bakayım bu iş için neler var diyerekten araştırmaya koyuldu, buna araştırma da denmez aslında “araş” ta kalırsınız anca, o kadar kısa sürdü çünkü.
Onca şey yazdık hala tek satır kod yok, yakışmaz bize diyerekten kullandığım fonksiyonu veriyorum:
def send_mail(to, subject, text = "", html = "", filename = ""): import os import sys import smtplib # dosya uzantısından türünü belirlemek için mime type'ı import ediyoruz import mimetypes from optparse import OptionParser from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText COMMASPACE = ', ' try: # kapsayıcı bir mesaj oluşturuyoruz outer = MIMEMultipart() #örnek: mail@example.com sender = "kendi_mail_adresim" outer['Subject'] = subject #to değişkeninde array içerisinde göndereceğimiz kişilerin adreslerini tutuyoruz outer['To'] = COMMASPACE.join(to) #örnek: mail@example.com outer['From'] = "gonderici_kisminda_gorunecek_adres" if text: #text içeriği ekliyoruz textContent = MIMEText(text, 'plain') outer.attach(textContent) if html: #html içeriği ekliyoruz htmlContent = MIMEText(text, 'html') outer.attach(htmlContent) #attachment var demektir if filename: path = "attachments/" + filename #dosyanın türünü tahmin edip ona göre type belirliyoruz ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: """ dosya türünü belirleyemediysek veya dosya sıkıştırılmış bir dosya ise generic olarak octet-stream veriyoruz""" ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(path) msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(path, 'rb') msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(path, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(fp.read()) fp.close() """eğer yukarıdakilerden biri değilse mesajı base64 olarak encoded texte çevirip mesaja ekliyoruz""" encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) # oluşturduğumuz text, html ve file datasını string olarak alıyoruz composed = outer.as_string() #örnek: mail.example.com s = smtplib.SMTP("mail_server_adresi",25) #göndermek için kullandığımız mail hesabımızın login bilgileri s.login("username","password") s.sendmail(sender, to, composed) s.quit() return "success" except Exception, exc: return "failed"
Kod içerisinde gerekli yerlerde açılama yaptım, kullanımı çok basit.
text: mail içerisinde gönderilecek text metin.
html: mail içerisinde html göndermek için set edeceğimiz değişken (html kodu)
filename: mail’a attach edeceğimiz dosya varsa onun adını veriyoruz. Fonksiyon içerisinde
path olarak attachments/filename pathini kullandım ben, siz kendinize göre değiştiriniz.
Python’la bir maceramızın daha sonuna geldik, yenileriyle en kısa zamanda birlikte olmak ümidiyle
(evet 2 gün üst üste post girdim, çok heyecanlıyım)
Kalın sağlıcakla.