In the first two articles, we used Daoman Python AI to achieve one-click generation of Excel, Word, and PDF - but if the files lie on the server and no one collects them, it is equivalent to wasting work. Today, let’s get through the last mile of business automation: use Python to send emails and text messages, and completely weld the link “document output → message access”.


1. Send email: Use SMTP to directly talk to the mail server

You don't have to open a browser to send an email. Essentially, the program simulates an email client and uses SMTP (Simple Mail Transfer Protocol) to shake hands, encrypt, and deliver with the NetEase/QQ/enterprise mailbox server. Python built-insmtplibThese underlying details have been encapsulated for us.

1.1 Pre-security preparation: get the exclusive "authorization code"

Directly using the login password to log in to the mailbox in a third-party program is too risky. Now mainstream mailboxes (126, 163, QQ, Gmail, etc.) require the use of authorization code:

  1. Log in to the email web version
  2. Enter "Settings → Account → POP3/IMAP/SMTP/Exchange"
  3. Enable POP3/SMTP service
  4. Follow the prompts to bind your phone, verify the text message, and get a string of about 16-digit authorization codes (only displayed once, be sure to save them)

💡 The methods for obtaining authorization codes for corporate email are similar. Just contact IT or check internal documents.

1.2 The first email: Get started quickly with plain text emails

The content of the email is provided byemail.mimeIt is assembled from a series of modules. Use plain text email directlyMIMEText; If you want to add attachments, HTML text or images later, you need to use a "container"MIMEMultipart

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

def send_plain_email():
    # 1. 创建邮件容器(即使只发纯文本,也推荐用容器,方便后续扩展)
    msg = MIMEMultipart()
    msg['From'] = 'daoman_ai_demo@126.com'       # 你的发送邮箱
    msg['To'] = 'recipient@example.com'          # 接收邮箱,多个用逗号分隔
    msg['Subject'] = Header('Daoman Python AI 季度报表通知', 'utf-8')  # 避免中文主题乱码

    # 2. 添加纯文本正文
    plain_body = (
        "您好李总,\n\n"
        "您申请的三季度自动化销售报表已通过 Daoman Python AI 生成完成,"
        "如需添加附件或自定义 HTML 请随时沟通。\n\n"
        "此致\n敬礼\n道满科技技术部"
    )
    msg.attach(MIMEText(plain_body, 'plain', 'utf-8'))

    # 3. 连接 SMTP 服务器(推荐 SSL 加密端口 465,非加密 25 端口需提防被封)
    try:
        # 不同邮箱 SMTP 地址不同:126 邮箱为 smtp.126.com,QQ 邮箱为 smtp.qq.com
        smtp_server = smtplib.SMTP_SSL('smtp.126.com', 465)
        smtp_server.login('daoman_ai_demo@126.com', '你的专属授权码')
        smtp_server.sendmail(
            from_addr='daoman_ai_demo@126.com',
            to_addrs=['recipient@example.com'],   # 必须传列表!
            msg=msg.as_string()
        )
        print("✅ 纯文本邮件发送成功!")
    except Exception as e:
        print(f"❌ 发送失败:{str(e)}")
    finally:
        smtp_server.quit()

send_plain_email()

1.3 Upgraded version: Email with attachments + HTML formatting

Plain text is a bit dry, we can add HTML to improve the visual effect (tables, bold, company logo placeholder, etc.), and at the same time send the AI-generated Excel / PDF / Word as an attachment.

Core logic of attachment

Attachments are essentially binary files, and SMTP can only transmit text, so Base64 needs to be used to encode the binary into a character stream. At the same time, the Chinese file name may be garbled, so you need to useemail.headerMatching methods.

import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication  # 比纯 MIMEText 更适合处理附件

def send_fancy_email():
    msg = MIMEMultipart()
    msg['From'] = 'daoman_ai_demo@126.com'
    msg['To'] = 'recipient@example.com'
    msg['Subject'] = Header('【重要】三季度销售分析报告', 'utf-8')

    # 1. 添加 HTML 正文(也可以附带纯文本作为备选,防止收件端不支持 HTML)
    html_body = """
    <html>
      <body>
        <p>亲爱的李总,</p>
        <p>您申请的<strong>202X 年三季度华东区销售分析报告</strong>已由 Daoman Python AI 自动生成,包含以下文件:</p>
        <ul>
          <li>原始销售数据汇总.xlsx</li>
          <li>可视化图表分析报告.pdf</li>
          <li>精简版 Word 汇报.docx</li>
        </ul>
        <p>请查收附件,如有问题随时联系技术部!</p>
        <br>
        <p style="color: #888; font-size: 12px;">道满科技技术部 · 自动生成邮件</p>
      </body>
    </html>
    """
    msg.attach(MIMEText(html_body, 'html', 'utf-8'))

    # 2. 批量添加附件(用循环优雅处理)
    attachment_list = [
        {'path': 'resources/202XQ3_销售数据.xlsx', 'name': '202X年三季度华东区销售数据.xlsx'},
        {'path': 'resources/202XQ3_可视化分析.pdf', 'name': '202X年三季度华东区销售分析.pdf'}
    ]

    for att in attachment_list:
        with open(att['path'], 'rb') as f:
            part = MIMEApplication(f.read())
            # 处理中文文件名,兼容 Outlook / 网易 / QQ 邮箱
            part.add_header(
                'Content-Disposition',
                'attachment',
                filename=('utf-8', '', att['name'])
            )
            msg.attach(part)

    # 3. 连接发送(逻辑与纯文本邮件相同)
    try:
        smtp_server = smtplib.SMTP_SSL('smtp.126.com', 465)
        smtp_server.login('daoman_ai_demo@126.com', '你的专属授权码')
        smtp_server.sendmail(
            'daoman_ai_demo@126.com',
            ['recipient@example.com'],
            msg.as_string()
        )
        print("✅ 带附件 + HTML 邮件发送成功!")
    except Exception as e:
        print(f"❌ 发送失败:{str(e)}")
    finally:
        smtp_server.quit()

send_fancy_email()

2. Send SMS: Find a third-party gateway to act as a "middleman"

Unlike email, which has a unified SMTP protocol, SMS does not have a universal programming interface - we can't build our own base station. Therefore, you need to use compliant third-party SMS service providers (such as Alibaba Cloud, Tencent Cloud, Screwcap, etc.) to send SMS messages through the HTTP API provided by them.

2.1 Standard Compliance Process for SMS Sending

The state has very strict control over the SMS business. Sending marketing SMS messages without a signature/without permission is a violation**. The formal process must go through the following steps:

  1. Register service provider account - Recommend big companies such as Alibaba Cloud and Tencent Cloud, with good compliance and in-place technical support
  2. Real-name authentication—Both companies or individuals need to submit information
  3. Apply for SMS signature - for example【道满科技】, will appear at the beginning or end of the text message, and the service provider’s review standards are clear
  4. Apply SMS Template - for example您的验证码是${code},请于5分钟内输入。请勿泄露给他人!, the variable uses the placeholder specified by the service provider
  5. Get API Key/Secret - equivalent to the credentials for calling the interface

2.2 Practical code (taking Alibaba Cloud SMS service as an example)

APIs from major manufacturers usually provide official SDKs, but here we use the generalrequestsLibrary demo to facilitate migration to other service providers.

import requests
import json
from hashlib import sha256
import hmac
import base64
from datetime import datetime
import urllib.parse

def send_aliyun_sms(phone, code):
    """
    发送阿里云短信验证码。
    需提前开通短信服务、申请签名、审核通过模板。
    """
    # 1. 配置项(强烈建议用环境变量存储,不要硬编码!)
    access_key_id = "你的AccessKey ID"
    access_key_secret = "你的AccessKey Secret"
    sign_name = "道满科技"              # 已审核通过的签名
    template_code = "SMS_123456789"     # 已审核通过的模板
    template_param = json.dumps({"code": code})   # 模板变量转 JSON 字符串

    # 2. 阿里云 API 签名算法(可直接复用,官方文档有标准示例)
    def get_signature(params):
        sorted_params = sorted(params.items())
        canonicalized_query = urllib.parse.urlencode(sorted_params)
        string_to_sign = f"GET&%2F&{urllib.parse.quote_plus(canonicalized_query)}"
        key = f"{access_key_secret}&".encode('utf-8')
        message = string_to_sign.encode('utf-8')
        h = hmac.new(key, message, sha256)
        signature = base64.b64encode(h.digest()).decode('utf-8')
        return signature

    # 3. 构建公共请求参数
    common_params = {
        "SignatureMethod": "HMAC-SHA1",
        "SignatureNonce": str(int(datetime.now().timestamp() * 1000000)),
        "SignatureVersion": "1.0",
        "AccessKeyId": access_key_id,
        "Timestamp": datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),
        "Format": "JSON",
        "Action": "SendSms",
        "Version": "2017-05-25",
        "RegionId": "cn-hangzhou",
        "PhoneNumbers": phone,
        "SignName": sign_name,
        "TemplateCode": template_code,
        "TemplateParam": template_param
    }

    # 4. 生成签名并拼接 URL
    signature = get_signature(common_params)
    common_params['Signature'] = signature
    request_url = f"https://dysmsapi.aliyuncs.com/?{urllib.parse.urlencode(common_params)}"

    # 5. 发起请求
    try:
        resp = requests.get(request_url, timeout=10)
        result = resp.json()
        if result.get("Code") == "OK":
            print(f"✅ 短信下发成功!手机号:{phone}")
            return True
        else:
            print(f"❌ 短信下发失败:{result.get('Message')}")
            return False
    except Exception as e:
        print(f"❌ 网络请求失败:{str(e)}")
        return False

# 测试发送(请替换为真实手机号)
send_aliyun_sms("13800000000", "666888")

3. Pitfall avoidance guide and safety suggestions

  1. 🔐 Safety first Authorization codes and API Key/Secret should never be hard-coded in the code (especially do not upload to a public repository). Recommendedpython-dotenvRead environment variables, or use the cloud service provider's key management service (KMS).

  2. 📧 Tips for anti-spam email

  • Avoid sending identical emails in batches and add personalized content (such as a title at the beginning)
  • Try to use business email for sending, as free email is more likely to be marked as spam.
  • Attachments should be controlled within 10 MB. For large files, it is recommended to use cloud disk links instead.
  1. 📱 SMS Compliance Red Line
  • Personal real-name users can only send verification codes and notification text messages, and are not allowed to send marketing text messages.
  • Marketing text messages must carry the words "Unsubscribe back to T"
  • Be sure to configure IP whitelist and call frequency limit to prevent the interface from being stolen

After mastering the automatic sending of emails and text messages, combined with the automatic generation of documents in the previous two articles, you can already use Daoman Python AI to create a complete "weekly/monthly report automatic generation + automatic notification" system. Go and give it a try~