阅读量:0
在CentOS上配置Python邮件发送,你可以使用smtplib库,这是一个用于发送电子邮件的Python标准库。以下是一个简单的示例,展示了如何使用smtplib和email库发送一封电子邮件。
- 首先,确保你已经安装了Python。CentOS 7默认安装了Python 2.7,但我们将使用Python 3。如果尚未安装,请运行以下命令安装:
sudo yum install python3
- 接下来,安装
postfix,这是一个用于处理邮件传输的邮件服务器。运行以下命令安装:
sudo yum install postfix
在安装过程中,选择"Internet Site"作为配置类型,然后设置系统邮件名称。
- 启动并启用
postfix服务:
sudo systemctl start postfix
sudo systemctl enable postfix
- 创建一个Python脚本以发送电子邮件。使用文本编辑器创建一个名为
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系统的测试电子邮件。
以上就是关于“在CentOS上如何配置Python邮件发送”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm