一、SMTP概述
SMTP(Simple Mail Transfer Protocol,简单邮件传输协议)是一种用于发送和接收电子邮件的标准协议。SMTP服务器可以通过TCP(传输控制协议)25端口进行连接。SMTP协议用于从邮件客户端发送邮件到邮件服务器或从邮件服务器传输邮件到另一个邮件服务器。
二、Python邮件模块
Python提供了邮件模块来构建和发送电子邮件。该模块支持以下协议:
- SMTP(Simple Mail Transfer Protocol,简单邮件传输协议)
- POP(Post Office Protocol,邮局协议)和IMAP(Internet Mail Access Protocol,互联网邮件访问协议)
邮件模块可以使用以下命令来安装:
pip install secure-smtplib
三、搭建本地SMTP服务器
使用Python搭建本地SMTP服务器,可以作为邮件服务器或构建一个用来发送邮件的本地测试服务器。这需要Python的Simple Mail Transfer Protocol(smtplib)模块。
步骤1:导入smtplib模块并建立连接。
import smtplib email = 'youremail@example.com' password = 'yourpassword' server = smtplib.SMTP('localhost', 1025) server.ehlo() server.starttls() server.login(email, password)
步骤2:填写电子邮件的正文和附件(如果需要)。
from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage msg = MIMEMultipart() msg.attach(MIMEText('This is a test email')) with open('image.jpg', 'rb') as f: img_data = f.read() msg.attach(MIMEImage(img_data, name='image.jpg'))
步骤3:发送电子邮件并关闭连接。
from_address = 'youremail@example.com' to_address = 'recipient@example.com' server.sendmail(from_address, to_address, msg.as_string()) server.quit()
四、完整代码示例
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage email = 'youremail@example.com' password = 'yourpassword' server = smtplib.SMTP('localhost', 1025) server.ehlo() server.starttls() server.login(email, password) msg = MIMEMultipart() msg['From'] = 'youremail@example.com' msg['To'] = 'recipient@example.com' msg['Subject'] = 'Test Email' body = 'This is a test email' msg.attach(MIMEText(body, 'plain')) with open('image.jpg', 'rb') as f: img_data = f.read() msg.attach(MIMEImage(img_data, name='image.jpg')) from_address = 'youremail@example.com' to_address = 'recipient@example.com' server.sendmail(from_address, to_address, msg.as_string()) server.quit()