python发送邮件

本文详细介绍了如何使用Python编写脚本来实现邮件自动化发送与管理,包括文本邮件、HTML邮件和带附件邮件的发送,以及如何在邮件中插入图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


# -*- coding:UTF-8 -*-
'''
Created on 2010-5-27

@author: 忧里修斯
'''
import smtplib
import email
import os
import traceback
from email.message import Message
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.base import MIMEBase
from email import encoders
import mimetypes
from email.mime.audio import MIMEAudio

'''
邮件收发管理
'''

#发送服务器信息
smtpserver='smtp.qq.com'
smtpuser='***@qq.com'
smtppass='***'
smtpport='25'

def login():
'''
发件人登录到服务器
'''
server=smtplib.SMTP(smtpserver,smtpport)
server.ehlo()
server.login(smtpuser,smtppass)
return server

def sendTextEmail(toAdd,subject,content):
'''
功能:发送纯文本邮件
参数说明:
toAdd:收件人E-mail地址 类型:list
subject:主题,类型:string
content:邮件内容 类型:string
fromAdd:发件人,默认为服务器用户
返回值:True/False
'''
result = False
server = login()
msg = Message()
msg['Mime-Version']='1.0'
msg['From'] = smtpuser
msg['To'] = toAdd
msg['Subject'] = subject
msg['Date'] = email.Utils.formatdate() # curr datetime, rfc2822
msg.set_payload(content)
try:
server.sendmail(smtpuser,toAdd,str(msg)) # may also raise exc
result = True
except Exception ,ex:
print Exception,ex
print 'Error - send failed'

return result


def sendEmail(toAdd,subject,html):
'''
发送html邮件
'''
result = False
try:
msgRoot = MIMEMultipart('ralated')
msgRoot['Subject'] = subject
msgRoot['From'] = smtpuser
msgRoot['To'] = toAdd
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
#设定HTML信息
msgText = MIMEText(html, 'html', 'utf-8')
msgAlternative.attach(msgText)
#设定内置图片信息
fp = open('test.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
#发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(smtpuser, smtppass)
smtp.sendmail(smtpuser, toAdd, msgRoot.as_string())
smtp.quit()
result = True
except:
result = False

return result

def sendMultiMail(toAdd,subject,html):
'''
发送带附件的邮件
'''
result = False
try:
msgRoot = MIMEMultipart('ralated')
msgRoot['Subject'] = subject
msgRoot['From'] = smtpuser
msgRoot['To'] = toAdd
msgRoot.preamble = 'This is a multi-part message in MIME format.'
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
#设定HTML信息
msgText = MIMEText(html, 'html', 'utf-8')
msgAlternative.attach(msgText)
#设定内置图片信息
fp = open(u'c:\\capmm.jpg', 'rb+')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

#构造附件
filepath = u'C:\\constant.py'
ctype, encoding = mimetypes.guess_type(filepath)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
if maintype == 'text':
fp = open(filepath)
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'image':
fp = open(filepath, 'rb')
msg = MIMEImage(fp.read(), _subtype=subtype)
fp.close()
elif maintype == 'audio':
fp = open(filepath, 'rb')
msg = MIMEAudio(fp.read(), _subtype=subtype)
fp.close()
else:
fp = open(filepath, 'rb')
msg = MIMEBase(maintype, subtype)
msg.set_payload(fp.read())
fp.close()
encoders.encode_base64(msg)
msg.replace_header('Content-type','Application/octet-stream;name=%s' % filepath)
msg.add_header('Content-Disposition', 'attachment',filename = filepath)
msgRoot.attach(msg)

#发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
print smtp.login(smtpuser, smtppass)
smtp.sendmail(smtpuser, toAdd, msgRoot.as_string())
smtp.quit()
result = True
except:
print traceback.format_exc()
result = False
return result

if __name__ == '__main__':

# print sendTextEmail('...@qq.com', '爱动注册通知', '本邮件有爱动系统自动发出,请勿回复,谢谢')
# print sendEmail('...@qq.com', 'html爱动注册通知', '<font color=red><b>本邮件有爱动系统自动发出,请勿回复,谢谢</b><img src="cid:image1"></font>')
print sendMultiMail('769435570@qq.com', 'html爱动注册通知', '<font color=red><b>本邮件有爱动系统自动发出,请勿回复,谢谢</b></font><img src="cid:image1">')



说明:如何在邮件中显示图片
1、为上传的图片设置名称
msgImage.add_header('Content-ID', '<image1>')
2、使用名称显示
<font color=red><b>本邮件有爱动系统自动发出,请勿回复,谢谢</b><img src="cid:image1"></font>
Python发送电子邮件可以通过 `smtplib` 库完成,它是标准库的一部分,因此不需要额外安装。下面是一个简单的介绍以及示例代码展示如何用 Python 发送带附件、HTML 内容等不同类型的邮件。 ### 使用 smtplib 和 email 模块发送基础文本邮件 1. **导入必要的模块** - `smtplib`: 用于SMTP协议通信。 - `email.mime.text.MIMEText`, `email.mime.multipart.MIMEMultipart`: 构造复杂的MIME消息体。 2. **设置服务器信息** 设置你的 SMTP 服务器地址及端口号,默认情况下 Gmail 的 SMTP 地址是 `"smtp.gmail.com"` 并且 SSL/TLS 加密连接默认使用465/587端口。 3. **构造邮件内容** 创建 MIME 格式的邮件对象,并设定主题、发件人、收件人等基本信息。 4. **登录邮箱账户并发送邮件** #### 基础文本邮件发送实例 ```python import smtplib from email.mime.text import MIMEText from email.header import Header # 定义变量 sender = "your_email@example.com" # 发件人的邮箱账号 receiver = ["recv_email1@example.com"] # 收件人的邮箱账号(支持多个) subject = "测试邮件标题" body = "这是一个来自Python脚本的基础文本邮件" msg = MIMEText(body, 'plain', 'utf-8') # 文本正文 msg['Subject'] = Header(subject, 'utf-8') # 主题 msg['From'] = sender # 显示的发件人名称 msg['To'] = ",".join(receiver) # 显示的收件人名单 try: server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465) # 使用SSL加密的方式链接到QQ企业邮服务器 login_result = server.login(sender, "your_password") # 登录验证 print(f"Login status code:{login_result}") if int(login_result) == 235: # 如果返回的状态码等于235表示认证成功 send_status = server.sendmail(sender, receiver, msg.as_string()) print(send_status) if not send_status: print('邮件已成功发出') else: print('邮件发送失败:', send_status) except Exception as e: print(f'发生错误:{e}') finally: server.quit() # 关闭连接 ``` 请注意,出于安全考虑,在生产环境中应避免直接将密码写入源代码文件中。推荐做法是从环境变量读取或者利用第三方服务如 OAuth 授权等方式替代传统用户名+密码组合来进行身份校验。 --- 接下来是一些高级功能的应用场景说明: * **带有 HTML 格式的内容**: 将第二步中的 `MIMEText()` 函数第二个参数改为 `'html'` 即可构建HTML格式的消息体; * **附加普通文件**: 使用 `email.mime.base.MIMEBase` 类结合 `encoders.encode_base64()` 方法编码二进制数据加入到 MIMEMultipart 对象里作为附件; * **同时包含文字和平面媒体资源(例如图片)** : 把所有非文本部分当作独立部件挂载至根容器之下形成复合型MIME文档结构。 如果需要进一步了解上述任意一种情况的具体实现,请告诉我!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值