本文目录导读:

我来为您介绍Python发送邮件的几种常见方法,包括带附件的邮件。
使用smtplib发送基本邮件
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
class EmailSender:
def __init__(self, smtp_server, smtp_port, sender_email, sender_password):
"""
初始化邮件发送器
:param smtp_server: SMTP服务器地址
:param smtp_port: SMTP端口号
:param sender_email: 发件人邮箱
:param sender_password: 发件人密码或授权码
"""
self.smtp_server = smtp_server
self.smtp_port = smtp_port
self.sender_email = sender_email
self.sender_password = sender_password
def send_simple_email(self, receiver_email, subject, content):
"""
发送纯文本邮件
"""
message = MIMEText(content, 'plain', 'utf-8')
message['From'] = Header(self.sender_email)
message['To'] = Header(receiver_email)
message['Subject'] = Header(subject, 'utf-8')
self._send_email(receiver_email, message)
def send_html_email(self, receiver_email, subject, html_content):
"""
发送HTML格式邮件
"""
message = MIMEText(html_content, 'html', 'utf-8')
message['From'] = Header(self.sender_email)
message['To'] = Header(receiver_email)
message['Subject'] = Header(subject, 'utf-8')
self._send_email(receiver_email, message)
def send_email_with_attachment(self, receiver_email, subject, content, attachments):
"""
发送带附件的邮件
:param attachments: 附件文件路径列表,如 ['path/file1.pdf', 'path/file2.jpg']
"""
# 创建带附件的实例
message = MIMEMultipart()
message['From'] = Header(self.sender_email)
message['To'] = Header(receiver_email)
message['Subject'] = Header(subject, 'utf-8')
# 添加邮件正文
message.attach(MIMEText(content, 'plain', 'utf-8'))
# 添加附件
for file_path in attachments:
self._add_attachment(message, file_path)
self._send_email(receiver_email, message)
def _add_attachment(self, message, file_path):
"""
添加附件到邮件
"""
try:
with open(file_path, 'rb') as f:
# 获取文件名
file_name = file_path.split('/')[-1] if '/' in file_path else file_path
# 创建附件
attachment = MIMEApplication(f.read())
attachment.add_header(
'Content-Disposition',
'attachment',
filename=Header(file_name, 'utf-8').encode()
)
message.attach(attachment)
except Exception as e:
print(f"添加附件失败 {file_path}: {str(e)}")
def _send_email(self, receiver_email, message):
"""
发送邮件的内部方法
"""
try:
# 连接SMTP服务器
with smtplib.SMTP_SSL(self.smtp_server, self.smtp_port) as server:
server.login(self.sender_email, self.sender_password)
server.sendmail(self.sender_email, receiver_email, message.as_string())
print("邮件发送成功!")
except Exception as e:
print(f"邮件发送失败: {str(e)}")
使用示例
# 示例1:发送简单文本邮件
def example_simple_email():
sender = EmailSender(
smtp_server='smtp.qq.com', # QQ邮箱
smtp_port=465,
sender_email='your_email@qq.com',
sender_password='your_authorization_code' # 使用授权码
)
sender.send_simple_email(
receiver_email='receiver@example.com',
subject='测试邮件',
content='这是一封测试邮件'
)
# 示例2:发送带附件的邮件
def example_attachment_email():
sender = EmailSender(
smtp_server='smtp.163.com', # 163邮箱
smtp_port=465,
sender_email='your_email@163.com',
sender_password='your_authorization_code'
)
sender.send_email_with_attachment(
receiver_email='receiver@example.com',
subject='带附件的邮件',
content='请查收附件',
attachments=[
'path/to/file.pdf',
'path/to/image.jpg',
'path/to/document.docx'
]
)
# 示例3:发送HTML格式邮件
def example_html_email():
sender = EmailSender(
smtp_server='smtp.gmail.com', # Gmail
smtp_port=465,
sender_email='your_email@gmail.com',
sender_password='your_app_password' # Gmail需要应用密码
)
html_content = """
<html>
<body>
<h1>欢迎</h1>
<p>这是一封<b>HTML</b>格式的邮件</p>
</body>
</html>
"""
sender.send_html_email(
receiver_email='receiver@example.com',
subject='HTML格式邮件',
html_content=html_content
)
# 示例4:使用Zoho邮箱
def example_zoho_email():
sender = EmailSender(
smtp_server='smtp.zoho.com',
smtp_port=465,
sender_email='your_email@zoho.com',
sender_password='your_password'
)
sender.send_simple_email(
receiver_email='receiver@example.com',
subject='Zoho邮箱测试',
content='这是通过Zoho邮箱发送的测试邮件'
)
批量发送邮件
def send_batch_emails(sender, recipients, subject, content, attachments=None):
"""
批量发送邮件
:param recipients: 收件人列表
"""
for recipient in recipients:
try:
if attachments:
sender.send_email_with_attachment(
recipient, subject, content, attachments
)
else:
sender.send_simple_email(recipient, subject, content)
print(f"邮件发送成功: {recipient}")
except Exception as e:
print(f"邮件发送失败 {recipient}: {str(e)}")
# 使用示例
recipients = ['user1@example.com', 'user2@example.com', 'user3@example.com']
sender = EmailSender(
smtp_server='smtp.qq.com',
smtp_port=465,
sender_email='your_email@qq.com',
sender_password='your_authorization_code'
)
send_batch_emails(
sender,
recipients,
'批量发送测试',
'这是批量发送的测试内容',
attachments=['path/to/file.pdf']
)
常用邮箱SMTP配置
# 常见邮箱SMTP配置
EMAIL_CONFIGS = {
'QQ': {
'server': 'smtp.qq.com',
'port': 465,
'note': '需要开启SMTP并获取授权码'
},
'163': {
'server': 'smtp.163.com',
'port': 465,
'note': '需要开启SMTP并获取授权码'
},
'Gmail': {
'server': 'smtp.gmail.com',
'port': 465,
'note': '需要开启两步验证并使用应用密码'
},
'Outlook': {
'server': 'smtp-mail.outlook.com',
'port': 587,
'note': '使用587端口,TLS加密'
},
'Zoho': {
'server': 'smtp.zoho.com',
'port': 465,
'note': '企业邮箱或个人邮箱'
}
}
def get_email_config(email_type):
"""
获取邮箱配置
"""
return EMAIL_CONFIGS.get(email_type.upper())
注意事项
- 授权码:大多数邮箱(如QQ、163)需要获取授权码而不是使用密码登录
- 安全设置:确保邮箱开启了SMTP服务
- 附件大小:注意附件的总大小限制(一般不超过20MB)
- 发送频率:避免短时间内发送大量邮件,可能被标记为垃圾邮件
- 字符编码:使用UTF-8编码避免中文乱码
这个代码可以直接使用,只需替换为您的邮箱配置即可。