All Products
Search
Document Center

Direct Mail:SMTP - Python3.6

Last Updated:Mar 28, 2024

This topic describes how to use Python 3.6 or later to send emails over the SMTP protocol.

Sample code:

# -*- coding:utf-8 -*-
import smtplib
import email
# import json
# import base64
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
from email.utils import formataddr

# username, the sender address created in the console
username = 'XXXXXXXX'
# password, the SMTP password created through the console
password = 'XXXXXXXX'
# The custom return address, regardless of the settings in the console. Direct Mail the sender address does not receive the letter, the recipient will automatically jump to the specified reply address when replying to the letter. 
replyto = 'XXXXXXXX'
# The To receiving address displayed.
rcptto = ['address1@test.com', 'address2@test.com']
# The Cc receiving address displayed.
rcptcc = ['address3@test.com', 'address4@test.com']
# Bcc receiving address, the bout will not be displayed on the mail, but can receive the mail
rcptbcc = ['address5@test.com', 'address6@test.com']
# All receiving addresses, including CC addresses, we limit the number of people allowed to send at a time, please refer to Limits.
receivers = rcptto + rcptcc + rcptbcc

# Create an alternative structure.
msg = MIMEMultipart('alternative')
msg['Subject'] = Header ('Custom letter subject')
msg['From'] = formataddr(["Custom sender nickname", username]) # Nickname + sender address (or agent)
# Convert list to strings.
msg['To'] = ",".join(rcptto)
msg['Cc'] = ",".join(rcptcc)
msg['Reply-to'] = replyto
msg['Return-Path'] = 'test@example.net' #Used to receive return emails, the recipient needs to support standard protocols
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate()

# If you need to enable the mail tracking service, use the following code to set up the tracking link. 
# First, the domain name needs to be filed, and the CNAME configuration has been set and correctly resolved. Second, you need to tag the letter. This tag has been created and exists in the console, and the tag can be used after 10 minutes.
# Set the tracking link connector
# tagName = 'xxxxxxx'
#
# # The corresponding value of OpenTrace is string 1, which is fixed.
# trace = {
# "OpenTrace": '1', # Open email tracking
# "LinkTrace": '1', # Click the URL trace in the email.
#     "TagName": tagName  # tagname created in console
# }
# jsonTrace = json.dumps(trace)
# base64Trace = str(base64.b64encode(jsonTrace.encode('utf-8')), 'utf-8')
# # print(base64Trace)
# msg.add_header("X-AliDM-Trace", base64Trace)


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

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

# Attachments
# files = [r'C:\Users\Downloads\test1.jpg', r'C:\Users\Downloads\test2.jpg']
# for t in files:
# part_attach1=MIMEApplication (open(t, 'rb').read()) # Open the attachment
# part_attach1.add_header('Content-Disposition', 'attachment', filename=t.rsplit('\\', 1)[1]) # Name the attachment.
# msg.attach(part_attach1) # Add an attachment.

# Send the email.
try:
    # If you need to use SSL for encryption, you can create a client in this way.
    # client = smtplib.SMTP_SSL('smtpdm-ap-southeast-1.aliyuncs.com', 465)
    
    # If SSL handshake fails in the new python version 3.10/3.11 , please use the following method to handle it:
    # ctxt = ssl.create_default_context()
    # ctxt.set_ciphers('DEFAULT')
    # client = smtplib.SMTP_SSL('smtpdm-ap-southeast-1.aliyuncs.com', 465, context=ctxt)
    
    
    # The SMTP common port is 25 or 80.
    client = smtplib.SMTP('smtpdm-ap-southeast-1.aliyuncs.com', 80)
    # Enable the DEBUG mode.
    client.set_debuglevel(0)
    # The sender and authentication address must be the same.
    client.login(username, password)
    # Note: If you want to obtain the return value of the DATA command, refer to the sendmail encapsulation method of smtplib:
    # Use the SMTP.mail/SMTP.rcpt/SMTP.data method
    # print(receivers)
    client.sendmail(username, receivers, msg.as_string()) # Support multiple recipients, up to 60
    client.quit()
    print ('The email was sent successfully! ')
except smtplib.SMTPConnectError as e:
    print ('Email sending failed, connection failed:', e.smtp_code, e.smtp_error)
except smtplib.SMTPAuthenticationError as e:
    print ('Email sending failed, authentication error:', e.smtp_code, e.smtp_error)
except smtplib.SMTPSenderRefused as e:
    print ('Email delivery failed, sender rejected:', e.smtp_code, e.smtp_error)
except smtplib.SMTPRecipientsRefused as e:
    print ('Email delivery failed. Recipient rejected:', e.smtp_code, e.smtp_error)
except smtplib.SMTPDataError as e:
    print ('Email sending failed, data receiving rejected:', e.smtp_code, e.smtp_error)
except smtplib.SMTPException as e:
    print('Mail sending failed, ', str(e))
except Exception as e:
    print ('Email sending exception, ', str(e))