python邮件收发

邮件发送

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#coding=utf-8
import smtplib
from email.mime.text import MIMEText
msg_from='xxxxxxxx' #发送方邮箱
passwd='xxxxxxx' #填入发送方邮箱的授权码
msg_to='939682389@qq.com' #收件人邮箱

subject="python邮件测试" #主题
content="这是我使用python smtplib及email模块发送的邮件"#正文
msg = MIMEText(content)
msg['Subject'] = subject
msg['From'] = msg_from
msg['To'] = msg_to
try:
s = smtplib.SMTP_SSL("smtp.qq.com",465)#邮件服务器及端口号
s.login(msg_from, passwd)
s.sendmail(msg_from, msg_to, msg.as_string())
print ("发送成功")
except s.SMTPException.e:
print ("发送失败")
finally:
s.quit()

邮件接收

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#coding=gbk

import re
import poplib
import email
import datetime
import time
import os
import mysql
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr

# 输入邮件地址, 口令和POP3服务器地址:
email = '939682389@qq.com'
password = 'xxxxxxxxxx'
pop3_server = 'pop.qq.com'


while 1:
try:
# 连接到POP3服务器:例如pop.163.com
server = poplib.POP3_SSL(pop3_server)
# 可以打开或关闭调试信息:
server.set_debuglevel(1)
# 可选:打印POP3服务器的欢迎文字:
#print(server.getwelcome())

# 身份认证:
server.user(email)
server.pass_(password)

# stat()返回邮件数量和占用空间:
#print('Messages: %s. Size: %s' % (server.stat()))
# list()返回所有邮件的编号:
resp, mails, octets = server.list()
# 可以查看返回的列表类似['1 82923', '2 2184', ...]
#print(mails)
# 获取最新一封邮件, 注意索引号从1开始:
index = len(mails)
resp, lines, octets = server.retr(index)
# lines存储了邮件的原始文本的每一行,它是个列表

# 可以获得整个邮件的原始文本:
msg_content = b'\r\n'.join(lines).decode('utf-8')
# 解析出邮件:这里输出msg是个乱的,还没有真正的解析
msg = Parser().parsestr(msg_content)
#print(msg)
# 可以根据邮件索引号直接从服务器删除邮件:
# server.dele(index)
# 关闭连接:

server.quit()

time.sleep(5)

More info: Server