您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python中怎么实现自动收发邮件功能
在现代办公和自动化场景中,邮件自动收发是提高效率的重要手段。Python通过`smtplib`和`imaplib`等标准库提供了完整的邮件处理能力。本文将详细介绍如何用Python实现邮件的自动发送、接收及附件处理。
## 一、环境准备
首先确保Python环境已安装(建议3.6+版本),无需额外安装库:
```python
# 所需标准库
import smtplib # 发送邮件
import imaplib # 接收邮件
import email # 邮件解析
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_email(sender, password, receiver, subject, body):
msg = MIMEText(body, 'plain', 'utf-8')
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
server.login(sender, password)
server.sendmail(sender, [receiver], msg.as_string())
def send_with_attachment(sender, password, receiver, subject, body, file_path):
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receiver
# 添加正文
msg.attach(MIMEText(body, 'plain'))
# 添加附件
with open(file_path, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename="{file_path}"')
msg.attach(part)
with smtplib.SMTP_SSL('smtp.example.com', 465) as server:
server.login(sender, password)
server.send_message(msg)
def connect_mailbox(email, password):
mail = imaplib.IMAP4_SSL('imap.example.com')
mail.login(email, password)
mail.select('inbox') # 选择收件箱
return mail
def fetch_unread_emails(mail):
status, messages = mail.search(None, 'UNSEEN')
email_ids = messages[0].split()
emails = []
for e_id in email_ids:
_, data = mail.fetch(e_id, '(RFC822)')
raw_email = data[0][1]
email_message = email.message_from_bytes(raw_email)
# 解析邮件内容
subject = email_message['subject']
from_ = email_message['from']
body = ""
if email_message.is_multipart():
for part in email_message.walk():
if part.get_content_type() == 'text/plain':
body = part.get_payload(decode=True).decode()
else:
body = email_message.get_payload(decode=True).decode()
emails.append({'subject': subject, 'from': from_, 'body': body})
return emails
def mail_automation():
# 配置信息
email = "your_email@example.com"
password = "your_password"
smtp_server = "smtp.example.com"
imap_server = "imap.example.com"
# 自动发送
send_email(email, password, "receiver@example.com", "自动邮件", "这是Python自动发送的邮件")
# 自动接收
mail = connect_mailbox(email, password)
unread_emails = fetch_unread_emails(mail)
for msg in unread_emails:
print(f"主题: {msg['subject']}\n发件人: {msg['from']}\n内容: {msg['body'][:100]}...")
mail.logout()
try:
server = smtplib.SMTP_SSL(smtp_server, 465)
server.login(email, password)
except Exception as e:
print(f"邮件发送失败: {str(e)}")
通过上述方法,你可以轻松实现邮件的自动化处理。根据实际需求,还可以扩展定时任务、邮件过滤等功能,构建更复杂的自动化工作流。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。