在CentOS中配置Python郵件發送功能,通常需要以下幾個步驟:
安裝必要的軟件包:
sudo yum install python3
smtplib
(Python標準庫中自帶)和email
(Python標準庫中自帶),或者使用第三方庫如yagmail
。配置郵件服務器:
編寫Python腳本:
使用Python的smtplib
庫來發送郵件。以下是一個簡單的示例腳本:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 郵件發送者
sender_email = "your_email@example.com"
# 郵件接收者
receiver_email = "receiver_email@example.com"
# SMTP服務器地址
smtp_server = "smtp.example.com"
# SMTP服務器端口
smtp_port = 587
# SMTP服務器用戶名
smtp_username = "your_smtp_username"
# SMTP服務器密碼
smtp_password = "your_smtp_password"
# 創建郵件對象
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = "Test Email"
# 郵件正文
body = "This is a test email sent from Python."
message.attach(MIMEText(body, "plain"))
# 連接到SMTP服務器并發送郵件
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
text = message.as_string()
server.sendmail(sender_email, receiver_email, text)
server.quit()
print("Email sent successfully!")
except Exception as e:
print(f"Failed to send email: {e}")
運行腳本:
send_email.py
),然后在終端中運行:python3 send_email.py
調試和測試:
通過以上步驟,你應該能夠在CentOS系統中配置并使用Python發送郵件。