Master Python Email Sending: 3 Methods with smtplib, zmail, yagmail
This guide explains three ways to send emails using Python—built‑in smtplib, the third‑party zmail library, and the lightweight yagmail package—covering setup, code examples for constructing messages with attachments, and best practices for reliable email delivery.
1. Introduction
Email is a formal communication method frequently used in daily office work. Python provides built‑in support for SMTP, allowing you to send plain‑text, rich‑text, or HTML emails.
2. Preparation
Using a 126.com mailbox as an example, you need to enable the SMTP service and generate an authorization code.
The account, authorization code, and server address are required to connect to the mail server.
3. Method One: smtplib
smtplib is a built‑in Python library that can be imported directly.
First, initialize an SMTP instance with the mailbox account, authorization code, and server address, then connect.
def __init__(self):
# 初始化
self.smtp = smtplib.SMTP()
# 连接邮箱服务器地址
self.smtp.connect('smtp.126.com')
# 加入主题和附件,邮件体
self.email_body = MIMEMultipart('mixed')
# 发件人地址及授权码
self.email_from_username = '**@126.com'
self.email_from_password = '授权码'
# 登录
self.smtp.login(self.email_from_username, self.email_from_password)Then add the recipient list, email subject, body content, attachment paths, and filenames to the email body.
def generate_email_body(self, email_to_list, email_title, email_content, attchment_path, files):
"""
组成邮件体
:param email_to_list: 收件人列表
:param email_title: 邮件标题
:param email_content: 邮件正文内容
:param attchment_path: 附件的路径
:param files: 附件文件名列表
:return:
"""
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)Finally, send the email using the SMTP instance.
# 收件人列表
email_to_list = ['收件人1地址', '收件人2地址']
# 发送邮件
# 注意:此处必须同时指定发件人与收件人,否则会当作垃圾邮件处理掉
self.smtp.sendmail(self.email_from_username, email_to_list, self.email_body.as_string())After sending, quit the service.
def exit(self):
"""
退出服务
:return:
"""
self.smtp.quit()4. Method Two: zmail
Zmail aims to simplify email handling. It automatically manages server address, port, and protocol, and makes creating MIME objects and headers easy.
Note: Zmail only supports Python 3, not Python 2.
Install the library: pip3 install zmail Create a mail service object with the account and authorization code:
class ZMailObject(object):
def __init__(self):
# 邮箱账号
self.username = '**@126.com'
# 邮箱授权码
self.authorization_code = '授权码'
# 构建一个邮箱服务对象
self.server = zmail.server(self.username, self.authorization_code)Compose the mail body as a dictionary:
# 邮件主体
mail_body = {
'subject': '测试报告',
'content_text': '这是一个测试报告', # 纯文本或者HTML内容
'attachments': ['./attachments/report.png'],
}Send the email:
# 收件人
mail_to = "收件人1"
# 发送邮件
self.server.send_mail(mail_to, mail_body)5. Method Three: yagmail
yagmail requires only a few lines of code to send emails and offers a more concise syntax than zmail.
Install the library: pip3 install yagmail Connect to the SMTP server using the account, authorization code, and server address:
import yagmail
yag_server = yagmail.SMTP(user='**@126.com', password='授权码', host='smtp.126.com')Prepare the email content and attachments, then send:
# 发送对象列表
email_to = ['**@qq.com']
email_title = '测试报告'
email_content = "这是测试报告的具体内容"
email_attachments = ['./attachments/report.png']
# 发送邮件
yag_server.send(email_to, email_title, email_content, email_attachments)Close the connection after sending.
yag_server.close()6. Conclusion
The article summarized three Python email‑sending methods; 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.
