Python3 网易126邮箱收发邮件

参考廖雪峰的Python教程,实现Python3 网易126邮箱收发邮件

发邮件

#!/usr/bin/python3
# coding: utf-8

import smtplib
from email import encoders 
from email.header import Header 
from email.mime.text import MIMEText 
from email.utils import parseaddr 
from email.utils import formataddr 

def format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, "utf-8").encode(), addr))

from_email = "[email protected]"
from_email_pwd = "xxx"
to_email = "[email protected]"
smtp_server = "smtp.126.com"

msg = MIMEText("

hello

hello, send by python

", "html", "utf-8") msg["From"] = format_addr("%s" %(from_email)) msg["To"] = format_addr("%s" %(to_email)) msg["Subject"] = Header("python email", "utf-8").encode() server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_email, from_email_pwd) server.sendmail(from_email, [to_email], msg.as_string()) server.quit()

收邮件

#!/usr/bin/python3
# coding: utf-8

import poplib
from email.header import decode_header 
from email.parser import Parser 
from email.utils import parseaddr 

def print_msg(msg, indent=0):
    if indent == 0:
        for header in ["From", "To", "Subject", "Date"]:
            value = msg[header]
            if value:
                value = decode_str(value)
            print("%s%s: %s" %(" " * indent, header, value))
    if msg.is_multipart():
        parts = msg.get_payload()
        for n, part in enumerate(parts):
            print("%spart %s" %(" " * indent, n))
            print_msg(part, indent + 1)
    else:
        content_type = msg.get_content_type()
        if content_type == "text/plain" or content_type == "text/html":
            content = msg.get_payload(decode=True)
            charset = get_charset(msg)
            if charset:
                content = content.decode(charset)
            print("%sText: %s" %(" " * indent, content))
        else:
            print("%sAttachment: %s" %(" " * indent, content_type))

def decode_str(s):
    l = decode_header(s)
    value, charset = l[0]
    if charset:
        value = value.decode(charset)

    if len(l) == 2:
        value_tmp = l[1][0]
        value = value + value_tmp.decode(charset)
    return value 

def get_charset(msg):
    charset = msg.get_charset()
    if charset is None:
        content_type = msg.get("Content-type", "").lower()
        pos = content_type.find("charset=")
        if pos >= 0:
            charset = content_type[pos + 8:].strip()
    return charset 

from_email = "[email protected]"
from_email_pwd = "xxx"
pop_server = "pop.126.com"

server = poplib.POP3(pop_server)
server.set_debuglevel(1)
print(server.getwelcome().decode("utf-8"))

server.user(from_email)
server.pass_(from_email_pwd)

print("Messages: %s Size: %s" %(server.stat()))

resp, mails, octets = server.list()
index = len(mails)
resp, lines, octets = server.retr(index)
msg_content = b"\r\n".join(lines).decode("utf-8")
msg = Parser().parsestr(msg_content)
print_msg(msg)
server.quit()

你可能感兴趣的:(Python)