python模块众多,在网络编程这方面能够发挥它独到的作用,今天就来讲用一些模块进行邮件的接收和发送。先讲用smtp进行发送邮件。直接上源码

# -*- coding: UTF-8 -*-
import cheap nba jerseys smtplib
import email.MIMEMultipart
import email.MIMEText
import email.MIMEBase
import os.path

From = “帐号如:zzz5323381@126.com”
To = “接收方帐号,如:644471937@qq.com”
file_name = “文件路径”

server = smtplib.SMTP(“smtp.126.com”)#smtp服务器地址
server.login(“发送方帐号,如:zzz5323381@126.com”,”密码,这边就不写了”) #仅smtp服务器需要验证时

# 构造MIMEMultipart对象做为根容器
main_msg = email.MIMEMultipart.MIMEMultipart()

# with 构造MIMEText对象做为邮件显示内容并附加到根容器
text_msg = email.MIMEText.MIMEText(“this is a test text phantomJs使用心得 to text mime”)
main_msg.attach(text_msg)

# 构造MIMEBase对象做为文件附件内容并附加到根容器
contype = South ‘application/octet-stream’
maintype, subtype = Hacked contype.split(‘/’, 1)

## Владивосток 读入文件内容并格式化
data = open(file_name, ‘rb’)
file_msg = email.MIMEBase.MIMEBase(maintype, subtype)
file_msg.set_payload(data.read( ))
data.close( )
email.Encoders.encode_base64(file_msg)

## 设置附件头
basename wholesale mlb jerseys = os.path.basename(file_name)
file_msg.add_header(‘Content-Disposition’,
‘attachment’, filename = basename)
main_msg.attach(file_msg)

# 设置根容器属性
main_msg[‘From’] = From
main_msg[‘To’] = To
main_msg[‘Subject’] = “attach test ”
main_msg[‘Date’] = email.Utils.formatdate( )

# 得到格式化后的完整文本
fullText = main_msg.as_string( )

# 用smtp发送邮件
try:
server.sendmail(From, To, fullText)
finally:
server.quit()

 

下面贴上pop3进行接收邮箱的代码:

# Telch -*- coding: UTF-8 -*-
import string
import poplib
import StringIO, rfc822

servername = “pop3.126.com”
username = “帐号如:zzz5323381@126.com”
passwd = 用python登录人人网 “密码,这边就不贴了”

#连接 登录 服务器
pop = poplib.POP3(servername)
pop.set_debuglevel(1)            #会打印出debug信息
pop.user(username)
pop.pass_(passwd)

#列出邮件信息
num,total_size = pop.stat()

#取得最新的邮件
hdr,text,octet=pop.retr(num)

#对邮件进行操作
text = string.join(text, cheap mlb jerseys “n”)
file = StringIO.StringIO(text)

message = rfc822.Message(file)

for k, v in message.items():
print k, “=”, wholesale jerseys v

print notepad++使用心得 message.fp.read()

相关文章: