在日常工作和学习中,我们经常需要发送邮件。Python提供了简单易用的邮件发送功能,可以自动发送文本邮件、html邮件,甚至包含附件的邮件。
在开始发送邮件之前,你需要准备:
发件人邮箱地址
邮箱密码或授权码
SMTP服务器地址和端口
常用的邮箱SMTP设置:
| 邮箱服务商 | SMTP服务器 | 端口 |
|---|---|---|
| QQ邮箱 | smtp.qq.com | 465或587 |
| 163邮箱 | smtp.163.com | 465或587 |
| Gmail | smtp.gmail.com | 587 |
注意:现在大多数邮箱都需要使用授权码而不是邮箱密码来发送邮件。
最基本的邮件就是纯文本格式。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_text_email():
# 邮箱配置
smtp_server = "smtp.qq.com" # QQ邮箱SMTP服务器
port = 465 # SSL端口
sender_email = "your_email@qq.com" # 发件人邮箱
password = "your_authorization_code" # 邮箱授权码
receiver_email = "receiver@example.com" # 收件人邮箱
# 创建邮件内容
subject = "Python邮件测试" # 邮件主题
body = """
这是一封来自Python的测试邮件。
恭喜!你已经成功使用Python发送了第一封邮件。
祝好,
Python程序
""" # 邮件正文
# 设置邮件信息
message = MIMEText(body, 'plain', 'utf-8') # 纯文本格式
message['From'] = Header("Python发件人", 'utf-8') # 发件人名称
message['To'] = Header("收件人", 'utf-8') # 收件人名称
message['Subject'] = Header(subject, 'utf-8') # 邮件主题
try:
# 创建SMTP连接
server = smtplib.SMTP_SSL(smtp_server, port)
# 登录邮箱
server.login(sender_email, password)
# 发送邮件
server.sendmail(sender_email, receiver_email, message.as_string())
# 关闭连接
server.quit()
print("邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {e}")
# 发送邮件
send_text_email()HTML邮件可以包含丰富的格式和样式。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_html_email():
# 邮箱配置
smtp_server = "smtp.qq.com"
port = 465
sender_email = "your_email@qq.com"
password = "your_authorization_code"
receiver_email = "receiver@example.com"
# HTML邮件内容
subject = "HTML格式测试邮件"
html_body = """
<html>
<head>
<style>
body { font-family: Arial, sans-serif; }
.header { background-color: #f0f0f0; padding: 20px; }
.content { padding: 20px; }
.footer { background-color: #f8f8f8; padding: 10px; text-align: center; }
</style>
</head>
<body>
<div>
<h1>欢迎使用Python发送邮件</h1>
</div>
<div>
<p>这是一封<strong>HTML格式</strong>的测试邮件。</p>
<p>你可以在这里添加各种HTML元素:</p>
<ul>
<li>列表项1</li>
<li>列表项2</li>
<li>列表项3</li>
</ul>
<p>访问我们的网站:<a href="https://www.fly63.com">fly63教程</a></p>
</div>
<div>
<p>© 2024 Python邮件系统</p>
</div>
</body>
</html>
"""
# 设置邮件信息
message = MIMEText(html_body, 'html', 'utf-8')
message['From'] = Header("Python邮件系统", 'utf-8')
message['To'] = Header(receiver_email, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
try:
server = smtplib.SMTP_SSL(smtp_server, port)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
server.quit()
print("HTML邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {e}")
# 发送HTML邮件
send_html_email()发送附件在工作和学习中非常实用。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.header import Header
import os
def send_email_with_attachment():
# 邮箱配置
smtp_server = "smtp.qq.com"
port = 465
sender_email = "your_email@qq.com"
password = "your_authorization_code"
receiver_email = "receiver@example.com"
# 创建多部分邮件
message = MIMEMultipart()
message['From'] = Header("文件发送系统", 'utf-8')
message['To'] = Header(receiver_email, 'utf-8')
message['Subject'] = Header("带附件的测试邮件", 'utf-8')
# 邮件正文
body = """
你好!
这封邮件包含附件,请查收。
附件说明:
1. 示例文档
2. 数据文件
如有问题请回复此邮件。
谢谢!
"""
message.attach(MIMEText(body, 'plain', 'utf-8'))
# 添加附件1 - 文本文件
try:
# 创建一个示例文件
with open('example.txt', 'w', encoding='utf-8') as f:
f.write("这是一个示例文本文件内容。\n")
f.write("使用Python自动生成。\n")
f.write("创建时间:2024年\n")
with open('example.txt', 'rb') as file:
attachment = MIMEApplication(file.read(), _subtype='txt')
attachment.add_header('Content-Disposition', 'attachment',
filename='示例文档.txt')
message.attach(attachment)
except Exception as e:
print(f"添加文本附件失败: {e}")
# 添加附件2 - PDF文件(如果有的话)
pdf_file = 'example.pdf'
if os.path.exists(pdf_file):
try:
with open(pdf_file, 'rb') as file:
attachment = MIMEApplication(file.read(), _subtype='pdf')
attachment.add_header('Content-Disposition', 'attachment',
filename='示例PDF.pdf')
message.attach(attachment)
except Exception as e:
print(f"添加PDF附件失败: {e}")
try:
server = smtplib.SMTP_SSL(smtp_server, port)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
server.quit()
print("带附件的邮件发送成功!")
# 清理临时文件
if os.path.exists('example.txt'):
os.remove('example.txt')
except Exception as e:
print(f"邮件发送失败: {e}")
# 发送带附件的邮件
send_email_with_attachment()在HTML邮件中嵌入图片可以让邮件更加生动。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
def send_email_with_images():
# 邮箱配置
smtp_server = "smtp.qq.com"
port = 465
sender_email = "your_email@qq.com"
password = "your_authorization_code"
receiver_email = "receiver@example.com"
# 创建邮件
message = MIMEMultipart('related')
message['From'] = Header("图片邮件测试", 'utf-8')
message['To'] = Header(receiver_email, 'utf-8')
message['Subject'] = Header("包含图片的HTML邮件", 'utf-8')
# 创建HTML正文
html_content = """
<html>
<body>
<h2>包含图片的HTML邮件</h2>
<p>这是一封包含嵌入式图片的邮件:</p>
<h3>产品介绍</h3>
<p>我们的产品具有以下特点:</p>
<img src="cid:image1" alt="产品图片1" width="300">
<h3>使用场景</h3>
<p>适用于各种工作环境:</p>
<img src="cid:image2" alt="使用场景" width="300">
<p>更多信息请访问我们的网站。</p>
</body>
</html>
"""
# 添加HTML正文
html_part = MIMEText(html_content, 'html', 'utf-8')
message.attach(html_part)
# 添加图片1
try:
# 这里需要替换为实际的图片文件路径
with open('image1.jpg', 'rb') as img_file:
img_data = img_file.read()
image1 = MIMEImage(img_data)
image1.add_header('Content-ID', '<image1>')
message.attach(image1)
except Exception as e:
print(f"添加图片1失败: {e}")
# 添加图片2
try:
with open('image2.jpg', 'rb') as img_file:
img_data = img_file.read()
image2 = MIMEImage(img_data)
image2.add_header('Content-ID', '<image2>')
message.attach(image2)
except Exception as e:
print(f"添加图片2失败: {e}")
try:
server = smtplib.SMTP_SSL(smtp_server, port)
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, message.as_string())
server.quit()
print("包含图片的邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {e}")
# 发送包含图片的邮件
# send_email_with_images()在工作中,我们经常需要给多个收件人发送相同的邮件。
import smtplib
from email.mime.text import MIMEText
from email.header import Header
def send_batch_emails():
# 邮箱配置
smtp_server = "smtp.qq.com"
port = 465
sender_email = "your_email@qq.com"
password = "your_authorization_code"
# 收件人列表
receivers = [
"user1@example.com",
"user2@example.com",
"user3@example.com",
"user4@example.com"
]
# 邮件主题和内容
subject = "会议通知"
body_template = """
尊敬的{name}:
您好!
我们将于本周五下午2点在公司会议室召开项目进度会议。
会议内容:
1. 项目进度汇报
2. 遇到的问题讨论
3. 下一步工作计划
请您准时参加,并准备好相关材料。
谢谢!
会议组织者
2024年1月
"""
# 收件人信息(姓名)
receiver_info = {
"user1@example.com": "张三",
"user2@example.com": "李四",
"user3@example.com": "王五",
"user4@example.com": "赵六"
}
success_count = 0
fail_count = 0
try:
server = smtplib.SMTP_SSL(smtp_server, port)
server.login(sender_email, password)
for receiver_email in receivers:
try:
# 个性化邮件内容
name = receiver_info.get(receiver_email, "同事")
personalized_body = body_template.format(name=name)
# 创建邮件
message = MIMEText(personalized_body, 'plain', 'utf-8')
message['From'] = Header("会议通知系统", 'utf-8')
message['To'] = Header(name, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
# 发送邮件
server.sendmail(sender_email, receiver_email, message.as_string())
print(f"发送成功: {receiver_email}")
success_count += 1
except Exception as e:
print(f"发送失败 {receiver_email}: {e}")
fail_count += 1
server.quit()
print(f"\n批量发送完成!")
print(f"成功: {success_count} 封")
print(f"失败: {fail_count} 封")
except Exception as e:
print(f"连接失败: {e}")
# 批量发送邮件
# send_batch_emails()为了方便重复使用,我们可以创建一个邮件发送类。
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
import os
class EmailSender:
def __init__(self, smtp_server, port, sender_email, password):
self.smtp_server = smtp_server
self.port = port
self.sender_email = sender_email
self.password = password
def send_text_email(self, receiver_email, subject, body, sender_name=None):
"""发送纯文本邮件"""
try:
message = MIMEText(body, 'plain', 'utf-8')
message['From'] = Header(sender_name or self.sender_email, 'utf-8')
message['To'] = Header(receiver_email, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
return self._send_email(receiver_email, message)
except Exception as e:
return False, str(e)
def send_html_email(self, receiver_email, subject, html_content, sender_name=None):
"""发送HTML邮件"""
try:
message = MIMEText(html_content, 'html', 'utf-8')
message['From'] = Header(sender_name or self.sender_email, 'utf-8')
message['To'] = Header(receiver_email, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
return self._send_email(receiver_email, message)
except Exception as e:
return False, str(e)
def send_email_with_attachments(self, receiver_email, subject, body, attachments, sender_name=None):
"""发送带附件的邮件"""
try:
message = MIMEMultipart()
message['From'] = Header(sender_name or self.sender_email, 'utf-8')
message['To'] = Header(receiver_email, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
# 添加正文
message.attach(MIMEText(body, 'plain', 'utf-8'))
# 添加附件
for attachment_path in attachments:
if os.path.exists(attachment_path):
with open(attachment_path, 'rb') as file:
filename = os.path.basename(attachment_path)
attachment = MIMEApplication(file.read(), _subtype='octet-stream')
attachment.add_header('Content-Disposition', 'attachment',
filename=filename)
message.attach(attachment)
return self._send_email(receiver_email, message)
except Exception as e:
return False, str(e)
def _send_email(self, receiver_email, message):
"""实际发送邮件"""
try:
server = smtplib.SMTP_SSL(self.smtp_server, self.port)
server.login(self.sender_email, self.password)
server.sendmail(self.sender_email, receiver_email, message.as_string())
server.quit()
return True, "发送成功"
except Exception as e:
return False, str(e)
# 使用示例
def main():
# 初始化邮件发送器
email_sender = EmailSender(
smtp_server="smtp.qq.com",
port=465,
sender_email="your_email@qq.com",
password="your_authorization_code"
)
# 发送文本邮件
success, message = email_sender.send_text_email(
receiver_email="receiver@example.com",
subject="测试邮件",
body="这是一封测试邮件内容。",
sender_name="Python邮件系统"
)
if success:
print("文本邮件发送成功")
else:
print(f"发送失败: {message}")
# 发送HTML邮件
html_content = """
<h1>HTML邮件测试</h1>
<p>这是一封<strong>HTML格式</strong>的邮件。</p>
"""
success, message = email_sender.send_html_email(
receiver_email="receiver@example.com",
subject="HTML测试邮件",
html_content=html_content
)
if success:
print("HTML邮件发送成功")
else:
print(f"发送失败: {message}")
if __name__ == "__main__":
main()以QQ邮箱为例:
登录QQ邮箱
点击"设置" → "账户"
找到"POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务"
开启"POP3/SMTP服务"
按照提示获取授权码
def safe_send_email(email_sender, receiver_email, subject, body):
"""安全的邮件发送函数,包含重试机制"""
max_retries = 3
for attempt in range(max_retries):
try:
success, message = email_sender.send_text_email(
receiver_email, subject, body
)
if success:
return True, "发送成功"
else:
print(f"第{attempt + 1}次尝试失败: {message}")
except Exception as e:
print(f"第{attempt + 1}次尝试异常: {e}")
return False, "所有尝试都失败了"主题要简洁明了
正文要分段,避免大段文字
重要的信息可以加粗或使用列表
包含明确的称呼和落款
掌握Python发送邮件的技能,可以让你在工作中自动化很多重复性的邮件发送任务,大大提高工作效率。
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!