E-mail is the most commonly used in our work. See how to send and receive messages in Python today.
Python implements the send and receive messages feature primarily for Poplib and smtplib modules.
The poplib is used to receive mail, and Smtplib is responsible for sending messages.
The code is as follows:
#! /usr/bin/env python#coding=utf-8import sys import time import poplib import smtplib #邮件发送函数def send_mail (): try: handle = Smtplib. SMTP (' smtp.126.com ', +) 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# message receive function Def accpet_mail (): try: p=poplib. POP3 (' pop.126.com ') p.user (' pythontab@126.com ') p.pass_ (' ********** ') ret = P.stat () #返回一个元组:(number of messages, Message size) #p. RETR (' Mail number ') method returns a tuple: (status information, mail, message size) except poplib.error_proto,e: print "Login failed:", E sys.exit (1) #运行当前文件时, perform sendmail and accpet_mail functions if __name__ = = "__main__": send_mail () accpet_ Mail ()