All Products
Search
Document Center

Direct Mail:SMTP call example for Python 2

Last Updated:Jun 02, 2026

This example shows how to send an email through Direct Mail using Python 2 and the SMTP protocol, with support for plain text, HTML, and multiple recipients.

Prerequisites

Before you begin, ensure that you have:

  • A sender address created in the Direct Mail console (used as the username value)

  • The SMTP password for that sender address (used as the password value), created in the Direct Mail console under the sender address settings

  • One or more recipient addresses

  • (Optional) A reply-to address

Send emails using SMTP

The following example builds a multipart email with both plain text and HTML body parts, then sends it through the Direct Mail SMTP server at smtpdm.aliyun.com. Replace all '***' placeholders with your actual values before running.

# -*- coding:utf-8 -*-
import smtplib
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email.mime.application import MIMEApplication
from email.header import Header

# The sender address. This address is created in the console.
username = '***'

# The sender password. This password is created in the console.
password = '***'

# The custom reply-to address.
replyto = '***'

# The recipient address or a list of recipient addresses. Multiple recipients are supported.
# For the specific number of recipients allowed, see the product specifications.
#receivers = ['address1@example.com', 'address2@example.com']
#rcptto = ','.join(rcptto)
rcptto = '***'

# Build the alternative structure.
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('Custom email subject'.decode('utf-8')).encode()
msg['From'] = '%s <%s>' % (Header('Custom sender nickname'.decode('utf-8')).encode(), username)
msg['To'] = rcptto
msg['Reply-to'] = replyto
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate() 

# Build the text/plain part of the alternative structure.
textplain = MIMEText('Custom plain text content', _subtype='plain', _charset='UTF-8')
msg.attach(textplain)

# Build the text/html part of the alternative structure.
texthtml = MIMEText('Custom HTML content', _subtype='html', _charset='UTF-8')
msg.attach(texthtml)

# Send the email.
try:
    client = smtplib.SMTP()
    # For Python 2.7 or later, create the client this way to use SSL.
    #client = smtplib.SMTP_SSL()

    # The standard SMTP port is 25 or 80.
    client.connect('smtpdm.aliyun.com', 25)

    # Enable DEBUG mode.
    client.set_debuglevel(0)

    client.login(username, password)

    # The sender address and the authentication address must be the same.
    # Note: To get the return value of the DATA command, use the 
    # SMTP.mail, SMTP.rcpt, and SMTP.data methods directly.
    client.sendmail(username, rcptto, msg.as_string())
    # To send to multiple recipients:
    #client.sendmail(username, receivers, msg.as_string())

    client.quit()
    print 'Email sent successfully!'
except smtplib.SMTPConnectError, e:
    print 'Failed to send the email. Connection error: ', e.smtp_code, e.smtp_error
except smtplib.SMTPAuthenticationError, e:
    print 'Failed to send the email. Authentication error: ', e.smtp_code, e.smtp_error
except smtplib.SMTPSenderRefused, e:
    print 'Failed to send the email. Sender refused: ', e.smtp_code, e.smtp_error
except smtplib.SMTPRecipientsRefused, e:
    print 'Failed to send the email. Recipient refused: ', e.smtp_code, e.smtp_error
except smtplib.SMTPDataError, e:
    print 'Failed to send the email. Data error: ', e.smtp_code, e.smtp_error
except smtplib.SMTPException, e:
    print 'Failed to send the email. ', e.message
except Exception, e:
    print 'An exception occurred while sending the email. ', str(e)

Parameters

Parameter

Description

username

Your sender address, created in the Direct Mail console. The sender address and the SMTP authentication address must be the same.

password

The SMTP password for the sender address, created in the Direct Mail console.

replyto

The reply-to address. Replies from recipients are delivered to this address.

rcptto

A single recipient address. To send to multiple recipients, use the receivers list and pass it to sendmail().

Connection options

The example uses an unencrypted connection on port 25. To use SSL, replace smtplib.SMTP() with smtplib.SMTP_SSL(). Refer to the Direct Mail documentation for the SSL port and any additional connection requirements.

For production use, use SSL. An unencrypted connection on port 25 works for development and debugging, but does not encrypt your credentials or message content in transit.

Error handling

Each exception block prints the SMTP response code and error message, which you can use to diagnose delivery failures:

Exception

Likely cause

SMTPConnectError

Cannot reach smtpdm.aliyun.com. Check your network or firewall rules.

SMTPAuthenticationError

Invalid username or password. Verify both in the Direct Mail console.

SMTPSenderRefused

The sender address was refused. Check the sender address configuration in the console.

SMTPRecipientsRefused

All recipient addresses were rejected. Check that rcptto is a valid address.

SMTPDataError

The server returned an error for the message data. Check the email body and headers.