SMTP email in Python
Send plain-text and HTML email with attachments from Python services.
Python services send email through SMTP connections defined in the Dashboard. The connection holds the server's address and credentials, and every service can use it by name.
Create a connection
To create a connection, go to Connections > Outgoing > E-mail > SMTP in the Dashboard, click Create a new SMTP connection and fill in the form:
- Name: My Connection
- Host: your SMTP server's address, e.g.
smtp.example.com - Username: the account the email is sent from
- Click OK
Send a plain-text email
To send a message, build an SMTPMessage and pass it to the connection's send method:
# -*- coding: utf-8 -*-
# Zato
from zato.common import SMTPMessage
from zato.server.service import Service
class MyService(Service):
def handle(self):
# Obtain a connection
conn = self.email.smtp.get('My Connection').conn
# Create a regular e-mail
msg = SMTPMessage()
msg.subject = 'Hello'
msg.to = 'hello@example.com'
msg.from_ = 'howdy@example.com'
msg.body = 'Hello, how are you?'
# Send the message
conn.send(msg)
Send an HTML email
Set is_html to True and the message body is sent as HTML:
# -*- coding: utf-8 -*-
# Zato
from zato.common import SMTPMessage
from zato.server.service import Service
class MyService(Service):
def handle(self):
# Obtain a connection
conn = self.email.smtp.get('My Connection').conn
# Create a regular e-mail
msg = SMTPMessage()
# The flag indicating it is HTML
msg.is_html = True
msg.subject = 'Hello'
msg.to = 'hello@example.com'
msg.from_ = 'howdy@example.com'
msg.body = '<b>Hello, how are you?</b>'
# Send the message
conn.send(msg)
Send an email with attachments
To add attachments, call .attach(name, payload) on the message. Attachments work with both plain-text and HTML email:
# -*- coding: utf-8 -*-
# Zato
from zato.common import SMTPMessage
from zato.server.service import Service
class MyService(Service):
def handle(self):
# Obtain a connection
conn = self.email.smtp.get('My Connection').conn
# Create a regular e-mail
msg = SMTPMessage()
msg.subject = 'Hello'
msg.to = 'hello@example.com'
msg.from_ = 'howdy@example.com'
msg.body = 'Hello, how are you?'
# Send attachments along
msg.attach('attachment_name1.txt', 'Attachment as string goes here')
msg.attach('attachment_name2.txt', 'Here is another one')
# Send the message
conn.send(msg)
See also
| Feature | What it does |
|---|---|
| IMAP | Receive and process email, including Microsoft 365 with OAuth2 |
| Scheduler | Send email on an interval or at a specific time |
| Config files | Keep addresses and templates outside code |