This topic provides a code example for sending SMTP emails with Python 3.6 or later.
Alibaba Mail configuration
SMTP server address: smtp.mxhichina.com or smtp.qiye.aliyun.com
Port: 25 for non-encrypted connections, 465 for SSL-encrypted connections
# -*- 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
# import urllib.request
# import ssl
# username
username = 'XXXXXXXX'
# password. If you enabled a security password for third-party clients, use the security password generated on the web page. Otherwise, use your logon password.
password = 'XXXXXXXX'
# Custom reply-to address
replyto = 'XXXXXXXX'
# Displayed To recipient addresses
rcptto = ['address1@example.net', 'address2@example.net']
# Displayed Cc recipient addresses
rcptcc = ['address3@example.net', 'address4@example.net']
# Bcc recipient addresses. Bcc recipients are not displayed on the email but can receive it.
rcptbcc = ['address5@example.net', 'address6@example.net']
receivers = rcptto + rcptcc + rcptbcc
# Build the alternative structure
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('Custom email subject')
msg['From'] = formataddr(["Custom sender nickname", username]) # Nickname + sender address (or on-behalf-of address)
# Convert the list to a string
msg['To'] = ",".join(rcptto)
msg['Cc'] = ",".join(rcptcc)
msg['Reply-to'] = replyto # Used to receive reply emails. Requires the recipient to support standard protocols.
msg['Return-Path'] = 'test@example.net' # Used to receive bounce emails. Requires the recipient to support standard protocols.
msg['Message-id'] = email.utils.make_msgid() # The message-id uniquely identifies each email. Its format must comply with RFC 5322, typically like <uniquestring@example.com>. The uniquestring is a unique identifier generated by the mail server, which may include information such as a timestamp and a random number.
msg['Date'] = email.utils.formatdate()
# Build the text/plain part of the alternative structure
# textplain = MIMEText('Custom plain text part', _subtype='plain', _charset='UTF-8')
# msg.attach(textplain)
# Build the text/html part of the alternative structure
texthtml = MIMEText('Custom HTML hypertext part', _subtype='html', _charset='UTF-8')
msg.attach(texthtml)
# # Send a local attachment
# files = [r'C:\Users\Downloads\test1.jpg', r'C:\Users\Downloads\test2.jpg']
# for t in files:
# filename = t.rsplit('/', 1)[1]
# part_attach1 = MIMEApplication(open(t, 'rb').read()) # Open the attachment
# part_attach1.add_header('Content-Disposition', 'attachment', filename=filename) # Name the attachment
# msg.attach(part_attach1) # Add the attachment
# # Send an attachment from a URL
# files = [r'https://example.oss-cn-shanghai.aliyuncs.com/xxxxxxxxxxx.png']
# for t in files:
# filename=t.rsplit('/', 1)[1]
# response = urllib.request.urlopen(t)
# part_attach1 = MIMEApplication(response.read()) # Open the attachment (not a local file)
# part_attach1.add_header('Content-Disposition', 'attachment', filename=filename) # Name the attachment
# msg.attach(part_attach1) # Add the attachment
# Send the email
try:
# To use SSL encryption, create the client as follows
# client = smtplib.SMTP_SSL('smtp.qiye.aliyun.com', 465)
# For Python 3.10/3.11, if an SSL handshake fails, handle it as follows:
# ctxt = ssl.create_default_context()
# ctxt.set_ciphers('DEFAULT')
# client = smtplib.SMTP_SSL('smtp.qiye.aliyun.com', 465, context=ctxt)
# The standard SMTP port is 25
client = smtplib.SMTP('smtp.qiye.aliyun.com', 25, timeout=10)
# Enable DEBUG mode
# client.set_debuglevel(0)
# The sender address and authentication address must be the same
client.login(username, password)
# Note: To get the return value of the DATA command, see the sendmail encapsulation method in smtplib:
# Use the SMTP.mail/SMTP.rcpt/SMTP.data methods
# print(receivers)
client.sendmail(username, receivers, msg.as_string()) # Multiple recipients are supported. For the specific limit, see the specification checklist.
client.quit()
print('Email sent successfully!')
except smtplib.SMTPConnectError as e:
print('Failed to send email. Connection failed:', e.smtp_code, e.smtp_error)
except smtplib.SMTPAuthenticationError as e:
print('Failed to send email. Authentication error:', e.smtp_code, e.smtp_error)
except smtplib.SMTPSenderRefused as e:
print('Failed to send email. Sender refused:', e.smtp_code, e.smtp_error)
except smtplib.SMTPRecipientsRefused as e:
print('Failed to send email. Recipients refused:', e.smtp_code, e.smtp_error)
except smtplib.SMTPDataError as e:
print('Failed to send email. Data reception refused:', e.smtp_code, e.smtp_error)
except smtplib.SMTPException as e:
print('Failed to send email, ', str(e))
except Exception as e:
print('Email sending exception, ', str(e))该文章对您有帮助吗?