在 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"等占位符值替换为的实际电子邮件地址和服务器信息。

相关推荐
YYXZZ。。39 分钟前
PyTorch——搭建小实战和Sequential的使用(7)
人工智能·pytorch·python
四川兔兔43 分钟前
pytorch 与 张量的处理
人工智能·pytorch·python
派阿喵搞电子3 小时前
在UI界面内修改了对象名,在#include “ui_mainwindow.h“没更新
c++·qt·ubuntu·ui
AI蜗牛之家4 小时前
Qwen系列之Qwen3解读:最强开源模型的细节拆解
人工智能·python
whyeekkk5 小时前
python打卡第48天
开发语言·python
地衣君7 小时前
RISC-V 开发板 + Ubuntu 23.04 部署 open_vins 过程
linux·ubuntu·risc-v
5:007 小时前
云备份项目
linux·开发语言·c++
Eiceblue7 小时前
Python读取PDF:文本、图片与文档属性
数据库·python·pdf
weixin_527550407 小时前
初级程序员入门指南
javascript·python·算法
码农101号7 小时前
Linux中shell编程表达式和数组讲解
linux·运维·服务器