本文目录导读:

我来详细说明Python使用SMTP发送邮件的配置方法:
基础配置
使用 smtplib 库(标准库)
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
# 配置邮件服务器
smtp_config = {
'server': 'smtp.example.com', # SMTP服务器地址
'port': 587, # 端口(587-TLS, 465-SSL)
'use_tls': True, # 是否使用TLS
'username': 'your@email.com',
'password': 'your_password'
}
# 创建邮件内容
message = MIMEText('邮件正文内容', 'plain', 'utf-8')
message['Subject'] = Header('邮件主题', 'utf-8')
message['From'] = smtp_config['username']
message['To'] = 'recipient@email.com'
# 发送邮件
try:
with smtplib.SMTP(smtp_config['server'], smtp_config['port']) as server:
if smtp_config['use_tls']:
server.starttls() # 启用TLS加密
server.login(smtp_config['username'], smtp_config['password'])
server.send_message(message)
print("邮件发送成功!")
except Exception as e:
print(f"发送失败:{e}")
各主流邮箱SMTP配置
Gmail
config = {
'server': 'smtp.gmail.com',
'port': 587,
'use_tls': True,
# 需要开启"应用专用密码"或启用"允许不够安全的应用"
}
QQ邮箱
config = {
'server': 'smtp.qq.com',
'port': 465, # 使用SSL
'use_tls': False,
'use_ssl': True,
# 密码需要使用授权码(在QQ邮箱设置中生成)
}
网易邮箱
config = {
'server': 'smtp.163.com',
'port': 465, # SSL
# 或 port: 25(无加密)
'use_tls': False,
'use_ssl': True
}
Outlook/Hotmail
config = {
'server': 'smtp-mail.outlook.com',
'port': 587,
'use_tls': True
}
企业邮箱
config = {
'server': 'smtp.yourcompany.com',
'port': 25, # 或 465, 587
'use_tls': True # 根据企业配置
}
完整示例:发送HTML邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os
def send_email(smtp_config, to_email, subject, body, attachments=None):
"""
发送邮件
:param smtp_config: SMTP配置字典
:param to_email: 收件人邮箱
:param subject: 邮件主题
:param body: 邮件正文(支持HTML)
:param attachments: 附件列表(文件路径)
"""
# 创建邮件对象
msg = MIMEMultipart('alternative')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = smtp_config['username']
msg['To'] = to_email
# 添加正文(支持HTML)
html_part = MIMEText(body, 'html', 'utf-8')
msg.attach(html_part)
# 添加附件
if attachments:
for file_path in attachments:
if os.path.isfile(file_path):
with open(file_path, 'rb') as f:
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(f.read())
encoders.encode_base64(attachment)
attachment.add_header(
'Content-Disposition',
f'attachment; filename="{os.path.basename(file_path)}"'
)
msg.attach(attachment)
# 发送邮件
try:
if smtp_config.get('use_ssl', False):
# 使用SSL连接
with smtplib.SMTP_SSL(smtp_config['server'], smtp_config['port']) as server:
server.login(smtp_config['username'], smtp_config['password'])
server.send_message(msg)
else:
# 使用TLS连接
with smtplib.SMTP(smtp_config['server'], smtp_config['port']) as server:
if smtp_config.get('use_tls', True):
server.starttls()
server.login(smtp_config['username'], smtp_config['password'])
server.send_message(msg)
print(f"邮件成功发送到 {to_email}")
return True
except smtplib.SMTPAuthenticationError:
print("认证失败,请检查用户名和密码")
return False
except smtplib.SMTPException as e:
print(f"SMTP错误:{e}")
return False
except Exception as e:
print(f"发送失败:{e}")
return False
# 使用示例
if __name__ == "__main__":
# QQ邮箱配置
config = {
'server': 'smtp.qq.com',
'port': 465,
'use_ssl': True,
'username': 'your_email@qq.com',
'password': 'your_authorization_code' # QQ邮箱的授权码
}
# HTML邮件内容
html_content = """
<html>
<body>
<h2>您好!</h2>
<p>这是一封测试邮件。</p>
<p>发送时间:{time}</p>
</body>
</html>
""".format(time=__import__('datetime').datetime.now())
# 发送
send_email(
config,
to_email='recipient@example.com',
subject='测试邮件',
body=html_content,
attachments=['file1.pdf', 'image.jpg'] # 可选附件
)
使用第三方库 yagmail(更简单)
# 安装:pip install yagmail
import yagmail
# 配置
yag = yagmail.SMTP(
user='your@email.com',
password='your_password',
host='smtp.example.com', # 可选,自动识别常见邮箱
port=587
)
# 发送
yag.send(
to=['recipient1@email.com', 'recipient2@email.com'],
subject='邮件主题',
contents='邮件正文',
attachments=['file.pdf', 'image.jpg']
)
使用环境变量存储敏感信息
import os
from dotenv import load_dotenv # pip install python-dotenv
load_dotenv() # 加载.env文件
config = {
'server': os.getenv('SMTP_SERVER'),
'port': int(os.getenv('SMTP_PORT', 587)),
'username': os.getenv('SMTP_USERNAME'),
'password': os.getenv('SMTP_PASSWORD'),
'use_tls': os.getenv('SMTP_USE_TLS', 'true').lower() == 'true'
}
.env 文件内容:
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587
SMTP_USERNAME=your@gmail.com
SMTP_PASSWORD=your_app_password
SMTP_USE_TLS=true
常见问题
常见错误及解决:
- 认证失败:检查用户名密码是否正确,QQ邮箱需使用授权码
- 连接超时:检查端口号(25, 465, 587)和防火墙设置
- 被标记为垃圾邮件:添加SPF记录,使用DKIM签名
安全建议:
- 永远不要在代码中硬编码密码
- 使用环境变量或配置文件
- 对密码进行加密存储
- 使用应用专用密码而不是主密码
选择合适的配置取决于你的邮箱服务商和安全需求!