python开发

Python之Zmail邮件处理

2023-01-16  本文已影响0人  羋学僧

介绍

Zmail 使得在python3中发送和接受邮件变得更简单。你不需要手动添加服务器地址、端口以及适合的协议,zmail会帮你完成。此外,使用一个python字典来代表邮件内容也更符合直觉。

安装

Zmail仅支持python3,不需要任何外部依赖. 不支持python2.

$ pip3 install zmail

特性

使用须知

使用它之前,请保证

然后,剩下你需要做的就是import zmail即可

快速入门

import zmail
server = zmail.server('yourmail@example.com', 'yourpassword')

# Send mail
server.send_mail('yourfriend@example.com',{'subject':'Hello!','content_text':'By zmail.'})
# Or to a list of friends.
server.send_mail(['friend1@example.com','friend2@example.com'],{'subject':'Hello!','content_text':'By zmail.'})

# Retrieve mail
latest_mail = server.get_latest()
zmail.show(latest_mail)

应用示例

请看 zmail_demos

import os
import zmail
from contextlib import suppress

USERNAME = ""  # Your mail address.(required)
PASSWORD = ""  # Your mail password.(required)

backup_dir = '{}_backup/'.format(USERNAME)
persist_walk = True
walk_steps = 20
backup_walk_path = backup_dir + '_mail_walk.txt'

srv = zmail.server(USERNAME, PASSWORD)

mail_count, mail_size = srv.stat()

# Make directory if not exist.
with suppress(FileExistsError):
    os.mkdir(backup_dir)


# walk functions.
def get_walk():
    if os.path.exists(backup_walk_path):
        with open(backup_walk_path, mode='r') as f:
            _walk = int(f.read())
        return _walk
    return 1


def save_walk(_walk):
    with open(backup_walk_path, mode='w') as f:
        f.write(str(_walk))


def safe_str(o, max_len=220):
    if o is None:
        return ''
    s = str(o).replace('/', ':')
    if len(s) > max_len:
        return s[:max_len]
    return s


walk = get_walk() if persist_walk else 1
while walk <= mail_count:
    mails = srv.get_mails(start_index=walk, end_index=walk + walk_steps)
    for mail in mails:
        zmail.save(mail,
                   name=safe_str(mail['subject']) + ' ' + safe_str(mail['date']) + '.eml',  # Your mail name.
                   target_path=backup_dir,
                   overwrite=True)
        print('{} {} {}/{}'.format(mail['subject'], mail['date'], walk, mail_count))
        walk += 1
        if persist_walk:
            save_walk(walk)

使用示例

测试SMTP和POP功能是否正常

import zmail
server = zmail.server('yourmail@example.com’, 'yourpassword')

if server.smtp_able():
    pass
    # SMTP function.
if server.pop_able():
    pass
    # POP function.
            

以上功能正常时,返回True,否则返回False,logger会打印相应错误信息。

发送你的邮件

import zmail
mail = {
    'subject': 'Success!',  # Anything you want.
    'content_text': 'This message from zmail!',  # Anything you want.
    'attachments': ['/Users/zyh/Documents/example.zip','/root/1.jpg'],  # Absolute path will be better.
}

server = zmail.server('yourmail@example.com’, 'yourpassword')

server.send_mail('yourfriend@example.com', mail)

你也可以自定义发送者的名字,具体的做法是在在mail中加入'from':'Boss <mymail@foo.com>'

server.send_mail(['yourfriend@example.com','12345@example.com'], mail)

你还可以为收件人定义名字(使用元组,第一个为其命名,第二个为其地址)

server.send_mail([('Boss','yourfriend@example.com'),'12345@example.com'], mail)
mail = {
    'subject': 'Success!',  # Anything you want.
    'content_html': ['HTML CONTENT'], 
    'attachments': '/Users/zyh/Documents/example.zip',  # Absolute path will be better.
}
server.send_mail('yourfriend@example.com',mail)

或者

with open('/Users/example.html','r') as f:
    content_html = f.read()
mail = {
    'subject': 'Success!',  # Anything you want.
    'content_html': content_html, 
    'attachments': '/Users/zyh/Documents/example.zip',  # Absolute path will be better.
}
server.send_mail('yourfriend@example.com',mail)
server.send_mail(['foo@163.com','foo@126.com'],mail,cc=['bar@163.com'])

同样,你也可以为他们命名(使用元组,第一个为其命名,第二个为其地址)

server.send_mail(['foo@163.com','foo@126.com'],mail,cc=[('Boss','bar@163.com'),'bar@126.com'])

如果zmail不能正常工作,你可以自定义server的配置

server = zmail.server('username','password',smtp_host='smtp.163.com',smtp_port=994,smtp_ssl=True,pop_host='pop.163.com',pop_port=995,pop_tls=True)

取回你的邮件

import zmail
server = zmail.server('yourmail@example.com', 'yourpassword')
mail = server.get_latest()
mail = server.get_mail(2)
mail = server.get_mails(subject='GitHub',after='2018-1-1',sender='github')

示例中, 如果 'GitHub' 在邮件的主题中,这封邮件将会被匹配, 例如' [GitHub] Your password has changed'

sender亦是如此

你也可以指定一个范围的邮件

mail = server.get_mails(subject='GitHub',start_time='2018-1-1',sender='github',start_index=1,end_index=10)
mailbox_info = server.stat()

结果为包含两个整型的元组: (邮件的数量, 邮箱的大小).

解析你的邮件

在zmail中,接收到的邮件被映射为一个字典,你可以通过访问python字典的形式来访问你的邮件,例如

subject = mail['subject']

打印你的邮件,使用 zmail.show()

import zmail
server = zmail.server('yourmail@example.com‘, 'yourpassword')
mail = server.get_latest()
zmail.show(mail)

查看邮件的所有内容

import zmail
server = zmail.server('yourmail@example.com’, 'yourpassword')
mail = server.get_latest()
for k,v in mail.items():
    print(k,v)
上一篇 下一篇

猜你喜欢

热点阅读