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

相关推荐
web135085886351 小时前
Python大数据可视化:基于python的电影天堂数据可视化_django+hive
python·信息可视化·django
东方芷兰1 小时前
伯克利 CS61A 课堂笔记 11 —— Mutability
笔记·python
不会Hello World的小苗4 小时前
Java——列表(List)
java·python·list
m0_748235956 小时前
Python大数据可视化:基于Python的王者荣耀战队的数据分析系统设计与实现_flask+hadoop+spider
hadoop·python·flask
Dyan_csdn6 小时前
【Python项目】基于Python的Web漏洞挖掘系统
网络·python·安全·web安全
Minner-Scrapy6 小时前
DApp 开发入门指南
开发语言·python·web app
lllsure6 小时前
Linux 实用指令
linux·物联网
&小刘要学习&6 小时前
anaconda不显示jupyter了?
python·jupyter
jerry-896 小时前
jupyterhub_config配置文件内容
python
奔跑吧邓邓子7 小时前
【Python爬虫(36)】深挖多进程爬虫性能优化:从通信到负载均衡
开发语言·爬虫·python·性能优化·负载均衡·多进程