Master Python Email Sending: 3 Powerful Methods with Code Samples
Learn how to send emails using Python by exploring three approaches—smtplib, zmail, and yagmail—including setup, authentication, constructing MIME messages, attaching files, and sending, with complete code examples and step‑by‑step instructions for each method.
1. Introduction
Email is a formal communication method widely used in daily work, and Python provides built‑in support for SMTP, allowing sending of plain‑text, rich‑text, and HTML emails.
2. Preparation
Using a 126.com mailbox as an example, enable the SMTP service, create an authorization code, and note the account, authorization code, and server address needed for connection.
3. Method 1: smtplib
smtplib is a built‑in Python library that can be imported directly.
def __init__(self):
# Initialize
self.smtp = smtplib.SMTP()
# Connect to the mail server
self.smtp.connect('smtp.126.com')
# Create a mixed MIME container
self.email_body = MIMEMultipart('mixed')
# Sender address and authorization code
self.email_from_username = '**@126.com'
self.email_from_password = 'authorization_code'
# Login
self.smtp.login(self.email_from_username, self.email_from_password)After initializing, add recipients, subject, body, and attachments to the MIME container, then send the email and quit the service.
def generate_email_body(self, email_to_list, email_title, email_content, attchment_path, files):
"""Compose the email body"""
self.email_body['Subject'] = email_title
self.email_body['From'] = self.email_from_username
self.email_body['To'] = ",".join(email_to_list)
for file in files:
file_path = attchment_path + '/' + file
if os.path.isfile(file_path):
att = MIMEText(open(file_path, 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att.add_header("Content-Disposition", "attachment", filename=("gbk", "", file))
self.email_body.attach(att)
text_plain = MIMEText(email_content, 'plain', 'utf-8')
self.email_body.attach(text_plain) # Recipients list
email_to_list = ['[email protected]', '[email protected]']
# Send email
self.smtp.sendmail(self.email_from_username, email_to_list, self.email_body.as_string()) def exit(self):
"""Quit the service"""
self.smtp.quit()4. Method 2: zmail
zmail simplifies email handling; it automatically configures server address, port, and protocol.
pip3 install zmail class ZMailObject(object):
def __init__(self):
self.username = '**@126.com'
self.authorization_code = 'authorization_code'
self.server = zmail.server(self.username, self.authorization_code) mail_body = {
'subject': 'Test Report',
'content_text': 'This is a test report',
'attachments': ['./attachments/report.png'],
}
self.server.send_mail('recipient1', mail_body)5. Method 3: yagmail
yagmail offers a concise API for sending emails.
pip3 install yagmail import yagmail
yag_server = yagmail.SMTP(user='**@126.com', password='authorization_code', host='smtp.126.com') email_to = ['[email protected]']
email_title = 'Test Report'
email_content = "This is the content of the test report"
email_attachments = ['./attachments/report.png']
yag_server.send(email_to, email_title, email_content, email_attachments) yag_server.close()6. Conclusion
The article presented three ways to send emails with Python; in real projects the latter two methods (zmail and yagmail) are generally recommended.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
