Send and receive emails using python

高洛峰
Release: 2016-10-18 13:59:25
Original
1213 people have browsed it

Sending emails is what everyone uses most in their work. Today let’s take a look at how to use python to send and receive emails.

Python mainly uses the poplib and smtplib modules to implement the function of sending and receiving emails.

poplib is used to receive emails, while smtplib is responsible for sending emails.

The code is as follows:

#! /usr/bin/env python
#coding=utf-8
import sys 
import time 
import poplib 
import smtplib 
#邮件发送函数
def send_mail(): 
     try: 
        handle = smtplib.SMTP('smtp.126.com',25) 
        handle.login('XXXX@126.com','**********') 
        msg = 'To: XXXX@qq.com\r\nFrom:XXXX@126.com\r\nSubject:hello\r\n'
        handle.sendmail('XXXX@126.com','XXXX@qq.com',msg) 
        handle.close() 
        return 1
    except: 
        return 0
#邮件接收函数
def accpet_mail(): 
    try: 
        p=poplib.POP3('pop.126.com') 
        p.user('pythontab@126.com') 
        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()
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!