Slovak (Slovenčina) translation by Ryan (you can also view the original English article)
V tomto návode si predstavíme SMTP, modul v Pythone, ktorý sa používa pre odosielanie e-mailov. Taktiež si ukážeme ako odosielať rôzne typy e-mailov ako sú jednoduché textové e-maily, e-maily s prílohami alebo e-maily s obsahom v jazyku HTML.
Úvod do SMTP
Simple Mail Transfer Protocol (SMTP) má na starosti odosielanie a smerovanie e-mailov medzi servermi.
Modul smtplib
v Pythone definuje objekt relácie SMTP klienta, ktorý može byť použitý na odosielanie e-mailov akémukoľvek inému prístroju na Internete s SMTP alebo ESMTP serverom.
Takto si vytvoríme objekt SMTP klienta.
import smtplib server = smtplib.SMTP(host='host_address',port=your_port)
Vytvárame a odosielame jednoduchý e-mail
Nasledujúci skript vám umožní odosielať e-mail cez SMTP server Googlu. Bohužiaľ, Google vám nepovolí prihlásiť sa cez smtplib
, pretože prihlásenie označí za “menej zabezpečené.” Prihláste sa a navštívte https://myaccount.google.com/lesssecureapps, potom zapnite možnosť “Povoliť menej zabezpečené aplikácie” ako na obrázku nižšie.



Kód nižšie vykonáva tieto kroky:
- Vytvára objekt pre pripojenie na SMTP server.
- Prihlasuje sa na váš účet.
- Určuje hlavičky správy a prihlasovacie údaje.
- Vytvára objekt správy
MIMEMultipart
a prikladá súvisiace hlavičky do nej, napr. Od, Komu a Predmet. - Prikladá správu do objektu správy
MIMEMultipart
. - A nakoniec, odosiela správu.
Tento proces je tak jednoduchý, ako je zobrazený v kóde nižšie.
# import necessary packages from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib # create message object instance msg = MIMEMultipart() message = "Thank you" # setup the parameters of the message password = "your_password" msg['From'] = "your_address" msg['To'] = "to_address" msg['Subject'] = "Subscription" # add in the message body msg.attach(MIMEText(message, 'plain')) #create server server = smtplib.SMTP('smtp.gmail.com: 587') server.starttls() # Login Credentials for sending the mail server.login(msg['From'], password) # send the message via the server. server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print "successfully sent email to %s:" % (msg['To'])
Všimnite si, že adresy v hlavičkách ‘Od’ a ‘Komu’ musia byť zahrnuté v hlavičkách správy.
Vytváranie a odosielanie e-mailu s prílohou
V tomto príklade si ukážeme ako odoslať e-mail s prílohou obrázka. Tento kód je podobný kódu, ktorý bol použitý na odosielanie jednoduchého textového e-mailu.
- Vytvára objekt pre pripojenie na SMTP server.
- Prihlasuje sa na váš účet.
- Určuje hlavičky správy a prihlasovacie údaje.
- Vytvára objekt správy
MIMEMultipart
a prikladá súvisiace hlavičky do nej, napr. Od, Komu a Predmet. - Číta a prikladá obrázok do objektu správy
MIMEMultipart
. - A nakoniec, odosiela správu.
# send_attachment.py # import necessary packages from email.mime.multipart import MIMEMultipart from email.MIMEImage import MIMEImage from email.mime.text import MIMEText import smtplib # create message object instance msg = MIMEMultipart() # setup the parameters of the message password = "your_password" msg['From'] = "your_address" msg['To'] = "to_address" msg['Subject'] = "Photos" # attach image to message body msg.attach(MIMEImage(file("google.jpg").read())) # create server server = smtplib.SMTP('smtp.gmail.com: 587') server.starttls() # Login Credentials for sending the mail server.login(msg['From'], password) # send the message via the server. server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print "successfully sent email to %s:" % (msg['To'])
Trieda MIMEImage
je podtrieda triedy MIMENonMultipart
, ktorá sa používa na vytváranie objektov správy obrázkového typu. Iné dostupné triedy sú MIMEMessage
a MIMEAudio
.
Vytváranie a odosielanie e-mailov s HTML obsahom
Najprv si vyvoríme HTML šablónu na e-mail.
Vytváranie HTML šablóny
Tu je HTML kód šablóny, ktorý obsahuje dva stĺpce tabuľky, kde každá z nich má obrázok a ukážku obsahu. Ak máde radšej predpripravené, profesionálne riešenie, vyberte si z našich najlepších e-mailových šablón. Môžete si vybrať z množstva riešení, ktoré viete jednoducho nastaviť.
<html> <head> <title>Tutsplus Email Newsletter</title> <style type="text/css"> a {color: #d80a3e;} body, #header h1, #header h2, p {margin: 0; padding: 0;} #main {border: 1px solid #cfcece;} img {display: block;} #top-message p, #bottom p {color: #3f4042; font-size: 12px; font-family: Arial, Helvetica, sans-serif; } #header h1 {color: #ffffff !important; font-family: "Lucida Grande", sans-serif; font-size: 24px; margin-bottom: 0!important; padding-bottom: 0; } #header p {color: #ffffff !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; font-size: 12px; } h5 {margin: 0 0 0.8em 0;} h5 {font-size: 18px; color: #444444 !important; font-family: Arial, Helvetica, sans-serif; } p {font-size: 12px; color: #444444 !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; line-height: 1.5;} </style> </head> <body> <table width="100%" cellpadding="0" cellspacing="0" bgcolor="e4e4e4"><tr><td> <table id="top-message" cellpadding="20" cellspacing="0" width="600" align="center"> <tr> <td align="center"> <p><a href="#">View in Browser</a></p> </td> </tr> </table> <table id="main" width="600" align="center" cellpadding="0" cellspacing="15" bgcolor="ffffff"> <tr> <td> <table id="header" cellpadding="10" cellspacing="0" align="center" bgcolor="8fb3e9"> <tr> <td width="570" align="center" bgcolor="#d80a3e"><h1>Evanto Limited</h1></td> </tr> <tr> <td width="570" align="right" bgcolor="#d80a3e"><p>November 2017</p></td> </tr> </table> </td> </tr> <tr> <td> <table id="content-3" cellpadding="0" cellspacing="0" align="center"> <tr> <td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;"> <img src="https://thumbsplus.tutsplus.com/uploads/users/30/posts/29520/preview_image/pre.png" width="250" height="150" /> </td> <td width="15"></td> <td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;"> <img src="https://cms-assets.tutsplus.com/uploads/users/30/posts/29642/preview_image/vue-2.png" width ="250" height="150" /> </td> </tr> </table> </td> </tr> <tr> <td> <table id="content-4" cellpadding="0" cellspacing="0" align="center"> <tr> <td width="200" valign="top"> <h5>How to Get Up and Running With Vue</h5> <p>In the introductory post for this series we spoke a little about how web designers can benefit by using Vue. In this tutorial we’ll learn how to get Vue up..</p> </td> <td width="15"></td> <td width="200" valign="top"> <h5>Introducing Haiku: Design and Create Motion</h5> <p>With motion on the rise amongst web developers so too are the tools that help to streamline its creation. Haiku is a stand-alone..</p> </td> </tr> </table> </td> </tr> </table> <table id="bottom" cellpadding="20" cellspacing="0" width="600" align="center"> <tr> <td align="center"> <p>Design better experiences for web & mobile</p> <p><a href="#">Unsubscribe</a> | <a href="#">Tweet</a> | <a href="#">View in Browser</a></p> </td> </tr> </table><!-- top message --> </td></tr></table><!-- wrapper --> </body> </html>
Šablóna by mala vyzerať takto:



Nižšie sa nachádza skript pre odosielanie e-mailu s HTML obsahom. Obsahom bude naša šablóna pre e-maily.
import smtplib import email.message server = smtplib.SMTP('smtp.gmail.com:587') email_content = """ <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Tutsplus Email Newsletter</title> <style type="text/css"> a {color: #d80a3e;} body, #header h1, #header h2, p {margin: 0; padding: 0;} #main {border: 1px solid #cfcece;} img {display: block;} #top-message p, #bottom p {color: #3f4042; font-size: 12px; font-family: Arial, Helvetica, sans-serif; } #header h1 {color: #ffffff !important; font-family: "Lucida Grande", sans-serif; font-size: 24px; margin-bottom: 0!important; padding-bottom: 0; } #header p {color: #ffffff !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; font-size: 12px; } h5 {margin: 0 0 0.8em 0;} h5 {font-size: 18px; color: #444444 !important; font-family: Arial, Helvetica, sans-serif; } p {font-size: 12px; color: #444444 !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; line-height: 1.5;} </style> </head> <body> <table width="100%" cellpadding="0" cellspacing="0" bgcolor="e4e4e4"><tr><td> <table id="top-message" cellpadding="20" cellspacing="0" width="600" align="center"> <tr> <td align="center"> <p><a href="#">View in Browser</a></p> </td> </tr> </table> <table id="main" width="600" align="center" cellpadding="0" cellspacing="15" bgcolor="ffffff"> <tr> <td> <table id="header" cellpadding="10" cellspacing="0" align="center" bgcolor="8fb3e9"> <tr> <td width="570" align="center" bgcolor="#d80a3e"><h1>Evanto Limited</h1></td> </tr> <tr> <td width="570" align="right" bgcolor="#d80a3e"><p>November 2017</p></td> </tr> </table> </td> </tr> <tr> <td> <table id="content-3" cellpadding="0" cellspacing="0" align="center"> <tr> <td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;"> <img src="https://thumbsplus.tutsplus.com/uploads/users/30/posts/29520/preview_image/pre.png" width="250" height="150" /> </td> <td width="15"></td> <td width="250" valign="top" bgcolor="d0d0d0" style="padding:5px;"> <img src="https://cms-assets.tutsplus.com/uploads/users/30/posts/29642/preview_image/vue-2.png" width ="250" height="150" /> </td> </tr> </table> </td> </tr> <tr> <td> <table id="content-4" cellpadding="0" cellspacing="0" align="center"> <tr> <td width="200" valign="top"> <h5>How to Get Up and Running With Vue</h5> <p>In the introductory post for this series we spoke a little about how web designers can benefit by using Vue. In this tutorial we will learn how to get Vue up..</p> </td> <td width="15"></td> <td width="200" valign="top"> <h5>Introducing Haiku: Design and Create Motion</h5> <p>With motion on the rise amongst web developers so too are the tools that help to streamline its creation. Haiku is a stand-alone..</p> </td> </tr> </table> </td> </tr> </table> <table id="bottom" cellpadding="20" cellspacing="0" width="600" align="center"> <tr> <td align="center"> <p>Design better experiences for web & mobile</p> <p><a href="#">Unsubscribe</a> | <a href="#">Tweet</a> | <a href="#">View in Browser</a></p> </td> </tr> </table><!-- top message --> </td></tr></table><!-- wrapper --> </body> </html> """ msg = email.message.Message() msg['Subject'] = 'Tutsplus Newsletter' msg['From'] = 'youraddress' msg['To'] = 'to_address' password = "yourpassword" msg.add_header('Content-Type', 'text/html') msg.set_payload(email_content) s = smtplib.SMTP('smtp.gmail.com: 587') s.starttls() # Login Credentials for sending the mail s.login(msg['From'], password) s.sendmail(msg['From'], [msg['To']], msg.as_string())
Spustite tento kód, a keď sa nevyskytne žiadna chyba, váš e-mail bol odoslaný. Choďte na doručenú poštu a uvidíte váš e-mail s HTML obsahom.



Záver
Tento návod pokryl väčšinu toho, čo je potrebné pre odosielanie e-mailov z vašej aplikácie. Existujú rôzne API pre odosielanie e-mailov, napr. SendGrid, takže vy nemusíte začať od začiatku, ale je dôležité pochopiť základy. Pre viac informácii navštívte dokumentáciu Pythonu.
Taktiež sa nebojte pozrieť sa na to, čo je dostupné na predaj v obchode Envato Market. Keď máte nejaké otázky, opýtajte sa ich pomocou komentárov nižšie.