Take a look at how to use Python to send and receive mail today, with the basics of Python's built-in Poplib and Stmplib modules.
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 = ' [email Protected] ' Self.password = ' xxxxxx ' self.bossmail = ' [email protected] '
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)
As we see the annotations, we know that the Retr method can get the entire contents of a specified number of messages, which are returned in the form[Response, [' line ', ...], octets], visible, the contents of the message are 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 mimetextimport poplibimport smtplibclass Mailmanager (object): Def __i Nit__ (self): self.pophost = ' pop.sina.com ' self.smtphost = ' smtp.sina.com ' Self.port =-Self . userName = ' [email protected] ' Self.password = ' xxxxxx ' self.bossmail = ' [email protected] ' 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].startswit H (' Subject '): Subject = mail[i][9:] If Mail[i].startswith (' X-sender '): Sender = mail[i][10:] content = {' Subject ': Subject, ' sender ': sender} return content Excep T Exception as E:print str (e) return None def configmailbox (self): TRY:SELF.M Ail_box = Smtplib. SMTP (Self.smtphost, Self.port) self.mail_box.login (self.username, Self.password) print U ' config mail Box success! ' except Exception as e:print U ' config mailbox fail! ' + str (e) Quit () # Send Message def sendmsg (self, mail_body= ' success! '): try:msg = Mimetext (M Ail_body, ' plain ', ' utf-8 ') msg['Subject '] = mail_body msg[' from '] = Self.username self.mail_box.sendmail (self.username, Self.bossmai L, 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 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 ~ ~ ~
Python send and receive mail