Python smtplib module sends SSL/TLS secure message instances

Source: Internet
Author: User
Tags starttls all mail ssl connection
Python's Smtplib provides a convenient way to send e-mails. It provides a simple encapsulation of the SMTP protocol.

Basic commands for the SMTP protocol include:

HELO Identifying user identities to the server
Mail initiates message transfer mail from:
RCPT identifies a single recipient of a message; often behind the mail command, there can be multiple RCPT to:
Data after single or multiple RCPT commands, indicates that all mail recipients have been identified and initialized with the data transfer to. End
The VRFY is used to verify that the specified user/mailbox exists, and the server often prohibits this command for security reasons
EXPN verifies that a given list of mailboxes exists, expands the list of mailboxes, and is often disabled
What commands are supported by the Help query server
NOOP no action, server should respond OK
QUIT End Session
RSET Reset session, the current transfer is 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 after the letter, the process is, for example, you want to send e-mail to zzz@163.com, you do not directly to the 163.com, but through their own in Sina.com another mailbox to send. This will first connect the Sina.com SMTP server, and then authentication, and then send to the 163.com letter to Sina.com, Sina.com will help you deliver the letter to 163.com.

The first way of the command flow is basically this:
1. Helo
2. Mail from
3. RCPT TO
4. Data
5. Quit

However, the first type of transmission is generally limited, that is, RCPT to the recipient of the message must exist on this server, otherwise it will not be received. First look at the code:

The code is as follows:

#-*-encoding:gb2312-*-import os, sys, stringimport smtplib# mail server address mailserver = "Smtp.163.com" # SMTP session during mail from address fr OM_ADDR = "Asfgysg@zxsdf.com" # SMTP session during the RCPT to address to_addr = "zhaoweikid@163.com" # Letter Content msg = "Test mail" SVR = smtplib. SMTP (mailserver) # is set to debug mode, that is, there will be output information during the session svr.set_debuglevel (1) # HELO command, DoCmd method includes getting the other server return information Svr.docmd ("HELO server ") # Mail from, send mail sender svr.docmd (" Mail from:

Note that 163.com is anti-spam features, the above-mentioned method of delivery of e-mails may not be detected by the anti-spam system. So it is generally not recommended for individuals to send such.

The second kind is a little different:

1.ehlo
2.auth Login
3.mail from
4.RCPT to
5.data
6.quit

Compared to the first, a more authentication process, that is, auth login this process.

The code is as follows:

#-*-encoding:gb2312-*-import os, sys, stringimport smtplibimport base64# mail server address mailserver = "Smtp.163.com" # Mail user name Usern Ame = "xxxxxx@163.com" # Password Password = "xxxxxxx" # SMTP Session during the mail from address from_addr = "xxxxxx@163.com" # during 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 during the session svr.set_debuglevel (1) # EHLO command, DoCmd method includes getting the other 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 a password svr.send (base64.encodestring (password)) svr.getreply () # Mail from, send sender Svr.docmd ("Mail from:


Above said is the most common situation, but can not be ignored is now a lot of enterprise mail is to support secure mail, is sent through SSL mail, this How to send it? SMTP support for SSL secure Mail has two scenarios, an old one is dedicated to open a 465 port to receive SSL mail, another update is to add a STARTTLS command on standard 25 port SMTP to support.

Look at the first way to do it:

The code is as follows:

#-*-encoding:gb2312-*-import os, sys, string, Socketimport smtplibclass 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 PO RT and (Host.find (': ') = = Host.rfind (': ')): i = Host.rfind (': ') if I >= 0:host, p  ORT = 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, ' Co Nnect: ', (host, port) msg = "Getaddrinfo Returns an empty list" Self.sock = None for res in socket.ge Taddrinfo (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) # New additions to create SSL connection Sslobj = Socket.ssl (Self.sock, Self.key, sel F.cert) except Socket.error, msg:if self.debuglevel > 0:print>>st Derr, ' 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 () 

Here I am from the original smtplib. SMTP derives a new Smtp_ssl class that specializes in handling SSL connections. The 192.168.2.10 I'm testing here is my own test server.

The second is the new addition to the STARTTLS command, this is very simple, smtplib there is this method, called Smtplib.starttls (). Of course, not all mail systems support secure mail, this needs to be confirmed from the return value of EHLO, if there is STARTTLS, it is supported. In contrast to the second method of sending a normal message, you only need to add a new line of code:

The code is as follows:

#-*-encoding:gb2312-*-import os, sys, stringimport smtplibimport base64# mail server address mailserver = "Smtp.163.com" # Mail user name Usern Ame = "xxxxxx@163.com" # Password Password = "xxxxxxx" # SMTP Session during the mail from address from_addr = "xxxxxx@163.com" # during 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 during the session svr.set_debuglevel (1) # EHLO command, DoCmd method includes getting the other side of the server return information, if you support secure mail, There will be a STARTTLS hint in the return value Svr.docmd ("EHLO server") Svr.starttls ()  # <------This line is the newly added code that supports secure mail! # Auth Login Command svr.docmd ("Auth login") # sends the user name, is Base64 encoded, sent with send, so use getreply to get the return information Svr.send (base64.encodestring ( username)) svr.getreply () # Send password svr.send (base64.encodestring (password)) svr.getreply () # Mail from, send sender Svr.docmd (" MAIL from:

Note: The above code for convenience I have not judged the return value, strictly speaking, it should be judged the return 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.

"Recommended"

1. Detailed description Python uses SMTP to send mail instances

2. Python code summary for sending mail using SMTP

3. C # call QQ mailbox SMTP send mail modified version code

4. Python sends mail using SMTP

5. PHP smtp Send mail

6. Python SMTP Mail module detailed

7. Share Python to implement SMTP send message graphics instances

  • 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.