《Python httplib,smtplib使用方法详解》
在Python编程中,网络通信和邮件发送是常见的需求。Python标准库提供了`httplib`(Python 3中更名为`http.client`)和`smtplib`模块,分别用于HTTP协议交互和SMTP协议邮件发送。本文将详细解析这两个模块的核心功能、使用场景及代码实现,帮助开发者快速掌握网络请求和邮件发送的技巧。
一、httplib(http.client)模块详解
`httplib`是Python 2中的模块名,在Python 3中更名为`http.client`,但功能保持一致。它提供了底层HTTP协议交互的接口,支持发送HTTP/HTTPS请求并获取响应。
1. 模块导入与基础用法
Python 3中需导入`http.client`模块:
import http.client
创建HTTP连接并发送GET请求的示例:
conn = http.client.HTTPSConnection("www.example.com")
conn.request("GET", "/")
response = conn.getresponse()
print(response.status, response.reason)
data = response.read()
print(data.decode())
conn.close()
2. 发送不同HTTP方法请求
(1)GET请求:
conn = http.client.HTTPSConnection("api.example.com")
conn.request("GET", "/data?id=123")
response = conn.getresponse()
print(response.read().decode())
(2)POST请求(带请求体):
conn = http.client.HTTPSConnection("api.example.com")
headers = {"Content-type": "application/json"}
body = '{"name": "John", "age": 30}'
conn.request("POST", "/api", body=body, headers=headers)
response = conn.getresponse()
print(response.read().decode())
(3)PUT/DELETE请求:
# PUT请求
conn.request("PUT", "/api/123", body='{"status": "active"}', headers=headers)
# DELETE请求
conn.request("DELETE", "/api/123")
3. 处理响应数据
响应对象包含状态码、原因短语和响应体:
response = conn.getresponse()
print("Status:", response.status) # 200
print("Reason:", response.reason) # OK
print("Headers:", response.getheaders()) # [('Content-type', 'text/html'), ...]
print("Body:", response.read().decode())
4. HTTPS与超时设置
使用HTTPS连接时需指定端口443(默认):
conn = http.client.HTTPSConnection("secure.example.com", timeout=10)
超时参数`timeout`可避免长时间等待。
5. 完整示例:获取网页内容
import http.client
def fetch_webpage(url):
try:
if url.startswith("https://"):
conn = http.client.HTTPSConnection(url[8:])
else:
conn = http.client.HTTPConnection(url[7:])
path = "/" if len(url.split("/"))
二、smtplib模块详解
`smtplib`是Python用于发送邮件的标准库模块,支持SMTP协议与邮件服务器交互。
1. 模块导入与基础配置
导入模块并创建SMTP连接:
import smtplib
from email.mime.text import MIMEText
from email.header import Header
连接SMTP服务器(以163邮箱为例):
smtp_server = "smtp.163.com"
smtp_port = 465 # SSL端口
sender = "your_email@163.com"
password = "your_password" # 或授权码
2. 发送纯文本邮件
创建邮件内容并发送:
def send_text_email(receiver, subject, content):
message = MIMEText(content, "plain", "utf-8")
message["From"] = Header(sender)
message["To"] = Header(receiver)
message["Subject"] = Header(subject, "utf-8")
try:
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
server.login(sender, password)
server.sendmail(sender, [receiver], message.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {str(e)}")
调用示例:
send_text_email("recipient@example.com", "Test", "Hello from Python!")
3. 发送HTML格式邮件
修改MIME类型为`html`:
def send_html_email(receiver, subject, html_content):
message = MIMEText(html_content, "html", "utf-8")
message["From"] = Header(sender)
message["To"] = Header(receiver)
message["Subject"] = Header(subject, "utf-8")
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
server.login(sender, password)
server.sendmail(sender, [receiver], message.as_string())
调用示例:
html_content = """
Hello!
This is an HTML email.
"""
send_html_email("recipient@example.com", "HTML Test", html_content)
4. 发送带附件的邮件
使用`email.mime`模块组合多部分邮件:
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def send_email_with_attachment(receiver, subject, content, file_path):
message = MIMEMultipart()
message["From"] = Header(sender)
message["To"] = Header(receiver)
message["Subject"] = Header(subject, "utf-8")
# 添加文本部分
text_part = MIMEText(content, "plain", "utf-8")
message.attach(text_part)
# 添加附件
with open(file_path, "rb") as f:
attachment = MIMEApplication(f.read())
attachment.add_header("Content-Disposition", "attachment", filename=file_path.split("/")[-1])
message.attach(attachment)
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
server.login(sender, password)
server.sendmail(sender, [receiver], message.as_string())
调用示例:
send_email_with_attachment(
"recipient@example.com",
"Attachment Test",
"Please find the attached file.",
"/path/to/file.pdf"
)
5. 使用非SSL端口(如587)
部分邮件服务商(如Gmail)使用587端口并支持STARTTLS:
smtp_port = 587
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls() # 启用加密
server.login(sender, password)
server.sendmail(sender, [receiver], message.as_string())
6. 完整示例:综合邮件发送
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
def send_comprehensive_email(receiver, subject, text_content, html_content=None, attachments=None):
message = MIMEMultipart("mixed") # "mixed"表示混合类型
message["From"] = Header(sender)
message["To"] = Header(receiver)
message["Subject"] = Header(subject, "utf-8")
# 添加文本和HTML部分(alternative类型)
alternative = MIMEMultipart("alternative")
alternative.attach(MIMEText(text_content, "plain", "utf-8"))
if html_content:
alternative.attach(MIMEText(html_content, "html", "utf-8"))
message.attach(alternative)
# 添加附件
if attachments:
for file_path in attachments:
with open(file_path, "rb") as f:
part = MIMEApplication(f.read())
part.add_header("Content-Disposition", "attachment", filename=file_path.split("/")[-1])
message.attach(part)
try:
with smtplib.SMTP_SSL("smtp.163.com", 465) as server:
server.login(sender, password)
server.sendmail(sender, [receiver], message.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {str(e)}")
# 调用示例
send_comprehensive_email(
receiver="recipient@example.com",
subject="Comprehensive Email",
text_content="This is a plain text part.",
html_content="""HTML Part
This is HTML content.
""",
attachments=["/path/to/file1.pdf", "/path/to/file2.txt"]
)
三、常见问题与解决方案
1. httplib连接失败
问题:`ConnectionRefusedError`或超时。
解决:检查目标服务器是否可达,确认URL和端口正确,增加`timeout`参数。
2. smtplib认证失败
问题:`smtplib.SMTPAuthenticationError`。
解决:确认用户名和密码(或授权码)正确,检查是否需要启用SMTP服务(如163邮箱需在设置中开启)。
3. 邮件被标记为垃圾邮件
问题:邮件被拒收或进入垃圾箱。
解决:使用正规的邮件服务商,避免敏感词,设置正确的`From`和`Reply-To`头。
四、总结
`httplib`(`http.client`)和`smtplib`是Python中处理HTTP请求和邮件发送的核心模块。通过本文的详细讲解,开发者可以掌握:
- 使用`http.client`发送GET/POST/PUT/DELETE请求并处理响应。
- 通过`smtplib`发送纯文本、HTML和带附件的邮件。
- 处理HTTPS连接、超时设置和认证问题。
掌握这些技能后,开发者可以轻松实现网页数据抓取、API调用和自动化邮件通知等功能。
关键词:Python、httplib、http.client、smtplib、HTTP请求、邮件发送、SMTP协议、网络编程、附件发送、HTML邮件
简介:本文详细介绍了Python中`httplib`(Python 3为`http.client`)和`smtplib`模块的使用方法,包括HTTP请求的发送与响应处理、纯文本/HTML/带附件邮件的发送技巧,以及常见问题的解决方案,适合需要实现网络通信和邮件发送功能的开发者。