在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发送邮件。