在 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'] = "your_email@gmail.com"
msg['To'] = "recipient@example.com"

# Connect to the SMTP server and send the email
with smtplib.SMTP('localhost') as server:
    server.sendmail("your_email@gmail.com", "recipient@example.com", 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('your_email@gmail.com', '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())

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

确保将"your_email@gmail.com"、"recipient@example.com"和"your_imap_server.com"等占位符值替换为的实际电子邮件地址和服务器信息。

相关推荐
2401_883600255 分钟前
golang如何理解weak pointer弱引用_golang weak pointer弱引用总结
jvm·数据库·python
FreakStudio7 分钟前
和做工厂系统的印尼老哥,复刻了一套属于 MicroPython 的包管理系统
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
偶尔上线经常挺尸11 分钟前
《每日一命令08:scp——安全的远程复制》
linux·安全·scp·文件传输·运维基础·远程复制
2301_7735536218 分钟前
mysql如何评估SQL语句的索引开销_mysql性能追踪与分析
jvm·数据库·python
计算机安禾32 分钟前
【Linux从入门到精通】第17篇:日志系统——系统运行的黑匣子
linux·运维·服务器
l1t36 分钟前
DeepSeek辅助解决windows 11 wsl2中Linux版Dbeaver显示中文
linux·运维·windows
pele1 小时前
PHP源码运行受主板供电影响吗_供电相数重要性说明【技巧】
jvm·数据库·python
sinat_383437361 小时前
CSS如何实现元素悬浮在页面底部_利用fixed定位与底部间距
jvm·数据库·python
gmaajt2 小时前
mysql如何备份与恢复函数定义_mysql mysqldump导出存储对象
jvm·数据库·python
qq_460978402 小时前
Python爬虫怎么模拟手机端抓取_设置手机型号User-Agent字符串
jvm·数据库·python