All Products
Search
Document Center

Direct Mail:SMTP - Python2

Last Updated:Dec 18, 2023

The following example shows how to send an email through SMTP using Python.

# -*- 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, created in the DirectMail console.
username = '***'

# The sender password, created in the DirectMail console.
password = '***'

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

# Recipient addresses or recipient address lists. at the same time, we limit the number of people allowed to send at a time, please refer to Limits.
#rcptto = ['***', '***']
rcptto = '***'

# Build the alternative structure
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('Custom mail subject'.decode('utf-8')).encode()
msg['From'] = '%s <%s>' % (Header('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() 

# Construct the alternative text/plain
textplain = MIMEText('Custom TEXT part plain TEXT', _subtype='plain', _charset='UTF-8')
msg.attach(textplain)

# Build the alternative text/HTML
texthtml = MIMEText('The custom HTML hypertext part', _subtype='html', _charset='UTF-8')
msg.attach(texthtml)

# Send mails
try:
    client = smtplib.SMTP()
    #Python version 2.7 or later, if you need to use SSL, can create the client
    #client = smtplib.SMTP_SSL()

    #The general port for SMTP is 25 or 80.
    client.connect('smtpdm-ap-southeast-1.aliyuncs.com', 25)

    #Open the DEBUG mode
    client.set_debuglevel(0)

    client.login(username, password)

    #The sender and the address must be consistent.
    #Note: if you want to get the DATA command return value, refer to sendmaili smtplib encapsulation methods:
    #      Using SMTP. Mail/SMTP. RCPT/SMTP data method
    client.sendmail(username, rcptto, msg.as_string())

    client.quit()
    print 'Mail sent successfully!'
except smtplib.SMTPConnectError, e:
    print 'Mail delivery fails, the connection fails:', e.smtp_code, e.smtp_error
except smtplib.SMTPAuthenticationError, e:
    print 'Mail delivery failure, certification error:', e.smtp_code, e.smtp_error
except smtplib.SMTPSenderRefused, e:
    print 'Send mail failed, the sender is rejected:', e.smtp_code, e.smtp_error
except smtplib.SMTPRecipientsRefused, e:
    print 'Send mail failed, the recipient was rejected:', e.smtp_code, e.smtp_error
except smtplib.SMTPDataError, e:
    print 'Send mail failed, data reception to refuse:', e.smtp_code, e.smtp_error
except smtplib.SMTPException, e:
    print 'Send mail failed, ', e.message
except Exception, e:
    print 'Send mail abnormal, ', str(e)