Tüm Ürünler
Search
Belge Merkezi

Direct Mail:Python 3.6 ve Sonraki Sürümler için SMTP Çağrı Örneği

Son Güncelleme:Oct 04, 2026

Direct Mail SMTP uç noktasını kullanarak Python 3.6 veya sonraki sürümlerden e-posta gönderin.

Ön Koşullar

Başlamadan önce aşağıdakilere sahip olduğunuzdan emin olun:

  • Direct Mail konsolunda oluşturulmuş bir gönderen adresi

  • Bu gönderen adresi için oluşturulmuş bir SMTP parolası

  • Yüklenmiş Python 3.6 veya sonraki bir sürüm

Uyarı: SMTP parolanızı source kodda sabit olarak kodlamayın. Kimlik bilgilerini ortam değişkenlerinde veya bir secrets manager içinde saklayın ve çalışma zamanında okuyun.

Nasıl Çalışır

Örnek, Python'un yerleşik smtplib ve email kütüphanelerini kullanarak şunları yapar:

  1. To, Cc, Bcc, Reply-To ve Return-Path başlıklarını içeren bir MIMEMultipart mesajı oluşturur.

  2. Bir HTML gövdesi ekler (düz metin ve dosya ekleri yorum satırı olarak bırakılan seçenekler arasındadır).

  3. 80 numaralı bağlantı noktasında (veya SSL için 465 numaralı bağlantı noktasında) smtpdm.aliyun.com adresine bağlanır ve gönderen adresi ile SMTP parolası kullanarak kimlik doğrulaması yapar.

  4. Tüm alıcılara tek bir çağrıda gönderim yapar ve SMTP hatalarını türlerine göre işler.

Örnek Kod

# -*- 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

# The sender address created in the Direct Mail console.
username = 'XXXXXXXX'
# The SMTP password for the sender address.
password = 'XXXXXXXX'
# The reply-to address. When a recipient replies, the email goes to this address
# instead of the sender address, which does not receive replies.
replyto = 'XXXXXXXX'
# The To recipient addresses (displayed in the email header).
rcptto = ['address1@example.net', 'address2@example.net']
# The Cc recipient addresses (displayed in the email header).
rcptcc = ['address3@example.net', 'address4@example.net']
# The Bcc recipient addresses (hidden from recipients but receive the email).
rcptbcc = ['address5@example.net', 'address6@example.net']
# All recipients. A single send cannot exceed 60 addresses.
receivers = rcptto + rcptcc + rcptbcc

# Build the message.
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('Custom email subject')
msg['From'] = formataddr(["Custom sender nickname", username])  # Nickname + sender address (or proxy sender)
msg['To'] = ",".join(rcptto)
msg['Cc'] = ",".join(rcptcc)
msg['Reply-to'] = replyto  # Address that receives replies. The recipient must support standard protocols.
msg['Return-Path'] = 'test@example.net'  # Address that receives bounces. The recipient must support standard protocols.
msg['Message-id'] = email.utils.make_msgid()  # Unique identifier per RFC 5322, e.g. <uniquestring@example.com>.
msg['Date'] = email.utils.formatdate()

# To enable email tracking, uncomment the following section.
# A tag is required and must be created in the console at least 10 minutes before use.
# tagName = 'xxxxxxx'
#
# trace = {
#     "OpenTrace": '1',  # Enable open tracking.
#     "LinkTrace": '1',  # Enable link-click tracking.
#     "TagName": tagName
# }
# jsonTrace = json.dumps(trace)
# base64Trace = str(base64.b64encode(jsonTrace.encode('utf-8')), 'utf-8')
# msg.add_header("X-AliDM-Trace", base64Trace)

# To add a plain-text fallback for mail clients that do not render HTML, uncomment the following.
# textplain = MIMEText('Custom plain text part', _subtype='plain', _charset='UTF-8')
# msg.attach(textplain)

# HTML body.
texthtml = MIMEText('Custom HTML hypertext part', _subtype='html', _charset='UTF-8')
msg.attach(texthtml)

# To attach a local file, uncomment the following.
# 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())
#     part_attach1.add_header('Content-Disposition', 'attachment', filename=filename)
#     msg.attach(part_attach1)

# To attach a file from a URL (e.g., an OSS object), uncomment the following.
# 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())
#     part_attach1.add_header('Content-Disposition', 'attachment', filename=filename)
#     msg.attach(part_attach1)

# Send the email.
try:
    # To use SSL, replace the line below with:
    # client = smtplib.SMTP_SSL('smtpdm.aliyun.com', 465)
    #
    # If the SSL handshake fails on Python 3.10 or 3.11, use a custom context:
    # ctxt = ssl.create_default_context()
    # ctxt.set_ciphers('DEFAULT')
    # client = smtplib.SMTP_SSL('smtpdm.aliyun.com', 465, context=ctxt)

    # Standard SMTP on port 80 (port 25 is also supported).
    client = smtplib.SMTP('smtpdm.aliyun.com', 80)
    client.set_debuglevel(0)  # Set to 1 to enable debug output.
    # The sender address and authentication address must match.
    client.login(username, password)
    client.sendmail(username, receivers, msg.as_string())
    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('Exception while sending email:', str(e))

Anahtar Parametreler


Parametre


Açıklama


username


Direct Mail konsolunda oluşturulan gönderen adresi. SMTP oturum açma işlemi ve sendmail FROM bağımsız değişkeni olarak kullanılır; bu üçü eşleşmelidir.


password


Gönderen adresi için SMTP parolası. Bu, Alibaba Cloud hesap parolanız değildir.


replyto


Yanıtları alan adres. Gönderen adresinden bağımsızdır; gönderen adresi kendisi yanıtları almaz.


rcptto / rcptcc / rcptbcc


To, Cc ve Bcc alıcı listeleri. Üç listedeki toplam adres sayısı, tek bir gönderimde 60 adresi aşamaz.


smtpdm.aliyun.com


Direct Mail SMTP uç noktası. Düz SMTP için 80 veya 25 numaralı bağlantı noktasını, SSL için 465 numaralı bağlantı noktasını kullanın.

İsteğe Bağlı Özellikler

Örnek, aşağıdaki özellikler için yorum satırı haline getirilmiş kodlar içerir. Bu özellikleri etkinleştirmek için ilgili bölümlerin yorumunu kaldırın.

  • Düz metin gövdesi: HTML gövdesinin yanına bir text/plain alternatif parçası ekleyin. HTML'i işleyemeyen e-posta istemcileri düz metin kısmına geri döner.

  • Yerel dosya eki: Diskten bir dosya okuyun ve MIMEApplication kullanarak ekleyin.

  • URL eki: Bir dosyayı bir URL'den (örneğin, bir OSS nesnesinden) alın ve önce diske kaydetmeden ekleyin.

  • SSL bağlantısı: 465 numaralı bağlantı noktasında smtplib.SMTP yerine smtplib.SMTP_SSL kullanın. Python 3.10 veya 3.11'de SSL el sıkışması başarısız olursa, ctxt.set_ciphers('DEFAULT') ile özel bir SSL bağlamı oluşturun.

  • E-posta izleme: Açılma izlemeyi ve bağlantı tıklama izlemeyi etkinleştirmek için Base64 ile kodlanmış bir JSON yükü içeren X-AliDM-Trace başlığını ayarlayın. Direct Mail konsolunda oluşturulmuş bir etiket gerektirir (oluşturulduktan 10 dakika sonra kullanılabilir).