一、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()
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/307056.html