Python中怎么实现自动收发邮件功能

发布时间:2021-08-09 13:43:04 作者:Leah
来源:亿速云 阅读:170
# 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

二、自动发送邮件

1. 基础文本邮件

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())

2. 发送带附件的邮件

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)

三、自动接收邮件

1. 连接邮箱服务器

def connect_mailbox(email, password):
    mail = imaplib.IMAP4_SSL('imap.example.com')
    mail.login(email, password)
    mail.select('inbox')  # 选择收件箱
    return mail

2. 读取未读邮件

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()

五、安全注意事项

  1. 不要硬编码密码,建议使用环境变量或配置文件
  2. 启用SMTP/IMAP的SSL加密(端口465/993)
  3. 企业邮箱可能需要配置应用专用密码
  4. 敏感操作建议添加异常处理:
try:
    server = smtplib.SMTP_SSL(smtp_server, 465)
    server.login(email, password)
except Exception as e:
    print(f"邮件发送失败: {str(e)}")

通过上述方法,你可以轻松实现邮件的自动化处理。根据实际需求,还可以扩展定时任务、邮件过滤等功能,构建更复杂的自动化工作流。 “`

推荐阅读:
  1. Java如何实现邮件收发?
  2. 如何使用python自动收发邮件

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:python中最短路径问题的示例分析

下一篇:怎么选择全国动态ip代理

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》