Python实现邮件发送:SMTP协议与Outlook COM接口详解

周叙
周叙
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍Python中两种常见的邮件发送实现方式。第一种是通过163邮箱的SMTP服务器直接调用,需先在邮箱后台开启服务并获取授权码;第二种是利用Windows系统的Outlook客户端,通过win32com库调用COM接口自动发送邮件。文章提供了完整的代码示例,涵盖邮件内容构造、附件添加及异常处理,适用于日常办公自动化场景。

在Python中实现邮件发送主要有两种路径:一是直接调用163邮箱的SMTP服务器,这要求用户先在163邮箱设置中开启SMTP服务并获取相应权限;二是通过Python直接调用Windows系统的Outlook客户端,利用win32com接口实现邮件的自动发送。

import win32com.client as win32 
import xlrd 
outlook = win32.Dispatch('outlook.application') 
mail = outlook.CreateItem(0) 
receivers = ['Yutao.A.Wang@alcatel-sbell.com.cn'] 
mail.To = receivers[0] 
mail.Subject ='test1' 
workbook = xlrd.open_workbook('E:\\kpi excel\\00_summary.xls') 
mySheet = workbook.sheet_by_index(0) 
 
nrows = mySheet.nrows 
content = [] 
for i in range(nrows): 
 ss = mySheet.row_values(i) 
 content.append(ss) 
 print(content) 
 Truecontent =str(content) 
 
mail.Body = Truecontent 
mail.Attachments.Add('E:\\kpi excel\\00_summary.xls') 
mail.Send() 

以下是使用SMTP协议发送邮件的具体实现步骤与代码示例。

import smtplib 
from email.mime.text import MIMEText 
mail_host = 'smtp.163.com' 
mail_user = '18298268658' 
mail_pass = 'cat123' 
sender = '18298268658@163.com' 
receivers = ['619538553@qq.com'] 
 
message = MIMEText('content','plain','utf-8') 
message['Subject'] = 'title' 
message['From'] = sender 
message['To'] = receivers[0] 
 
try: 
 smtpObj = smtplib.SMTP() 
 smtpObj.connect(mail_host,25) 
 smtpObj.login(mail_user,mail_pass) 
 smtpObj.sendmail( 
  sender,receivers,message.as_string()) 
 smtpObj.quit() 
 print('success') 
except smtplib.SMTPException as e: 
 print('error',e) 

以上即为本文介绍的全部内容,希望这些示例能对您的学习与实践有所帮助,也欢迎大家继续支持本站获取更多技术资源。

相关标签:

本站声明

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

Python 相关产品和应用

全部下载

专题列表