#coding=utf-8 # smtplib负责发送邮件的动作,连接邮箱服务器、登录、发送 # email负责构造邮件,指的是邮箱页面显示,如发件人,收件人,主题,正文,附件等 import smtplib from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.header import Header from email.utils import formataddr # 设置smtplib所需的参数 from_addr = '发件人邮箱地址' receivers = ['收件人邮件地址'] qqAuthPassword = '发件人邮箱密码' smtp_server = '服务器地址' smtp_port = 587 attach_filename = 'test.py' attach_imagefile = u'1.png' def mail(): ret = True try: # 构造邮件对象MIMEMultipart对象 message = MIMEMultipart('mixed') message['From'] = from_addr message['To'] = ';'.join(receivers) message['Subject'] = u'subject' msgAlternative = MIMEMultipart('alternative') message.attach(msgAlternative) # 构造html mail_msg = ''' <p>邮件发送测试...</p> ''' ## <p><img src='cid:image1'></p> msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8')) # 构造图片链接 fp = open(attach_imagefile, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') message.attach(msgImage) # 构造附件 att1 = MIMEText(open(attach_filename, 'rb').read(), 'base64', 'utf-8') att1['Content-Type'] = 'application/octet-stream' att1['Content-Disposition'] = 'attachment;filename=' + attach_filename message.attach(att1) # 配置服务器 if smtp_port == 25: smtp = smtplib.SMTP() smtp.connect(smtp_server,smtp_port) elif smtp_port == 465: smtp = smtplib.SMTP_SSL(smtp_server, smtp_port) elif smtp_port == 587: smtp = smtplib.SMTP(smtp_server, smtp_port) smtp.connect(smtp_server,smtp_port) smtp.ehlo() smtp.starttls() smtp.login(from_addr, qqAuthPassword) smtp.sendmail(from_addr, receivers, message.as_string()) smtp.quit() except Exception as e: print('Error--' + str(e)) ret = False return ret ret = mail() if ret: print(u'邮件发送成功') else: print(u'邮件发送失败' )
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南