A simple implementation of the Python messaging feature

Source: Internet
Author: User
Tags sendmsg
This article mainly teaches you how to realize the Python to send and receive the mail function easily, the knowledge point is used in Python's built-in Poplib and Stmplib module. Have a certain reference value, interested in small partners can refer to, hope to help everyone.

1. Preparatory work

First, we need to have a test mailbox, we use Sina Mailbox, and to do the following settings:

In the top right corner of the Sina email page, find more settings, and then select "Client/pop/imap/smtp" on the Left:

Finally, you can open the service status of the POP3/SMTP service:

2. Poplib Receive mail

First, introduce some of the interfaces for Poplib login mailboxes and download messages:

Self.pophost = ' pop.sina.com ' self.smtphost = ' smtp.sina.com ' self.port = self.username = ' xxxxxx@sina.com ' Self.passwo rd = ' xxxxxx ' self.bossmail = ' xxxxxx@qq.com '

We need to specify a number of constants for specifying the login mailbox and the POP,SMTP server and port. We call Poplib's Pop3_ssl interface to log in to the mailbox.

# Login 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 you log in to a mailbox, it's natural that we need to provide a username and password, as shown in the code above, which is very simple to use.
After the login mailbox is successful, we can use the list method to get mail information for 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 the a message number argument is given are 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, which means that the list method has a default parameter of which, whose default value is None, and when the caller does not give a parameter, the method lists all message information, which is returned in the form [Response, [' Msg_number, Octets ', ...], octets], where response is the response result, Msg_number is the message number, octets is a 8-bit byte unit. Let's take a look at specific examples:
(' +ok ', [' 1 2424 ', ' 2 2422 '], 16)
This is a return result of a call to the list () method. Obviously, this is a tuple, the first value sahib the response result ' +ok ', indicating that the request was successful, the second value is an array, and the message information is stored. For example, ' 1 2424 ' in 1 means that the message is numbered 1.
Let's look at how to download messages using Poplib.

# Get Mail 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 gets the message content interface is the Retr method. It requires a parameter, which is the number of the message to get. The following is the definition of the RETR method:

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

We see the note, we can know that the Retr method can get the entire contents of the specified number of messages, its return form is [response, [' line ', ...], octets], visible, the content of the message is stored in the second element of the returned tuple, which is stored as an array. Let's test how the array is.

As we can see, this array is stored in a form similar to a dict! As a result, we can find any content that is of interest to us accordingly. For example, our sample code is to find the subject of the message and the sender, which can be written as in the code above. Of course, you can also use regular match ~ ~ ~ here is the test result:

Well... You can try it yourself.

3. SMTP Send mail

As with pop, you will need to provide some constants before using SMTP:

Self.mail_box = Smtplib. SMTP (Self.smtphost, Self.port) self.mail_box.login (Self.username, Self.password)

Above is the code that uses the SMTP logon mailbox, similar to pop. Here's the code for sending mail using SMTP, and you'll see how simple and beautiful Python is!

# Send Message 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 Python's code for sending mail with SMTP! It's simple, there's wood! Very convenient to have wood there! Very easy to understand there are wood! Here is the main sendmail this method, the designated sender, receiver and the content of the message can be. And Mimetext can see it as defined below:

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 to 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 would also be set.   "" Mimenonmultipart.__init__ (self, ' text ', _subtype,          **{' charset ': _charset})   Self.set_payload (_text, _ CharSet

Look at the Note ~ ~ ~ This is a way to generate the specified content, specifying the encoded MIME document. By the way, see SendMail Method ~ ~ ~

def sendmail (self, from_addr, To_addrs, MSG, mail_options=[],     rcpt_options=[]): "" "This  command performs an Entire mail transaction.   The arguments is:   -from_addr:the address sending this mail.   -To_addrs  : A List of addresses to send the this mail to. A bare        string would 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... The content of sending messages using SMTP is probably the case.

4. Source code and testing

#-*-Coding:utf-8-*-from email.mime.text import mimetext import poplib Import Smtplib class Mailmanager (object): De F __init__ (self): self.pophost = ' pop.sina.com ' self.smtphost = ' smtp.sina.com ' self.port = Self.username = ' xx   xxxx@sina.com ' Self.password = ' xxxxxx ' self.bossmail = ' xxxxxx@qq.com ' Self.login () self.configmailbox () # Login 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 () # get mail 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 N One 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 () # Send mail 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, M   Sg.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:pri NT Mail mailmanager.sendmsg ()

The above code first logs in to the mailbox, then gets its first message and deletes it, then gets the subject and sender of the message and prints it, and finally sends a successful message to another Bossmail mailbox.

The test results are as follows:

OK, you can copy the above code, play for yourself

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.