search
HomeBackend DevelopmentPython TutorialSimple implementation of the function of sending and receiving emails in Python

This article mainly teaches you how to simply implement the function of sending and receiving emails in python. The key points of knowledge are the use of python's built-in poplib and stmplib modules. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

1. Preparation

First of all, we need to have a test email. We use Sina Email and make the following settings:

Find Settings->More Settings in the upper right corner of the Sina Mail homepage, and then select "Client/pop/imap/smtp" on the left:

Finally, turn on the service status of the Pop3/smtp service:

2. poplib receives mail

First , introduce some interfaces for poplib login mailbox and download mail:

self.popHost = 'pop.sina.com' 
self.smtpHost = 'smtp.sina.com' 
self.port = 25 
self.userName = 'xxxxxx@sina.com' 
self.passWord = 'xxxxxx' 
self.bossMail = 'xxxxxx@qq.com'

We need some constants as above to specify the login mailbox and pop, smtp server and port. We call poplib's POP3_SSL interface to log in to the mailbox.

# 登录邮箱 
def login(self): 
 try: 
  self.mailLink = poplib.POP3_SSL(self.popHost) 
  self.mailLink.set_debuglevel(0) 
  self.mailLink.user(self.userName) 
  self.mailLink.pass_(self.passWord) 
  self.mailLink.list() 
  print u'login success!' 
 except Exception as e: 
  print u'login fail! ' + str(e) 
  quit()

When logging in to the mailbox, it is natural that we need to provide a username and password. As shown in the above code, it is very simple to use.
After successfully logging in to the mailbox, we can use the list method to obtain the mail information of the mailbox. We see the definition of the list method:

def list(self, which=None): 
 """Request listing, return result. 
 
 Result without a message number argument is in form 
 ['response', ['mesg_num octets', ...], octets]. 
 
 Result when a message number argument is given is a 
 single response: the "scan listing" for that message. 
 """ 
 if which is not None: 
  return self._shortcmd('LIST %s' % which) 
 return self._longcmd('LIST')

We see the comment of the list method, whose Chinese meaning is that the list method has a default parameter which, and its default value is None when the caller does not give a parameter. , this method will list the information of all emails, and its return form is [response, ['msg_number, octets', ...], octets], where response is the response result, msg_number is the email number, and octets is an 8-bit word section unit. Let's take a look at a specific example:
('+OK ', ['1 2424', '2 2422'], 16)
This is the return result after calling the list() method. Obviously, this is a tuple. The first value sahib responds with '+OK', indicating that the request is successful. The second value is an array that stores the email information. For example, 1 in '1 2424' means that the email number is 1.
Let’s look at how to use poplib to download emails.

# 获取邮件 
def retrMail(self): 
 try: 
  mail_list = self.mailLink.list()[1] 
  if len(mail_list) == 0: 
   return None 
  mail_info = mail_list[0].split(' ') 
  number = mail_info[0] 
  mail = self.mailLink.retr(number)[1] 
  self.mailLink.dele(number) 
 
  subject = u'' 
  sender = u'' 
  for i in range(0, len(mail)): 
   if mail[i].startswith('Subject'): 
    subject = mail[i][9:] 
   if mail[i].startswith('X-Sender'): 
    sender = mail[i][10:] 
  content = {'subject': subject, 'sender': sender} 
  return content 
 except Exception as e: 
  print str(e) 
  return None

poplib’s interface for obtaining email content is the retr method. It requires one parameter, which is the email number to be obtained. The following is the definition of the retr method:

def retr(self, which): 
 """Retrieve whole message number 'which'. 
 
 Result is in form ['response', ['line', ...], octets]. 
 """ 
 return self._longcmd('RETR %s' % which)

We see the comments and we can know that the retr method can obtain the entire content of the email with the specified number, and its return form is [response, ['line', ...] , octets], it can be seen that the content of the email is stored in the second element of the returned tuple, and its storage form is an array. Let's test what this array looks like.

We can see that the storage form of this array is similar to a dict! So, we can find anything we are interested in based on this. For example, if our sample code is to find the subject and sender of the email, it can be written as the above code. Of course, you can also use regular matching~~~ Here are the test results:

Well...you can try it yourself.

3. Smtp sends mail

Like pop, you must provide it with some required constants before using smtp:

self.mail_box = smtplib.SMTP(self.smtpHost, self.port) 
self.mail_box.login(self.userName, self.passWord)

The above is the code for logging in to the mailbox using smtp, which is similar to pop. The code for sending emails using SMTP is given below. You will see how simple and beautiful Python is!

# 发送邮件 
def sendMsg(self, mail_body='Success!'): 
 try: 
  msg = MIMEText(mail_body, 'plain', 'utf-8') 
  msg['Subject'] = mail_body 
  msg['from'] = self.userName 
  self.mail_box.sendmail(self.userName, self.bossMail, msg.as_string()) 
  print u'send mail success!' 
 except Exception as e: 
  print u'send mail fail! ' + str(e)

This is the code for python to use smtp to send emails! It's very simple! Very convenient! Very easy to understand! The main method here is sendmail. Just specify the sender, receiver and email content. There is also MIMEText, which can be defined as follows:

class MIMEText(MIMENonMultipart): 
 """Class for generating text/* type MIME documents.""" 
 
 def __init__(self, _text, _subtype='plain', _charset='us-ascii'): 
  """Create a text/* type MIME document. 
 
  _text is the string for this message object. 
 
  _subtype is the MIME sub content type, defaulting to "plain". 
 
  _charset is the character set parameter added to the Content-Type 
  header. This defaults to "us-ascii". Note that as a side-effect, the 
  Content-Transfer-Encoding header will also be set. 
  """ 
  MIMENonMultipart.__init__(self, 'text', _subtype, 
         **{'charset': _charset}) 
  self.set_payload(_text, _charset)

See the comments~~~ This is just a method to generate a MIME document with specified content and specified encoding. By the way, let’s take a look at the sendmail method~~~

def sendmail(self, from_addr, to_addrs, msg, mail_options=[], 
    rcpt_options=[]): 
 """This command performs an entire mail transaction. 
 
 The arguments are: 
  - from_addr : The address sending this mail. 
  - to_addrs  : A list of addresses to send this mail to. A bare 
       string will be treated as a list with 1 address. 
  - msg   : The message to send. 
  - mail_options : List of ESMTP options (such as 8bitmime) for the 
       mail command. 
  - rcpt_options : List of ESMTP options (such as DSN commands) for 
       all the rcpt commands.

Well...that’s about it for sending emails using smtp.

4. Source code and testing

# -*- coding:utf-8 -*- 
from email.mime.text import MIMEText 
import poplib 
import smtplib 
 
 
class MailManager(object): 
 
 def __init__(self): 
  self.popHost = 'pop.sina.com' 
  self.smtpHost = 'smtp.sina.com' 
  self.port = 25 
  self.userName = 'xxxxxx@sina.com' 
  self.passWord = 'xxxxxx' 
  self.bossMail = 'xxxxxx@qq.com' 
  self.login() 
  self.configMailBox() 
 
 # 登录邮箱 
 def login(self): 
  try: 
   self.mailLink = poplib.POP3_SSL(self.popHost) 
   self.mailLink.set_debuglevel(0) 
   self.mailLink.user(self.userName) 
   self.mailLink.pass_(self.passWord) 
   self.mailLink.list() 
   print u'login success!' 
  except Exception as e: 
   print u'login fail! ' + str(e) 
   quit() 
 
 # 获取邮件 
 def retrMail(self): 
  try: 
   mail_list = self.mailLink.list()[1] 
   if len(mail_list) == 0: 
    return None 
   mail_info = mail_list[0].split(' ') 
   number = mail_info[0] 
   mail = self.mailLink.retr(number)[1] 
   self.mailLink.dele(number) 
 
   subject = u'' 
   sender = u'' 
   for i in range(0, len(mail)): 
    if mail[i].startswith('Subject'): 
     subject = mail[i][9:] 
    if mail[i].startswith('X-Sender'): 
     sender = mail[i][10:] 
   content = {'subject': subject, 'sender': sender} 
   return content 
  except Exception as e: 
   print str(e) 
   return None 
 
 def configMailBox(self): 
  try: 
   self.mail_box = smtplib.SMTP(self.smtpHost, self.port) 
   self.mail_box.login(self.userName, self.passWord) 
   print u'config mailbox success!' 
  except Exception as e: 
   print u'config mailbox fail! ' + str(e) 
   quit() 
 
 # 发送邮件 
 def sendMsg(self, mail_body='Success!'): 
  try: 
   msg = MIMEText(mail_body, 'plain', 'utf-8') 
   msg['Subject'] = mail_body 
   msg['from'] = self.userName 
   self.mail_box.sendmail(self.userName, self.bossMail, msg.as_string()) 
   print u'send mail success!' 
  except Exception as e: 
   print u'send mail fail! ' + str(e) 
 
if __name__ == '__main__': 
 mailManager = MailManager() 
 mail = mailManager.retrMail() 
 if mail != None: 
  print mail 
  mailManager.sendMsg()

The above code first logs in to the mailbox, then gets the first email and deletes it, and then gets the subject of the email and the sender and print it out, and finally send a successful email to another bossMail mailbox.

The test results are as follows:

Okay, you can copy the above code and play with it yourself

Related recommendations:

python to send and receive emails

thinkphp implements 163, QQ mailbox method to send and receive emails_PHP

phpsend and receive emails

The above is the detailed content of Simple implementation of the function of sending and receiving emails in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.