在CentOS上配置Python邮件发送,你可以使用smtplib库,这是一个用于发送电子邮件的Python标准库。以下是一个简单的示例,展示了如何使用smtplib和email库发送一封电子邮件。
sudo yum install python3
postfix,这是一个用于处理邮件传输的邮件服务器。运行以下命令安装:sudo yum install postfix
在安装过程中,选择"Internet Site"作为配置类型,然后设置系统邮件名称。
postfix服务:sudo systemctl start postfix
sudo systemctl enable postfix
send_email.py的新文件,并添加以下代码: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"
# 邮件主题和内容
subject = "Test Email from CentOS"
body = "This is a test email sent from a CentOS system using Python."
# 创建MIMEMultipart对象并设置邮件头
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
# 将邮件正文添加到MIMEMultipart对象
message.attach(MIMEText(body, "plain"))
# 连接到SMTP服务器并发送邮件
try:
smtp_server = "smtp.example.com" # 替换为你的SMTP服务器地址
smtp_port = 587 # 替换为你的SMTP服务器端口
smtp_username = "your_email@example.com" # 替换为你的SMTP用户名
smtp_password = "your_email_password" # 替换为你的SMTP密码
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(sender_email, receiver_email, message.as_string())
print("Email sent successfully!")
except Exception as e:
print(f"Error sending email: {e}")
finally:
server.quit()
更新脚本中的占位符,例如your_email@example.com、receiver_email@example.com、smtp.example.com等,以匹配你的电子邮件帐户和SMTP服务器设置。
运行脚本以发送电子邮件:
python3 send_email.py
如果一切正常,你应该会收到一封来自CentOS系统的测试电子邮件。