2024 python 脚本收发邮件
时间: 2024-10-10 22:11:32 浏览: 47
在Python中,你可以使用内置的`smtplib`和`email`库来编写脚本来发送和接收电子邮件。以下是基本步骤:
**发送邮件(SMTP)**:
```python
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 邮件配置
smtp_server = "your-smtp-server.com"
port = 587 # 或者465 for SSL/TLS
username = "your-email@example.com"
password = "your-password"
def send_email(recipient, subject, message):
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = recipient
msg['Subject'] = subject
body = MIMEText(message, 'plain')
msg.attach(body)
server = smtplib.SMTP(smtp_server, port)
server.starttls() # 如果需要加密
server.login(username, password)
text = msg.as_string()
server.sendmail(username, recipient, text)
server.quit()
# 示例用法
send_email("recipient@example.com", "测试邮件", "这是一封测试邮件")
```
**接收邮件(POP3 / IMAP)**:
```python
import imaplib
from email.parser import BytesParser
# 邮箱配置
imap_server = "your-imap-server.com"
imap_port = 993 # or 143 for non-SSL
username = "your-email@example.com"
password = "your-password"
def fetch_emails():
mail = imaplib.IMAP4_SSL(imap_server) if imap_port == 993 else imaplib.IMAP4(imap_server)
mail.login(username, password)
mail.select('inbox') # 根据邮箱选择合适的标签
status, messages = mail.search(None, 'ALL')
latest_email_id = messages[0].split()[-1] # 获取最新邮件ID
typ, data = mail.fetch(latest_email_id, '(RFC822)')
raw_email = data[0][1]
email_message = BytesParser().parsebytes(raw_email)
# 解析邮件内容
...
mail.close()
mail.logout()
fetch_emails()
```
请注意,实际应用中你需要替换上面的服务器地址、端口和用户名密码。此外,处理邮件内容通常会涉及到解析`email.message.Message`对象,根据具体需求提取发件人、主题、正文等信息。
阅读全文