Python SMTP学习笔记
SMTP是指简单邮件传输协议(Simple Mail Transfer Protocol),是网络中用于发送电子邮件的标准协议。Python自带了SMTP库,可以方便地发送邮件。
安装SMTP库
Python自带了SMTP库,无需安装。
连接SMTP服务器
在使用SMTP库发送邮件之前,我们需要先连接SMTP服务器。SMTP服务器的地址和端口号与不同的邮件服务提供商有关。以Gmail为例:
pythonCopy Codeimport smtplib
smtp_server = "smtp.gmail.com"
port = 587
smtp_user = "youremail@gmail.com"
smtp_password = "yourpassword"
server = smtplib.SMTP(smtp_server, port)
server.starttls()
server.login(smtp_user, smtp_password)
以上代码会连接到Gmail的SMTP服务器,并使用TLS加密进行通信。其中,smtp_user
和smtp_password
分别是你的Gmail邮箱地址和密码。
发送邮件
连接SMTP服务器成功后,我们就可以开始发送邮件了。
pythonCopy Codefrom email.mime.text import MIMEText
from email.header import Header
def send_email(sender, receiver, subject, body):
message = MIMEText(body, 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(receiver, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
server.sendmail(sender, [receiver], message.as_string())
send_email('youremail@gmail.com', 'recipientemail@gmail.com', 'Hello from Python!', 'This is a test email sent from Python.')
以上代码会向recipientemail@gmail.com
发送一封标题为Hello from Python!
的测试邮件。
发送带附件的邮件
除了发送纯文本邮件,SMTP库还可以发送带附件的邮件。
pythonCopy Codefrom email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
def send_email_with_attachment(sender, receiver, subject, body, filepath):
message = MIMEMultipart()
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(receiver, 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
# 添加文本内容
message.attach(MIMEText(body, 'plain', 'utf-8'))
# 添加附件
with open(filepath, 'rb') as f:
attachment = MIMEApplication(f.read(), _subtype=None)
attachment.add_header('Content-Disposition', 'attachment', filename=filepath.split('/')[-1])
message.attach(attachment)
server.sendmail(sender, [receiver], message.as_string())
send_email_with_attachment('youremail@gmail.com', 'recipientemail@gmail.com', 'Email with Attachment', 'This is an email with an attachment sent from Python.', 'path/to/attachment')
以上代码会向recipientemail@gmail.com
发送一封标题为Email with Attachment
的测试邮件,并附带文件path/to/attachment
作为附件。
结束SMTP会话
在结束程序之前,我们需要显式地关闭SMTP会话。
pythonCopy Codeserver.quit()
以上代码会关闭与SMTP服务器的连接。