温馨提示×

温馨提示×

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

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

Linux Python邮件发送与接收

发布时间:2024-09-11 22:22:57 来源:亿速云 阅读:78 作者:小樊 栏目:编程语言

在 Linux 系统中,使用 Python 发送和接收邮件可以通过内置的 smtplibimaplib 库来实现

  1. 发送邮件:

首先,确保已经安装了 smtplib 库。然后,编写如下代码:

import smtplib
from email.mime.text import MIMEText

# 设置邮件服务器、用户名和密码
smtp_server = 'smtp.example.com'
username = 'your_email@example.com'
password = 'your_password'

# 创建邮件对象
msg = MIMEText('这是一封测试邮件。')
msg['Subject'] = '测试邮件'
msg['From'] = username
msg['To'] = 'recipient@example.com'

# 连接到邮件服务器并发送邮件
try:
    server = smtplib.SMTP(smtp_server, 587)
    server.starttls()
    server.login(username, password)
    server.sendmail(username, 'recipient@example.com', msg.as_string())
    print('邮件发送成功!')
except Exception as e:
    print(f'邮件发送失败:{e}')
finally:
    server.quit()
  1. 接收邮件:

首先,确保已经安装了 imaplib 库。然后,编写如下代码:

import imaplib
import email
from email.header import decode_header

# 设置邮件服务器、用户名和密码
imap_server = 'imap.example.com'
username = 'your_email@example.com'
password = 'your_password'

# 连接到邮件服务器并登录
mail = imaplib.IMAP4_SSL(imap_server)
mail.login(username, password)

# 选择要读取的邮箱(例如:INBOX)
mail.select('inbox')

# 搜索并获取所有未读邮件
status, messages = mail.search(None, '(UNSEEN)')
messages = messages[0].split()

# 遍历并打印未读邮件的信息
for msg_num in messages:
    status, msg_data = mail.fetch(msg_num, '(RFC822)')
    msg = email.message_from_bytes(msg_data[0][1])
    
    subject = decode_header(msg['subject'])[0][0]
    from_ = msg.get('From')
    date = msg.get('Date')
    
    print(f'邮件编号:{msg_num}')
    print(f'主题:{subject.decode()}')
    print(f'发件人:{from_}')
    print(f'日期:{date}')
    print('-' * 20)

# 退出并关闭邮件服务器连接
mail.logout()

请注意,您需要将示例代码中的邮件服务器地址、用户名和密码替换为您自己的实际信息。同时,根据需要调整邮件搜索条件和处理逻辑。

向AI问一下细节

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

AI