侧边栏壁纸
博主头像
phphi

phphi's blog

  • 累计撰写 51 篇文章
  • 累计收到 0 条评论

Day29 - Python发送邮件和短信

2026-4-24 / 0 评论 / 2 阅读

发送邮件和短信

发送电子邮件

基本原理

  • SMTP:简单邮件传输协议,基于 TCP 的应用层协议
  • Python 标准库 smtplib + email 模块即可发送邮件

发送纯文本邮件

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

# 邮件服务器配置(以126邮箱为例)
SMTP_HOST = 'smtp.126.com'
SMTP_PORT = 465
USERNAME = 'your_email@126.com'
AUTH_CODE = 'your授权码'  # 不是登录密码,是SMTP授权码

# 构建邮件
msg = MIMEText('邮件正文内容', 'plain', 'utf-8')
msg['From'] = USERNAME
msg['To'] = 'recipient@example.com'
msg['Subject'] = Header('邮件主题', 'utf-8')

# 发送
with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) as server:
    server.login(USERNAME, AUTH_CODE)
    server.sendmail(USERNAME, 'recipient@example.com', msg.as_string())

发送 HTML 邮件

msg = MIMEText('<p>这是 <b>HTML</b> 邮件</p>', 'html', 'utf-8')

发送带附件的邮件

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from urllib.parse import quote

email = MIMEMultipart()
email['From'] = USERNAME
email['To'] = 'recipient@example.com'
email['Subject'] = Header('带附件的邮件', 'utf-8')

# 正文
email.attach(MIMEText('请查收附件', 'plain', 'utf-8'))

# 附件
with open('report.pdf', 'rb') as f:
    attachment = MIMEText(f.read(), 'base64', 'utf-8')
    attachment['content-type'] = 'application/octet-stream'
    filename = quote('报告.pdf')
    attachment['content-disposition'] = f'attachment; filename="{filename}"'
    email.attach(attachment)

封装发送函数

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from urllib.parse import quote

SMTP_HOST, SMTP_PORT = 'smtp.126.com', 465
USERNAME, AUTH_CODE = 'xxx@126.com', '授权码'

def send_email(from_, to_, subject='', content='', filenames=[]):
    email = MIMEMultipart()
    email['From'] = from_
    email['To'] = to_
    email['Subject'] = subject
    email.attach(MIMEText(content, 'plain', 'utf-8'))

    for filepath in filenames:
        with open(filepath, 'rb') as f:
            name = filepath.split('/')[-1]
            att = MIMEText(f.read(), 'base64', 'utf-8')
            att['content-type'] = 'application/octet-stream'
            att['content-disposition'] = f'attachment; filename="{quote(name)}"'
            email.attach(att)

    with smtplib.SMTP_SSL(SMTP_HOST, SMTP_PORT) as s:
        s.login(USERNAME, AUTH_CODE)
        s.sendmail(from_, to_.split(';'), email.as_string())

# 使用
send_email(
    from_='xxx@126.com',
    to_='yyy@qq.com',
    subject='报告',
    content='请查收',
    filenames=['report.pdf']
)

发送短信

短信需要第三方平台(如螺丝帽、阿里的云市场等),通过 HTTP API 调用。

import requests

def send_sms(phone, message):
    resp = requests.post(
        'http://sms-api.luosimao.com/v1/send.json',
        auth=('api', '平台分配的KEY'),
        data={'mobile': phone, 'message': message},
        verify=False
    )
    return resp.json()

# 使用(国内短信需加签名)
code = '123456'
send_sms('13500112233', f'您的验证码是{code},打死也不告诉别人!【签名】')

总结

  • 邮件:用 smtplib.SMTP_SSL 连接,MIMEText/MIMEMultipart 构建邮件
  • 附件:用 MIMEText 编码为 BASE64,设置 content-disposition
  • 短信:通过第三方 HTTP API 调用,需购买服务并配置签名
  • 授权码 ≠ 登录密码,需要在邮箱设置中单独开启 SMTP 并获取