在 Linux-Ubuntu/Debian 上使用 Postfix , Python 发送和接收电子邮件

要在 Ubuntu 上使用 Postfix 在 Python 中发送和接收电子邮件,需要设置和配置 Postfix 作为邮件服务器。 此外,可以使用 Python 中的"smtplib"和"imaplib"库分别发送和接收电子邮件。

以下是一般步骤:

1.安装并配置Postfix:

复制代码
sudo apt-get update
sudo apt-get install postfix

在安装过程中,系统将提示选择配置。 选择"Internet 站点"并输入服务器的完全限定域名 (FQDN)。

2.配置Postfix:

编辑主 Postfix 配置文件:

复制代码
sudo nano /etc/postfix/main.cf

确保配置了以下设置:

复制代码
myhostname = your_fqdn
mydomain = your_domain
myorigin = $mydomain
inet_interfaces = all

your_fqdnyour_domain 替换为服务器的完全限定域名。

3.重新启动Postfix:

复制代码
sudo systemctl restart postfix

4. 使用 Python 发送电子邮件:

可以使用"smtplib"库发送电子邮件。 这是一个例子:

复制代码
import smtplib
from email.mime.text import MIMEText

# Set up the email message
msg = MIMEText("Hello, this is the body of the email.")
msg['Subject'] = "Test Email"
msg['From'] = "[email protected]"
msg['To'] = "[email protected]"

# Connect to the SMTP server and send the email
with smtplib.SMTP('localhost') as server:
    server.sendmail("[email protected]", "[email protected]", msg.as_string())

5.使用Python接收电子邮件:

可以使用"imaplib"库连接到 IMAP 服务器并检索电子邮件。 这是一个例子:

复制代码
import imaplib
import email

# Connect to the IMAP server
mail = imaplib.IMAP4_SSL('your_imap_server.com')
mail.login('[email protected]', 'your_password')

# Select the mailbox you want to read emails from
mail.select('inbox')

# Search for all emails in the mailbox
status, messages = mail.search(None, 'ALL')
messages = messages[0].split()

# Retrieve the latest email
latest_email_id = messages[-1]
status, msg_data = mail.fetch(latest_email_id, '(RFC822)')
raw_email = msg_data[0][1]

# Parse the raw email
msg = email.message_from_bytes(raw_email)

# Print the email subject and body
print("Subject:", msg['Subject'])
print("Body:", msg.get_payload())

注意:不建议将密码直接存储在代码中。 使用安全方法处理凭据,例如环境变量或配置文件。

确保将"[email protected]"、"[email protected]"和"your_imap_server.com"等占位符值替换为的实际电子邮件地址和服务器信息。

相关推荐
深度学习入门11 分钟前
机器学习,深度学习,神经网络,深度神经网络之间有何区别?
人工智能·python·深度学习·神经网络·机器学习·机器学习入门·深度学习算法
酷爱码19 分钟前
Linux实现临时RAM登录的方法汇总
linux·前端·javascript
muxue17828 分钟前
chmod 777含义:
linux
Snasph33 分钟前
Ubnutu ADB 无法识别设备的解决方法
ubuntu·adb
帷幄庸者43 分钟前
CentOS 上配置 Docker 使用 NVIDIA GPU
linux·docker·centos
xbd_zc1 小时前
【Linux Nano Vim快捷键大全】
linux·运维·vim
森哥的歌1 小时前
Python uv包管理器使用指南:从入门到精通
python·开发工具·uv·虚拟环境·包管理
qq_214782611 小时前
给你的matplotlib images添加scale Bar
python·数据分析·matplotlib
Mapleay1 小时前
ubuntu 更新华为源
运维·服务器·ubuntu
Johny_Zhao1 小时前
Vmware workstation安装部署微软SCCM服务系统
网络·人工智能·python·sql·网络安全·信息安全·微软·云计算·shell·系统运维·sccm