Python3入门指南Python语言的特点和实际应用Python3环境搭建配置VSCode进行Python开发Python基础语法Python变量与数据类型Python数据类型转换Python解释器使用Python注释使用Python运算符Python数字类型Python字符串操作Python列表操作Python元组使用Python字典使用Python集合使用Python条件控制详解Python循环语句详解Python编程入门实践Python推导式详解Python迭代器和生成器Python with语句详解Python函数详解Python lambda(匿名函数)Python装饰器Python数据结构Python模块和包使用Python中__name__和__main__的用法Python输入输出:从基础到文件操作Python文件操作Python OS模块使用Python错误和异常处理Python面向对象编程Python命名空间和作用域Python虚拟环境:venv详细教程Python类型注解Python标准库常用模块Python正则表达式Python CGI编程Python MySQL(mysql-connector驱动)Python MySQL(PyMySQL驱动)Python网络编程Python发送邮件Python多线程编程Python XML解析Python JSON解析Python日期和时间处理Python操作MongoDBPython urllib库使用Python uWSGI 安装与配置Python pip包管理工具Python operator模块Python math模块Python requests模块HTTP请求Python random模块Python OpenAI库Python AI绘画制作Python statistics模块Python hashlib模块:哈希加密Python量化交易Python pyecharts数据可视化Python Selenium网页自动化Python BeautifulSoup网页数据提取Python Scrapy爬虫框架Python Markdown转HTMLPython sys模块Python Pickle模块:数据存储Python subprocess模块Python queue队列模块Python StringIO内存文件操作Python logging日志记录Python datetime日期时间处理Python re正则表达式Python csv表格数据处理Python threading 多线程编程Python asyncio 异步编程Python PyQt 图形界面开发Python 应用方向和常用库框架

Python发送邮件

在日常工作和学习中,我们经常需要发送邮件。Python提供了简单易用的邮件发送功能,可以自动发送文本邮件、html邮件,甚至包含附件的邮件。


准备工作

在开始发送邮件之前,你需要准备:

  1. 发件人邮箱地址

  2. 邮箱密码或授权码

  3. SMTP服务器地址和端口

常用的邮箱SMTP设置:

邮箱服务商SMTP服务器端口
QQ邮箱smtp.qq.com465或587
163邮箱smtp.163.com465或587
Gmailsmtp.gmail.com587

注意:现在大多数邮箱都需要使用授权码而不是邮箱密码来发送邮件。


发送纯文本邮件

最基本的邮件就是纯文本格式。

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

def send_text_email():
    # 邮箱配置
    smtp_server = "smtp.qq.com"      # QQ邮箱SMTP服务器
    port = 465                       # SSL端口
    sender_email = "your_email@qq.com"  # 发件人邮箱
    password = "your_authorization_code"  # 邮箱授权码
    receiver_email = "receiver@example.com"  # 收件人邮箱
    
    # 创建邮件内容
    subject = "Python邮件测试"        # 邮件主题
    body = """
    这是一封来自Python的测试邮件。
    
    恭喜!你已经成功使用Python发送了第一封邮件。
    
    祝好,
    Python程序
    """                              # 邮件正文
    
    # 设置邮件信息
    message = MIMEText(body, 'plain', 'utf-8')  # 纯文本格式
    message['From'] = Header("Python发件人", 'utf-8')  # 发件人名称
    message['To'] = Header("收件人", 'utf-8')         # 收件人名称
    message['Subject'] = Header(subject, 'utf-8')     # 邮件主题
    
    try:
        # 创建SMTP连接
        server = smtplib.SMTP_SSL(smtp_server, port)
        # 登录邮箱
        server.login(sender_email, password)
        # 发送邮件
        server.sendmail(sender_email, receiver_email, message.as_string())
        # 关闭连接
        server.quit()
        print("邮件发送成功!")
        
    except Exception as e:
        print(f"邮件发送失败: {e}")

# 发送邮件
send_text_email()


发送HTML格式邮件

HTML邮件可以包含丰富的格式和样式。

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

def send_html_email():
    # 邮箱配置
    smtp_server = "smtp.qq.com"
    port = 465
    sender_email = "your_email@qq.com"
    password = "your_authorization_code"
    receiver_email = "receiver@example.com"
    
    # HTML邮件内容
    subject = "HTML格式测试邮件"
    html_body = """
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; }
            .header { background-color: #f0f0f0; padding: 20px; }
            .content { padding: 20px; }
            .footer { background-color: #f8f8f8; padding: 10px; text-align: center; }
        </style>
    </head>
    <body>
        <div>
            <h1>欢迎使用Python发送邮件</h1>
        </div>
        <div>
            <p>这是一封<strong>HTML格式</strong>的测试邮件。</p>
            <p>你可以在这里添加各种HTML元素:</p>
            <ul>
                <li>列表项1</li>
                <li>列表项2</li>
                <li>列表项3</li>
            </ul>
            <p>访问我们的网站:<a href="https://www.fly63.com">fly63教程</a></p>
        </div>
        <div>
            <p>© 2024 Python邮件系统</p>
        </div>
    </body>
    </html>
    """
    
    # 设置邮件信息
    message = MIMEText(html_body, 'html', 'utf-8')
    message['From'] = Header("Python邮件系统", 'utf-8')
    message['To'] = Header(receiver_email, 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')
    
    try:
        server = smtplib.SMTP_SSL(smtp_server, port)
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())
        server.quit()
        print("HTML邮件发送成功!")
        
    except Exception as e:
        print(f"邮件发送失败: {e}")

# 发送HTML邮件
send_html_email()


发送带附件的邮件

发送附件在工作和学习中非常实用。

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header
import os

def send_email_with_attachment():
    # 邮箱配置
    smtp_server = "smtp.qq.com"
    port = 465
    sender_email = "your_email@qq.com"
    password = "your_authorization_code"
    receiver_email = "receiver@example.com"
    
    # 创建多部分邮件
    message = MIMEMultipart()
    message['From'] = Header("文件发送系统", 'utf-8')
    message['To'] = Header(receiver_email, 'utf-8')
    message['Subject'] = Header("带附件的测试邮件", 'utf-8')
    
    # 邮件正文
    body = """
    你好!
    
    这封邮件包含附件,请查收。
    
    附件说明:
    1. 示例文档
    2. 数据文件
    
    如有问题请回复此邮件。
    
    谢谢!
    """
    message.attach(MIMEText(body, 'plain', 'utf-8'))
    
    # 添加附件1 - 文本文件
    try:
        # 创建一个示例文件
        with open('example.txt', 'w', encoding='utf-8') as f:
            f.write("这是一个示例文本文件内容。\n")
            f.write("使用Python自动生成。\n")
            f.write("创建时间:2024年\n")
        
        with open('example.txt', 'rb') as file:
            attachment = MIMEApplication(file.read(), _subtype='txt')
            attachment.add_header('Content-Disposition', 'attachment', 
                                filename='示例文档.txt')
            message.attach(attachment)
    except Exception as e:
        print(f"添加文本附件失败: {e}")
    
    # 添加附件2 - PDF文件(如果有的话)
    pdf_file = 'example.pdf'
    if os.path.exists(pdf_file):
        try:
            with open(pdf_file, 'rb') as file:
                attachment = MIMEApplication(file.read(), _subtype='pdf')
                attachment.add_header('Content-Disposition', 'attachment', 
                                    filename='示例PDF.pdf')
                message.attach(attachment)
        except Exception as e:
            print(f"添加PDF附件失败: {e}")
    
    try:
        server = smtplib.SMTP_SSL(smtp_server, port)
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())
        server.quit()
        print("带附件的邮件发送成功!")
        
        # 清理临时文件
        if os.path.exists('example.txt'):
            os.remove('example.txt')
            
    except Exception as e:
        print(f"邮件发送失败: {e}")

# 发送带附件的邮件
send_email_with_attachment()


发送包含图片的HTML邮件

在HTML邮件中嵌入图片可以让邮件更加生动。

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

def send_email_with_images():
    # 邮箱配置
    smtp_server = "smtp.qq.com"
    port = 465
    sender_email = "your_email@qq.com"
    password = "your_authorization_code"
    receiver_email = "receiver@example.com"
    
    # 创建邮件
    message = MIMEMultipart('related')
    message['From'] = Header("图片邮件测试", 'utf-8')
    message['To'] = Header(receiver_email, 'utf-8')
    message['Subject'] = Header("包含图片的HTML邮件", 'utf-8')
    
    # 创建HTML正文
    html_content = """
    <html>
    <body>
        <h2>包含图片的HTML邮件</h2>
        <p>这是一封包含嵌入式图片的邮件:</p>
        
        <h3>产品介绍</h3>
        <p>我们的产品具有以下特点:</p>
        <img src="cid:image1" alt="产品图片1" width="300">
        
        <h3>使用场景</h3>
        <p>适用于各种工作环境:</p>
        <img src="cid:image2" alt="使用场景" width="300">
        
        <p>更多信息请访问我们的网站。</p>
    </body>
    </html>
    """
    
    # 添加HTML正文
    html_part = MIMEText(html_content, 'html', 'utf-8')
    message.attach(html_part)
    
    # 添加图片1
    try:
        # 这里需要替换为实际的图片文件路径
        with open('image1.jpg', 'rb') as img_file:
            img_data = img_file.read()
        image1 = MIMEImage(img_data)
        image1.add_header('Content-ID', '<image1>')
        message.attach(image1)
    except Exception as e:
        print(f"添加图片1失败: {e}")
    
    # 添加图片2
    try:
        with open('image2.jpg', 'rb') as img_file:
            img_data = img_file.read()
        image2 = MIMEImage(img_data)
        image2.add_header('Content-ID', '<image2>')
        message.attach(image2)
    except Exception as e:
        print(f"添加图片2失败: {e}")
    
    try:
        server = smtplib.SMTP_SSL(smtp_server, port)
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())
        server.quit()
        print("包含图片的邮件发送成功!")
        
    except Exception as e:
        print(f"邮件发送失败: {e}")

# 发送包含图片的邮件
# send_email_with_images()


批量发送邮件

在工作中,我们经常需要给多个收件人发送相同的邮件。

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

def send_batch_emails():
    # 邮箱配置
    smtp_server = "smtp.qq.com"
    port = 465
    sender_email = "your_email@qq.com"
    password = "your_authorization_code"
    
    # 收件人列表
    receivers = [
        "user1@example.com",
        "user2@example.com", 
        "user3@example.com",
        "user4@example.com"
    ]
    
    # 邮件主题和内容
    subject = "会议通知"
    body_template = """
    尊敬的{name}:
    
    您好!
    
    我们将于本周五下午2点在公司会议室召开项目进度会议。
    
    会议内容:
    1. 项目进度汇报
    2. 遇到的问题讨论
    3. 下一步工作计划
    
    请您准时参加,并准备好相关材料。
    
    谢谢!
    
    会议组织者
    2024年1月
    """
    
    # 收件人信息(姓名)
    receiver_info = {
        "user1@example.com": "张三",
        "user2@example.com": "李四",
        "user3@example.com": "王五", 
        "user4@example.com": "赵六"
    }
    
    success_count = 0
    fail_count = 0
    
    try:
        server = smtplib.SMTP_SSL(smtp_server, port)
        server.login(sender_email, password)
        
        for receiver_email in receivers:
            try:
                # 个性化邮件内容
                name = receiver_info.get(receiver_email, "同事")
                personalized_body = body_template.format(name=name)
                
                # 创建邮件
                message = MIMEText(personalized_body, 'plain', 'utf-8')
                message['From'] = Header("会议通知系统", 'utf-8')
                message['To'] = Header(name, 'utf-8')
                message['Subject'] = Header(subject, 'utf-8')
                
                # 发送邮件
                server.sendmail(sender_email, receiver_email, message.as_string())
                print(f"发送成功: {receiver_email}")
                success_count += 1
                
            except Exception as e:
                print(f"发送失败 {receiver_email}: {e}")
                fail_count += 1
        
        server.quit()
        print(f"\n批量发送完成!")
        print(f"成功: {success_count} 封")
        print(f"失败: {fail_count} 封")
        
    except Exception as e:
        print(f"连接失败: {e}")

# 批量发送邮件
# send_batch_emails()


实用的邮件发送类

为了方便重复使用,我们可以创建一个邮件发送类。

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import os

class EmailSender:
    def __init__(self, smtp_server, port, sender_email, password):
        self.smtp_server = smtp_server
        self.port = port
        self.sender_email = sender_email
        self.password = password
    
    def send_text_email(self, receiver_email, subject, body, sender_name=None):
        """发送纯文本邮件"""
        try:
            message = MIMEText(body, 'plain', 'utf-8')
            message['From'] = Header(sender_name or self.sender_email, 'utf-8')
            message['To'] = Header(receiver_email, 'utf-8')
            message['Subject'] = Header(subject, 'utf-8')
            
            return self._send_email(receiver_email, message)
        except Exception as e:
            return False, str(e)
    
    def send_html_email(self, receiver_email, subject, html_content, sender_name=None):
        """发送HTML邮件"""
        try:
            message = MIMEText(html_content, 'html', 'utf-8')
            message['From'] = Header(sender_name or self.sender_email, 'utf-8')
            message['To'] = Header(receiver_email, 'utf-8')
            message['Subject'] = Header(subject, 'utf-8')
            
            return self._send_email(receiver_email, message)
        except Exception as e:
            return False, str(e)
    
    def send_email_with_attachments(self, receiver_email, subject, body, attachments, sender_name=None):
        """发送带附件的邮件"""
        try:
            message = MIMEMultipart()
            message['From'] = Header(sender_name or self.sender_email, 'utf-8')
            message['To'] = Header(receiver_email, 'utf-8')
            message['Subject'] = Header(subject, 'utf-8')
            
            # 添加正文
            message.attach(MIMEText(body, 'plain', 'utf-8'))
            
            # 添加附件
            for attachment_path in attachments:
                if os.path.exists(attachment_path):
                    with open(attachment_path, 'rb') as file:
                        filename = os.path.basename(attachment_path)
                        attachment = MIMEApplication(file.read(), _subtype='octet-stream')
                        attachment.add_header('Content-Disposition', 'attachment', 
                                            filename=filename)
                        message.attach(attachment)
            
            return self._send_email(receiver_email, message)
        except Exception as e:
            return False, str(e)
    
    def _send_email(self, receiver_email, message):
        """实际发送邮件"""
        try:
            server = smtplib.SMTP_SSL(self.smtp_server, self.port)
            server.login(self.sender_email, self.password)
            server.sendmail(self.sender_email, receiver_email, message.as_string())
            server.quit()
            return True, "发送成功"
        except Exception as e:
            return False, str(e)

# 使用示例
def main():
    # 初始化邮件发送器
    email_sender = EmailSender(
        smtp_server="smtp.qq.com",
        port=465,
        sender_email="your_email@qq.com",
        password="your_authorization_code"
    )
    
    # 发送文本邮件
    success, message = email_sender.send_text_email(
        receiver_email="receiver@example.com",
        subject="测试邮件",
        body="这是一封测试邮件内容。",
        sender_name="Python邮件系统"
    )
    
    if success:
        print("文本邮件发送成功")
    else:
        print(f"发送失败: {message}")
    
    # 发送HTML邮件
    html_content = """
    <h1>HTML邮件测试</h1>
    <p>这是一封<strong>HTML格式</strong>的邮件。</p>
    """
    
    success, message = email_sender.send_html_email(
        receiver_email="receiver@example.com",
        subject="HTML测试邮件", 
        html_content=html_content
    )
    
    if success:
        print("HTML邮件发送成功")
    else:
        print(f"发送失败: {message}")

if __name__ == "__main__":
    main()


常见问题解决

1. 获取邮箱授权码

以QQ邮箱为例:

  1. 登录QQ邮箱

  2. 点击"设置" → "账户"

  3. 找到"POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务"

  4. 开启"POP3/SMTP服务"

  5. 按照提示获取授权码

2. 处理发送失败

def safe_send_email(email_sender, receiver_email, subject, body):
    """安全的邮件发送函数,包含重试机制"""
    max_retries = 3
    for attempt in range(max_retries):
        try:
            success, message = email_sender.send_text_email(
                receiver_email, subject, body
            )
            if success:
                return True, "发送成功"
            else:
                print(f"第{attempt + 1}次尝试失败: {message}")
        except Exception as e:
            print(f"第{attempt + 1}次尝试异常: {e}")
    
    return False, "所有尝试都失败了"

3. 邮件内容格式建议

  • 主题要简洁明了

  • 正文要分段,避免大段文字

  • 重要的信息可以加粗或使用列表

  • 包含明确的称呼和落款

掌握Python发送邮件的技能,可以让你在工作中自动化很多重复性的邮件发送任务,大大提高工作效率。

本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!

链接: https://fly63.com/course/36_2114

目录选择