本系列博文基于廖雪峰老师的官网Python教程,笔者在大学期间已经阅读过廖老师的Python教程,教程相当不错,官网链接: 廖雪峰官方网站.请需要系统学习Python的小伙伴到廖老师官网学习,笔者的编程环境是Anaconda+Pycharm,Python版本:Python3.
1.电子邮件简介
2.SMTP发送邮件
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = input('From: ')
password = input('Password: ')
to_addr = input('To: ')
smtp_server = input('SMTP server: ')
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
msg['From'] = _format_addr('Willard <%s>' % from_addr)
msg['To'] = _format_addr('Admin <%s>' % to_addr)
msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
From: xxxx@qq.com
Password: ngcmrsredduvdccd
To: xxxxx@163.com
SMTP server: smtp.qq.com
...
(221,b'Bye.')
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import smtplib
def _format_addr(s):
name, addr = parseaddr(s)
return formataddr((Header(name, 'utf-8').encode(), addr))
from_addr = input('From: ')
password = input('Password: ')
to_addr = input('To: ')
smtp_server = input('SMTP server: ')
msg = MIMEMultipart()
msg['From'] = _format_addr('Willard <%s>' % from_addr)
msg['To'] = _format_addr('Admin <%s>' % to_addr)
msg['Subject'] = Header('Come From SMTP', 'utf-8').encode()
msg.attach(MIMEText("Send with Files.", "plain", "utf-8"))
with open("willard.jpg", "rb") as f:
mime = MIMEBase("image", "jpg", filename = "willard.jpg")
mime.add_header("Content-Disposition", "attachment", filename = "willard.jpg")
mime.add_header("Content-ID", "<0>")
mime.add_header("X-Attachment-Id", "0")
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
server = smtplib.SMTP(smtp_server, 25)
server.starttls()
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
From: xxxx@qq.com
Password: ngcmrsredduvdccd
To: xxxxx@163.com
SMTP server: smtp.qq.com
...
(221,b'Bye.')
3.POP3收取邮件
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
import poplib
email = input("Email:")
password = input("Password:")
pop3_server = input("POP3 server:")
server = poplib.POP3(pop3_server)
server.set_debuglevel(1)
print(server.getwelcome().decode("utf-8"))
server.user(email)
server.pass_(password)
print("Message:%s.Size:%s" % server.stat())
resp, mails, octets = server.list()
print(mails)
index = len(mails)
resp, lines, octets = server.retr(index)
msg_content = b"\r\n".join(lines).decode("utf-8")
msg = Parser().parsestr(msg_content)
def decode_str(s):
value, charset = decode_header(s)[0]
if charset:
value = value.decode(charset)
return value
def guess_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
def print_info(msg, indent=0):
if indent == 0:
for header in ['From', 'To', 'Subject']:
value = msg.get(header, '')
if value:
if header=='Subject':
value = decode_str(value)
else:
hdr, addr = parseaddr(value)
name = decode_str(hdr)
value = u'%s <%s>' % (name, addr)
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('%s--------------------' % (' ' * indent))
print_info(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 = guess_charset(msg)
if charset:
content = content.decode(charset)
print('%sText: %s' % (' ' * indent, content + '...'))
else:
print('%sAttachment: %s' % (' ' * indent, content_type))
if __name__ == "__main__":
print_info(msg, indent = 0)
server.quit()
Email:xxxx@qq.com
Password:ahjycyfdssssedg
POP3 server:pop.qq.com
+OK XMail POP3 Server v1.0 Service Ready(XMail v1.0)
*cmd* 'USER xxx2s4e4@qq.com'
*cmd* 'PASS ahjycyfdsssssedg'
*cmd* 'STAT'
*stat* [b'+OK', b'1', b'8526']
Message:1.Size:8526
*cmd* 'LIST'
[b'1 8526']
*cmd* 'RETR 1'
From: QQ邮箱团队 <10000@qq.com>
To: 思 <3xxxxde4e4@qq.com>
Subject: 更安全、更高效、更强大,尽在QQ邮箱APP
Text:
<!DOCTYPE html>
...
b'+OK Bye'
|