Python邮件发送代码

功能描述

这段Python代码实现了通过SMTP协议发送邮件的功能,支持HTML和纯文本格式,包含错误处理和调试功能。

代码实现

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


def send_email(sender, auth_code, receiver, subject, content, is_html=False):
    """
    使用邮箱发送邮件(优化版)

    参数:
    - sender: 发件人邮箱地址
    - auth_code: 邮箱授权码(不是密码)
    - receiver: 收件人邮箱地址(可以是字符串或列表)
    - subject: 邮件主题
    - content: 邮件内容
    - is_html: 是否为HTML格式(默认False,纯文本)
    """

    # 邮箱SMTP服务器设置
    mail_host = "smtp.163.com"
    mail_port = 587  # SSL加密端口
    timeout = 10  # 设置超时时间(秒)

    try:
        # 1. 创建邮件对象
        message = MIMEMultipart()
        message['From'] = Header(sender, 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')

        # 处理收件人格式
        if isinstance(receiver, list):
            message['To'] = Header(",".join(receiver), 'utf-8')
        else:
            message['To'] = Header(receiver, 'utf-8')

        # 添加邮件正文
        if is_html:
            msg_content = MIMEText(content, 'html', 'utf-8')
        else:
            msg_content = MIMEText(content, 'plain', 'utf-8')
        message.attach(msg_content)

        print("正在连接邮箱服务器...")

        # 2. 连接SMTP服务器(增加超时设置)
        smtp_obj = smtplib.SMTP_SSL(mail_host, mail_port, timeout=timeout)
        smtp_obj.set_debuglevel(1)  # 开启调试模式(打印详细日志)

        print("正在登录邮箱...")
        smtp_obj.login(sender, auth_code)

        print("正在发送邮件...")
        smtp_obj.sendmail(sender, receiver, message.as_string())
        print("邮件发送成功!")

    except socket.timeout:
        print(f"连接超时({timeout}秒),请检查网络或防火墙设置")
    except smtplib.SMTPAuthenticationError:
        print("登录失败:邮箱或授权码错误")
    except smtplib.SMTPException as e:
        print(f"SMTP错误: {e}")
    except Exception as e:
        print(f"未知错误: {e}")
    finally:
        if 'smtp_obj' in locals():
            smtp_obj.quit()  # 确保关闭连接


# 使用示例
if __name__ == "__main__":
    # 替换为你的邮箱和授权码
    _sender = "13517255491@163.com"
    _auth_code = ""

    # 收件人邮箱(可以是单个或列表)
    receiver_email = "13517255491@163.com"

    # 邮件主题和内容
    email_subject = "Python发送邮件测试(优化版)"
    email_content = """
    这是一封优化后的Python测试邮件。

    如果发送成功,说明代码已修复!
    """

    # 发送邮件
    send_email(_sender, _auth_code, receiver_email, email_subject, email_content)

关键功能说明

注意事项

  1. 需要替换为有效的邮箱地址和授权码
  2. 163邮箱需要使用授权码而非密码
  3. 发送频率过高可能导致邮件被拦截
  4. 敏感信息(如授权码)应避免硬编码在代码中