Python使用smtplib模块发送普通及带附件邮件的完整指南

陆景行
陆景行
发布时间:2026-10-13 | 8人浏览过
原创

本文详细介绍Python中smtplib模块的使用方法,涵盖发送普通文本邮件及带附件邮件的具体代码实现。通过示例演示如何配置SMTP服务器、登录认证及构建邮件对象,并提供一个封装好的通用发送函数,支持自定义发件人、收件人、标题及内容,便于在自动化任务中直接调用。

Python发送普通邮件的基础实现

在程序开发过程中,经常需要执行自动化任务并在完成后自动发送结果报告。Python提供了标准的smtplib模块来处理邮件发送,无需额外安装,直接导入即可使用。以下是发送普通文本邮件的基础代码示例:

普通邮件发送代码解析


import smtplib    
from email.mime.text import MIMEText
email_host = 'smtp.163.com'   #邮箱地址
email_user = 'xxxx@163.com' # 发送者账号
email_pwd = 'xxxx'    # 发送者密码
maillist ='511402865@qq.com'
#收件人邮箱,多个账号的话,用逗号隔开
me = email_user
msg = MIMEText('邮件发送测试内容')  # 邮件内容
msg['Subject'] = '邮件测试主题'  # 邮件主题
msg['From'] = me  # 发送者账号
msg['To'] = maillist  # 接收者账号列表
smtp = smtplib.SMTP(email_host,port=25) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
smtp.login(email_user, email_pwd)  # 发送者的邮箱账号,密码
smtp.sendmail(me, maillist, msg.as_string())
# 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
smtp.quit() # 发送完毕后退出smtp
print ('email send success.')

发送带附件邮件的方法

接下来介绍如何发送包含附件的邮件,这需要结合MIMEMultipart模块来构建复杂的邮件结构。

带附件邮件代码解析


import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
username='xxx@xx.com'
email_host = 'smtp.163.com'
passwd='123456'
recv=['511402865@qq.com',]
title='邮件标题'
content='发送邮件测试'
msg = MIMEMultipart()
file='a.txt'
att = MIMEText(open(file,encoding='utf-8').read())
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="%s"'%file
msg.attach(att)
msg.attach(MIMEText(content))#邮件正文的内容
msg['Subject'] = title # 邮件主题
msg['From'] = username # 发送者账号
msg['To'] = recv # 接收者账号列表
#smtp = smtplib.SMTP_SSL(eail_host,port=456)#qq邮箱
smtp = smtplib.SMTP_SSL(eail_host,port=25)#其他邮箱
smtp.login(username,passwd)
smtp.sendmail(username,recv,msg.as_string())
smtp.quit()

封装通用邮件发送函数

为了提高代码复用性,可以将邮件发送逻辑封装为一个通用函数。调用该函数时,只需传入发件人账号、密码、收件人列表、邮件标题及正文内容即可。

封装函数代码示例


  import smtplib      
  from email.mime.text import MIMEText
  def send_mail(username,passwd,recv,title,content,mail_host='smtp.163.com',port=25):
    '''
    发送邮件函数,默认使用163smtp
    :param username: 邮箱账号 xx@163.com
    :param passwd: 邮箱密码
    :param recv: 邮箱接收人地址,多个账号以逗号隔开
    :param title: 邮件标题
    :param content: 邮件内容
    :param mail_host: 邮箱服务器
    :param port: 端口号
    :return:
    '''
    msg = MIMEText(content)  # 邮件内容
    msg['Subject'] = title  # 邮件主题
    msg['From'] = username  # 发送者账号
    msg['To'] = recv  # 接收者账号列表
    smtp = smtplib.SMTP(mail_host,port=port) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
    smtp.login(username, passwd)  # 发送者的邮箱账号,密码
    smtp.sendmail(username, recv, msg.as_string())
    # 参数分别是发送者,接收者,第三个是把上面的发送邮件的内容变成字符串
    smtp.quit() # 发送完毕后退出smtp
    print ('email send success.')
     
email_user = 'xxxx@163.com' # 发送者账号
email_pwd = 'xxxxx'    # 发送者密码
maillist ='511402865@qq.com'
title = '测试邮件标题'
content = '这里是邮件内容'
send_mail(email_user,email_pwd,maillist,title,content)

以上即为Python使用smtplib模块发送邮件的核心内容,希望能为您的开发工作提供参考。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表