A tutorial that Python uses poplib modules and Smtplib modules to send and receive e-mail _python

Source: Internet
Author: User
Tags auth base64 starttls all mail ssl connection in python


poplib module receives mail
the Poplib module of Python is used to collect mail from POP3, or it is the first step in processing messages. The
POP3 protocol is not complex, it is also used in a question-and-answer way, you send a command to the server, the server will inevitably reply to a message. The POP3 command code is as follows:


Command Poplib method Parameter status description
-----------------------------------------------------------------------------------------   ------User user username to recognize the username
, this command, if successful with the pass command below, will result in a state transition
pass_ Password approved user password
APOP APOP Name,digest recognition Digest is MD5 message digest
------------------------------------------------------------------------------ -----------------
STAT STAT None processing requests the server to send back statistics about mailboxes, such as total number of messages and total bytes
UIDL UIDL [msg#] processes the unique identifier of the returned message, POP3 session Each identifier will be the only
list [msg#] processed to return the number of messages and the size of each message
RETR RETR [msg#]  handles the return of all text for the message identified by the parameter
DELE del   The E [msg#]  processing server marks the message identified by the parameter as deleted, and the Quit command performs
RSET RSET the None  processing server resets all messages marked for deletion to undo the dele command
top The top [msg#] processing server returns the first n rows of the message identified by the parameter, and n must be a positive integer
NOOP NOOP the None processing server returns a positive response
-------------------------- --------------------------------------------------------------------
QUIT QUIT  None Update





Python's poplib also provides a corresponding method for these commands, which are already marked in the second column. The process of receiving mail is generally:
1. Connect POP3 server (poplib. POP3.__INIT__)
2. Send user name and password for verification (poplib. Pop3.user Poplib. Pop3.pass_)
3. Get the letter information in the mailbox (Poplib. Pop3.stat)
4. Receive mail (poplib. POP3.RETR)
5. Delete message (poplib. Pop3.dele)
6. Exit (Poplib. Pop3.quit)
Note that the above I wrote in parentheses is the method used to do this, in the actual code can not write that, should be to create poplib. POP3 object, and then call the method of this object. Like what:


Poplib. Pop3.quit 


Should be understood as


A = Poplib. POP3 (host)
A.quit ()


Let's look at the actual code:


#-*-encoding:gb2312-*-
import OS, sys, string
import poplib

# POP3 server address
host = "pop3.163.com"
# User Name
username = "xxxxxx@163.com"
# password
password = "xxxxxxx"
# Create a POP3 object that is actually connected to the server at this time
pp = poplib . POP3 (host)
# set debug mode, you can see the interaction information with the server
pp.set_debuglevel (1)
# Send user name
Pp.user (username) to the server
# Send a password to the server
pp.pass_ (password)
# Get the message on the server, return is a list, the first item is a total of more than one message, the second is the total number of bytes
ret = Pp.stat ()
Print RET
# requires the head of all letters to be removed, and the letter ID starts at 1.
for I in range (1, ret[0]+1):
  # Take out the head of the letter. Note: The number of rows specified in top is based on the header of the letter, which means that when you take 0 lines,
  # is actually returning the header information, and taking 1 rows is actually going to return the header information and then 1 more lines.
  mlist = pp.top (i, 0)
  print ' line: ', Len (mlist[1])
# lists mail messages on the server, which output IDs and sizes for each message. Unlike the stat output is the total statistic
ret = pp.list ()
print ret
# takes the first message complete information, in the return value, is stored by rows in the list of down[1]. DOWN[0] is the state information that is returned down
= PP.RETR (1)
print ' lines: ', Len (down)
# output message for line in
down[1]:
  Print Line
# exit
pp.quit ()


In some places, there is a security message that says, in fact, SSL encryption is done on the POP3. Like this, poplib can handle, but not with POP3 this class, but with Pop3_ssl, their methods are the same. Therefore, SSL is supported in the above code, replacing the behavior of creating a POP3 object:


pp = Poplib. Pop3_ssl (host)


Smtplib: Send ssl/tls secure messages in Python
Python's smtplib provides a convenient way to send e-mail. It is a simple encapsulation of the SMTP protocol.
The basic commands for the SMTP protocol include:


    • HELO identify the user identity to the server
    • Mail initiate message transfer mail from:
    • RCPT identifies a single recipient of the message; often after the mail command, there can be multiple RCPT to:
    • Data after a single or multiple RCPT command indicates that all message recipients have identified and initialized the data transfer to. End
    • VRFY is used to verify that the specified user/mailbox exists or that the server often prohibits this command for security reasons
    • EXPN Verify that a given mailbox list exists, and that the expanded mailbox list is often disabled
    • Help query server What commands are supported
    • NOOP no action, server should respond OK
    • QUIT End Session
    • RSET reset session, current transfer canceled
    • Mail from specify Sender address
    • RCPT to specified recipient address


General SMTP session There are two ways, one is direct mail delivery, that is, for example, you want to send e-mail to zzz@163.com, then directly connected to the 163.com mail server, the letter to zzz@163.com; The other is the verification of the post, its process is, for example, you want to send e-mail to zzz@163.com, you are not directly to 163.com, but through their own in Sina.com another mailbox to send. This will be connected to the Sina.com SMTP server, and then certified, and then sent to the 163.com letter to the Sina.com, Sina.com can help you deliver the letter to 163.com.



The first method of command flow is basically this:
1. Helo
2. Mail from
3. RCPT TO
4. Data
5. Quit
But the first way to send a general limit, that is RCPT to specify the recipient of this message must exist on this server, otherwise it will not receive. First look at the code:


#-*-encoding: gb2312-*-
import os, sys, string
import smtplib

# Mail server address
mailserver = "smtp.163.com"
# smtp mail from address during the session
from_addr = "asfgysg@zxsdf.com"
# smtp rcpt to address during the session
to_addr = "zhaoweikid@163.com"
# Letter content
msg = "test mail"

svr = smtplib.SMTP (mailserver)
# Set to debug mode, that is, there will be output information during the session
svr.set_debuglevel (1)
# helo command, the docmd method includes obtaining the information returned by the opposite server
svr.docmd ("HELO server")
# mail from, send mail sender
svr.docmd ("MAIL FROM: <% s>"% from_addr)
# rcpt to, mail recipient
svr.docmd ("RCPT TO: <% s>"% to_addr)
# data command to start sending data
svr.docmd ("DATA")
# Send body data
svr.send (msg)
# For example,. Is used to mark the end of the body sending, which is sent using send, so you need to use getreply to get the return information
svr.send (".")
svr.getreply ()
# Send end, exit
svr.quit ()


    Note that the 163.com is anti-spam, and that the way it is posted is not necessarily detected by the anti-spam system. Therefore, it is generally not recommended for individuals to send.
    The second one is a bit different:
      1.ehlo
      2. Auth Login
      3.mail from
      4.rcpt to
       5.data
      6.quit
    In contrast to the first, there is a more authentication process, is auth login this process.


 #-*-encoding:gb2312-*-import OS, sys, string import smtplib import Base64 # mail server address m  Ailserver = "Smtp.163.com" # Mail user name username = "xxxxxx@163.com" # Password Password = "xxxxxxx" # Mail from address during SMTP session FROM_ADDR = "Xxxxxx@163.com" # SMTP Session RCPT to address to_addr = "yyyyyy@163.com" # Letter Content msg = "My Test mail" SVR = smtplib. SMTP (mailserver) # is set to debug mode, that is, there will be output information Svr.set_debuglevel (1) # EHLO command during session, DoCmd method includes obtaining the opposite server return information Svr.docmd ("EHLO server # Auth Login Command svr.docmd ("Auth login") # Send user name, base64 encoded, sent with send, so use getreply to get return information Svr.send (base64.encodestring
(username)) Svr.getreply () # Send password svr.send (base64.encodestring (password)) svr.getreply () # Mail from, sent by sender Svr.docmd ("Mail from: & Lt;%s> "% from_addr) # RCPT to, Mail Recipient Svr.docmd (" RCPT TO: <%s> "% to_addr) # Data command, start sending data svr.docmd (" Data ") # Send Body Data Svr.send (msg) # for example. Mark Svr.send (".") svr.getreply () # Sent as body text end, Exit Svr.quit () #-*-encoding: gb2312-*-
import os, sys, string
import smtplib
import base64

# Mail server address
mailserver = "smtp.163.com"
# Email username
username = "xxxxxx@163.com"
# Password
password = "xxxxxxx"
# smtp mail from address during the session
from_addr = "xxxxxx@163.com"
# smtp rcpt to address during the session
to_addr = "yyyyyy@163.com"
# Letter content
msg = "my test mail"

svr = smtplib.SMTP (mailserver)
# Set to debug mode, that is, there will be output information during the session
svr.set_debuglevel (1)
# ehlo command, the docmd method includes obtaining information returned by the opposite server
svr.docmd ("EHLO server")
# auth login command
svr.docmd ("AUTH LOGIN")
# Send username, which is base64 encoded and sent using send, so getreply is used to get the returned information
svr.send (base64.encodestring (username))
svr.getreply ()
# Send password
svr.send (base64.encodestring (password))
svr.getreply ()
# mail from, send mail sender
svr.docmd ("MAIL FROM: <% s>"% from_addr)
# rcpt to, mail recipient
svr.docmd ("RCPT TO: <% s>"% to_addr)
# data command to start sending data
svr.docmd ("DATA")
# Send body data
svr.send (msg)
# E.g.. As the end of the body
svr.send (".")
svr.getreply ()
# Send end, exit
svr.quit ()


&NBSP;&NBSP;&NBSP;&NBSP
    said above is the most common situation, but can not be ignored is now a lot of corporate mail is to support secure mail, that is, sent through the SSL mail, how to send this? SMTP has two options for SSL-secured mail, one that is dedicated to opening a 465 port to receive SSL mail, and the other is to add a STARTTLS command to the standard 25 port SMTP.
    See the first way to do this:


#-*-encoding: gb2312-*-
import os, sys, string, socket
import smtplib


class SMTP_SSL (smtplib.SMTP):
  def __init __ (self, host = '', port = 465, local_hostname = None, key = None, cert = None):
    self.cert = cert
    self.key = key
    smtplib.SMTP .__ init __ (self, host, port, local_hostname)
    
  def connect (self, host = 'localhost', port = 465):
    if not port and (host.find (':') == host.rfind (':')):
      i = host.rfind (':')
      if i> = 0:
        host, port = host [: i], host [i + 1:]
        try: port = int (port)
        except ValueError:
          raise socket.error, "nonnumeric port"
    if not port: port = 654
    if self.debuglevel> 0: print >> stderr, 'connect:', (host, port)
    msg = "getaddrinfo returns an empty list"
    self.sock = None
    for res in socket.getaddrinfo (host, port, 0, socket.SOCK_STREAM):
      af, socktype, proto, canonname, sa = res
      try:
        self.sock = socket.socket (af, socktype, proto)
        if self.debuglevel> 0: print >> stderr, 'connect:', (host, port)
        self.sock.connect (sa)
        # Newly created ssl connection
        sslobj = socket.ssl (self.sock, self.key, self.cert)
      except socket.error, msg:
        if self.debuglevel> 0:
          print >> stderr, 'connect fail:', (host, port)
        if self.sock:
          self.sock.close ()
        self.sock = None
        continue
      break
    if not self.sock:
      raise socket.error, msg

    # Set ssl
    self.sock = smtplib.SSLFakeSocket (self.sock, sslobj)
    self.file = smtplib.SSLFakeFile (sslobj);

    (code, msg) = self.getreply ()
    if self.debuglevel> 0: print >> stderr, "connect:", msg
    return (code, msg)
    
if __name__ == '__main__':
  smtp = SMTP_SSL ('192.168.2.10')
  smtp.set_debuglevel (1)
  smtp.sendmail ("zzz@xxx.com", "zhaowei@zhaowei.com", "xxxxxxxxxxxxxxxxx")
  smtp.quit ()


&NBSP;&NBSP;&NBSP;&NBSP
    Here I am from the original smtplib. SMTP derives a new Smtp_ssl class that specializes in processing SSL connections. The 192.168.2.10 I tested here is my own test server.
    The second is the newly added STARTTLS command, which is very simple, Smtplib has this method, called Smtplib.starttls (). Of course, not all mail systems support secure mail, this needs to be confirmed from the EHLO return value, if there is STARTTLS, to support. As opposed to the second way to send a regular message, you just need to add a new line of code:


#-*-encoding: gb2312-*-
import os, sys, string
import smtplib
import base64

# Mail server address
mailserver = "smtp.163.com"
# Email username
username = "xxxxxx@163.com"
# Password
password = "xxxxxxx"
# smtp mail from address during the session
from_addr = "xxxxxx@163.com"
# smtp rcpt to address during the session
to_addr = "yyyyyy@163.com"
# Letter content
msg = "my test mail"

svr = smtplib.SMTP (mailserver)
# Set to debug mode, that is, there will be output information during the session
svr.set_debuglevel (1)
# ehlo command, the docmd method includes obtaining the information returned by the opposite server. If secure mail is supported, there will be a starttls prompt in the return value.
svr.docmd ("EHLO server")
svr.starttls () # <------ This line is the new code that supports secure mail!
# auth login command
svr.docmd ("AUTH LOGIN")
# Send username, which is base64 encoded and sent using send, so getreply is used to get the returned information
svr.send (base64.encodestring (username))
svr.getreply ()
# Send password
svr.send (base64.encodestring (password))
svr.getreply ()
# mail from, send mail sender
svr.docmd ("MAIL FROM: <% s>"% from_addr)
# rcpt to, mail recipient
svr.docmd ("RCPT TO: <% s>"% to_addr)
# data command to start sending data
svr.docmd ("DATA")
# Send body data
svr.send (msg)
# E.g.. As the end of the body
svr.send (".")
svr.getreply ()
# Send end, exit
svr.quit () 


Note: The above code for convenience I did not judge the return value, strictly speaking, should be judged by the return of the Code, in the SMTP protocol, only the return code is 2XX or 3xx to continue the next step, return 4xx or 5xx, is an error.


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.