Easy Tutorial
❮ Python Os Makedev Python Dictionary ❯

Python3 SMTP Email Sending

SMTP (Simple Mail Transfer Protocol) is a protocol for transmitting email from a source address to a destination address, controlling the way emails are relayed.

Python's smtplib provides a convenient way to send emails, encapsulating the SMTP protocol.

The syntax for creating an SMTP object in Python is as follows:

import smtplib

smtpObj = smtplib.SMTP([host[, port[, local_hostname]]])

Parameter descriptions:

The Python SMTP object uses the sendmail method to send emails, with the following syntax:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

Parameter descriptions:

Note that the third parameter, msg, is a string representing the email. Emails typically consist of a subject, sender, recipient, content, attachments, etc. When sending an email, ensure the format of msg complies with the SMTP protocol.

Example

Below is a simple example of sending an email using Python:

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = '[email protected]'
receivers = ['[email protected]']  # Recipient email, can be set to your QQ email or other email

# Three parameters: the first is the text content, the second 'plain' sets the text format, the third 'utf-8' sets the encoding
message = MIMEText('Python email sending test...', 'plain', 'utf-8')
message['From'] = Header("tutorialpro.org", 'utf-8')  # Sender
message['To'] = Header("Test", 'utf-8')  # Recipient

subject = 'Python SMTP Email Test'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("Email sent successfully")
except smtplib.SMTPException:
    print("Error: Unable to send email")

We use triple quotes to set the email message. A standard email requires three header fields: From, To, and Subject, each separated by a blank line.

We connect to the SMTP server by instantiating the smtplib module's SMTP object smtpObj and use the sendmail method to send the message.

Running the above program, if sendmail is installed on your local machine, the output will be:

$ python3 test.py
Email sent successfully

Check your inbox (usually in the junk folder) to see the email message.

If your local machine does not have sendmail access, you can also use SMTP services from other providers (QQ, NetEase, Google, etc.).

Example

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# Third-party SMTP service
mail_host = "smtp.XXX.com"  # Set the server
mail_user = "XXXX"  # Username
mail_pass = "XXXXXX"  # Password

sender = '[email protected]'
receivers = ['[email protected]']  # Recipient email, can be set to your QQ email or other email

message = MIMEText('Python email sending test...', 'plain', 'utf-8')
message['From'] = Header("tutorialpro.org", 'utf-8')  # Sender
message['To'] = Header("Test", 'utf-8')  # Recipient

subject = 'Python SMTP Email Test'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # Connect to the server, default port is 25
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("Email sent successfully")
except smtplib.SMTPException:
    print("Error: Unable to send email")
message = MIMEText('Python email sending test...', 'plain', 'utf-8')
message['From'] = Header("tutorialpro.org", 'utf-8')
message['To'] = Header("test", 'utf-8')

subject = 'Python SMTP Email Test'
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj = smtplib.SMTP() 
    smtpObj.connect(mail_host, 25)    # 25 is the SMTP port number
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("Email sent successfully")
except smtplib.SMTPException:
    print("Error: Unable to send email")
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# The filename here can be anything you want; it will display as the name of the attachment in the email
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)

# Construct attachment 2, sending the 'tutorialpro.txt' file in the current directory
att2 = MIMEText(open('tutorialpro.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="tutorialpro.txt"'
message.attach(att2)

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print("Email sent successfully")
except smtplib.SMTPException:
    print("Error: Unable to send email")
$ python3 test.py 
Email sent successfully

Check our inbox (usually in the spam folder) to see the email details:


Adding Images in HTML Text

External links are typically invalid in HTML text for most email services. The correct way to add images is shown in the following example:

Example

#!/usr/bin/python3

import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

sender = '[email protected]'
receivers = ['[email protected]']  # Recipients can be set to your QQ email or any other email

msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("tutorialpro.org", 'utf-8')
msgRoot['To'] = Header("Test", 'utf-8')
subject = 'Python SMTP Email Test'
msgRoot['Subject'] = Header(subject, 'utf-8')

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

mail_msg = """
<p>Python email sending test...</p>
<p><a href="http://www.tutorialpro.org">tutorialpro.org link</a></p>
<p>Image demonstration:</p>
<p><img decoding="async" src="cid:image1"></p>
"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))

# Specify the image in the current directory
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()

# Define the image ID, referenced in the HTML text
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, msgRoot.as_string())
    print("Email sent successfully")
except smtplib.SMTPException:
    print("Error: Unable to send email")
$ python3 test.py 
Email sent successfully

Check our inbox (if it's in the spam folder, you may need to move it to the inbox for proper display) to see the email details:

## Sending Email Using a Third-Party SMTP Service

Here, the SMTP service of QQ Mail (you can also use 163, Gmail, etc.) is used, and the following configuration is required:

QQ Mail sets up a password by generating an authorization code:

QQ Mail SMTP server address: smtp.qq.com, SSL port: 465.

You need to modify the following examples: sender's email (your QQ email), password, recipient's email (can be sent to yourself).

## QQ SMTP

!/usr/bin/python3

import smtplib from email.mime.text import MIMEText from email.utils import formataddr

my_sender = '[email protected]' # Sender's email account my_pass = 'xxxxxxxxxx' # Sender's email password my_user = '[email protected]' # Recipient's email account, sent to myself

def mail(): ret = True try: msg = MIMEText('Fill in the email content', 'plain', 'utf-8') msg['From'] = formataddr(["Fromtutorialpro", my_sender]) # Corresponds to the sender's email nickname, sender's email account msg['To'] = formataddr(["FK", my_user]) # Corresponds to the recipient's email nickname, recipient's email account msg['Subject'] = "Email Test from tutorialpro.org" # Email subject or title

    server = smtplib.SMTP_SSL("smtp.qq.com", 465)  # SMTP server in the sender's email, port 25
    server.login(my_sender, my_pass)  # Corresponds to the sender's email account, email password
    server.sendmail(my_sender, [my_user,], msg.as_string())  # Corresponds to the sender's email account, recipient's email account, email sent
    server.quit()  # Close the connection
except Exception:  # If the statements in try are not executed, ret=False will be executed below
    ret = False
return ret

ret = mail() if ret: print("Email sent successfully") else: print("Email sending failed")


$ python test.py Email sent successfully ```

After successful sending, log in to the recipient's email to view:

For more content, please refer to: https://docs.python.org/3/library/email-examples.html.

❮ Python Os Makedev Python Dictionary ❯