Simple implementation of the function of sending and receiving emails in Python

小云云
Release: 2018-05-12 11:16:17
Original
5661 people have browsed it

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'
Copy after login

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()
Copy after login

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')
Copy after login

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
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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)
Copy after login

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.
Copy after login

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()
Copy after login

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!

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