发邮件是大家工作中最常用到的。今天来看一下怎么用python来发送和接收邮件。
python实现发送和接收邮件功能主要用到poplib和smtplib模块。
poplib用于接收邮件,而smtplib负责发送邮件。
代码如下:
#! /usr/bin/env python#coding=utf-8import sys import time import poplib import smtplib #邮件发送函数def send_mail(): try: handle = smtplib.SMTP('smtp.126.com',25) handle.login('[email protected]','**********') msg = 'To: [email protected]\r\nFrom:[email protected]\r\nSubject:hello\r\n' handle.sendmail('[email protected]','[email protected]',msg) handle.c<mark style="color:transparent">来4源gaodaimacom搞#代%码*网</mark>lose() return 1 except: return 0#邮件接收函数def accpet_mail(): try: p=poplib.POP3('pop.126.com') p.user('[email protected]') p.pass_('**********') ret = p.stat() #返回一个元组:(邮件数,邮件尺寸) #p.retr('邮件号码')方法返回一个元组:(状态信息,邮件,邮件尺寸) except poplib.error_proto,e: print "Login failed:",e sys.exit(1) #运行当前文件时,执行sendmail和accpet_mail函数if __name__ == "__main__": send_mail() accpet_mail()