All Products
Search
Document Center

:SMTP Call Examples for Python3.6 and Above Version

Last Updated:Aug 09, 2023

This topic provides the SMTP Call Example and is applicable to Python3.6 and above version.

Alibaba Mail Configuration

SMTP server address: smtp.sg.aliyun.com

Port: non-encrypted is 25, SSL encrypted is 465

# -*- coding:utf-8 -*-
import smtplib
import email
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
# The email address of the sender.
from email.utils import formataddr

username = ''
# The email password of the sender.
password = ''
# Custom reply address
replyto = ''

From = formataddr(["custom sender nickname",'' ]) # nickname + sender address (or substitute sender)
to = ','.join(['', ''])

cc = ''
bcc = ''

# The recipient address or address list. Multiple recipients are supported.
rcptto = [to, cc, bcc]

# msg is the information that the email needs to display
msg = MIMEMultipart('alternative')
msg['Subject'] = Header('smtp sending test')
msg['from'] = From
msg['rcptto'] = ','.join(rcptto)
print ('Received list:', msg['rcptto'], type(msg['rcptto']))

msg['Reply-to'] = replyto
msg['Message-id'] = email.utils.make_msgid()
msg['Date'] = email.utils.formatdate()

# Build the alternative text/plain part
textplain = MIMEText ('This email is for test', _subtype='plain', _charset='UTF-8')
msg.attach(textplain)
# Build the alternative text/html part
texthtml = MIMEText ('This is a test email', _subtype='html', _charset='UTF-8)
msg.attach(texthtml)

try:
    client = smtplib.SMTP_SSL('smtp.sg.aliyun.com', 465)
    print ('Service and port connected')
except:
    print ('Service and port unservice')
    exit(1)

# Enable the DEBUG mode.
try:
    client.set_debuglevel(0)
    client.login(username, password)
    print ('Password verified')
except:
    print ('Password verification failed')
    exit(1)

client.sendmail(username, msg['rcptto'].split(','), msg.as_string())
client.quit()
print ('Email sent successfully! ')