Home Backend Development Python Tutorial python smtplib模块发送SSL/TLS安全邮件实例

python smtplib模块发送SSL/TLS安全邮件实例

May 24, 2017 pm 02:28 PM
python smtplib ssl tls

python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。

smtp协议的基本命令包括:

HELO 向服务器标识用户身份
MAIL 初始化邮件传输 mail from:
RCPT 标识单个的邮件接收人;常在MAIL命令后面,可有多个rcpt to:
DATA 在单个或多个RCPT命令后,表示所有的邮件接收人已标识,并初始化数据传输,以.结束
VRFY 用于验证指定的用户/邮箱是否存在;由于安全方面的原因,服务器常禁止此命令
EXPN 验证给定的邮箱列表是否存在,扩充邮箱列表,也常被禁用
HELP 查询服务器支持什么命令
NOOP 无操作,服务器应响应OK
QUIT 结束会话
RSET 重置会话,当前传输被取消
MAIL FROM 指定发送者地址
RCPT TO 指明的接收者地址

一般smtp会话有两种方式,一种是邮件直接投递,就是说,比如你要发邮件給zzz@163.com,那就直接连接163.com的邮件服务器,把信投給zzz@163.com; 另一种是验证过后的发信,它的过程是,比如你要发邮件給zzz@163.com,你不是直接投到163.com,而是通过自己在sina.com的另一个邮箱来发。这样就要先连接sina.com的smtp服务器,然后认证,之后在把要发到163.com的信件投到sina.com上,sina.com会帮你把信投递到163.com。

第一种方式的命令流程基本是这样:
1. helo
2. mail from
3. rcpt to
4. data
5. quit

但是第一种发送方式一般有限制的,就是rcpt to指定的这个邮件接收者必须在这个服务器上存在,否则是不会接收的。 先看看代码:

代码如下:

#-*- encoding: gb2312 -*-import os, sys, stringimport smtplib
# 邮件服务器地址mailserver = "smtp.163.com"# smtp会话过程中的mail from地址from_addr = "asfgysg@zxsdf.com"# smtp会话过程中的rcpt to地址to_addr = "zhaoweikid@163.com"# 信件内容msg = "test mail"
svr = smtplib.SMTP(mailserver)# 设置为调试模式,就是在会话过程中会有输出信息svr.set_debuglevel(1)# helo命令,docmd方法包括了获取对方服务器返回信息svr.docmd("HELO server")# mail from, 发送邮件发送者svr.docmd("MAIL FROM:
Copy after login

注意的是,163.com是有反垃圾邮件功能的,想上面的这种投递邮件的方法不一定能通过反垃圾邮件系统的检测的。所以一般不推荐个人这样发送。

第二种有点不一样:

1.ehlo
2.auth login
3.mail from
4.rcpt to
5.data
6.quit

相对于第一种来说,多了一个认证过程,就是auth login这个过程。

代码如下:

#-*- encoding: gb2312 -*-import os, sys, stringimport smtplibimport base64
# 邮件服务器地址mailserver = "smtp.163.com"# 邮件用户名username = "xxxxxx@163.com"# 密码password = "xxxxxxx"# smtp会话过程中的mail from地址from_addr = "xxxxxx@163.com"# smtp会话过程中的rcpt to地址to_addr = "yyyyyy@163.com"# 信件内容msg = "my test mail"
svr = smtplib.SMTP(mailserver)# 设置为调试模式,就是在会话过程中会有输出信息svr.set_debuglevel(1)# ehlo命令,docmd方法包括了获取对方服务器返回信息svr.docmd("EHLO server")# auth login 命令svr.docmd("AUTH LOGIN")# 发送用户名,是base64编码过的,用send发送的,所以要用getreply获取返回信息svr.send(base64.encodestring(username))svr.getreply()# 发送密码svr.send(base64.encodestring(password))svr.getreply()# mail from, 发送邮件发送者svr.docmd("MAIL FROM:
Copy after login


上面说的是最普通的情况,但是不能忽略的是现在好多企业邮件是支持安全邮件的,就是通过SSL发送的邮件,这个怎么发呢?SMTP对SSL安全邮件的支持有两种方案,一种老的是专门开启一个465端口来接收ssl邮件,另一种更新的做法是在标准的25端口的smtp上增加一个starttls的命令来支持。

看看第一种怎么办:

代码如下:

#-*- encoding: gb2312 -*-import os, sys, string, socketimport 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)                # 新增加的创建ssl连接                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
        # 设置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()
Copy after login

这里我是从原来的smtplib.SMTP派生出了新的SMTP_SSL类,它专门来处理ssl连接。我这里测试的192.168.2.10是我自己的测试服务器.

第二种是新增加了starttls的命令,这个很简单,smtplib里就有这个方法,叫smtplib.starttls()。当然,不是所有的邮件系统都支持安全邮件的,这个需要从ehlo的返回值里来确认,如果里面有starttls,才表示支持。相对于发送普通邮件的第二种方法来说,只需要新增加一行代码就可以了:

代码如下:

#-*- encoding: gb2312 -*-import os, sys, stringimport smtplibimport base64
# 邮件服务器地址mailserver = "smtp.163.com"# 邮件用户名username = "xxxxxx@163.com"# 密码password = "xxxxxxx"# smtp会话过程中的mail from地址from_addr = "xxxxxx@163.com"# smtp会话过程中的rcpt to地址to_addr = "yyyyyy@163.com"# 信件内容msg = "my test mail"
svr = smtplib.SMTP(mailserver)# 设置为调试模式,就是在会话过程中会有输出信息svr.set_debuglevel(1)# ehlo命令,docmd方法包括了获取对方服务器返回信息,如果支持安全邮件,返回值里会有starttls提示svr.docmd("EHLO server")svr.starttls()  # <------ 这行就是新加的支持安全邮件的代码!# auth login 命令svr.docmd("AUTH LOGIN")# 发送用户名,是base64编码过的,用send发送的,所以要用getreply获取返回信息svr.send(base64.encodestring(username))svr.getreply()# 发送密码svr.send(base64.encodestring(password))svr.getreply()# mail from, 发送邮件发送者svr.docmd("MAIL FROM:
Copy after login

注意: 以上的代码为了方便我都没有判断返回值,严格说来,是应该判断一下返回的代码的,在smtp协议中,只有返回代码是2xx或者3xx才能继续下一步,返回4xx或5xx的,都是出错了。

【相关推荐】

1. 详细介绍Python使用SMTP发送邮件实例

2. Python 使用SMTP发送邮件的代码小结

3. c#调用qq邮箱smtp发送邮件修改版代码

4. Python使用SMTP发送邮件

5. php smtp发送邮件

6. Python SMTP邮件模块详解

7. 分享Python实现SMTP发送邮件图文实例

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

How to train PyTorch model on CentOS How to train PyTorch model on CentOS Apr 14, 2025 pm 03:03 PM

Efficient training of PyTorch models on CentOS systems requires steps, and this article will provide detailed guides. 1. Environment preparation: Python and dependency installation: CentOS system usually preinstalls Python, but the version may be older. It is recommended to use yum or dnf to install Python 3 and upgrade pip: sudoyumupdatepython3 (or sudodnfupdatepython3), pip3install--upgradepip. CUDA and cuDNN (GPU acceleration): If you use NVIDIAGPU, you need to install CUDATool

How is the GPU support for PyTorch on CentOS How is the GPU support for PyTorch on CentOS Apr 14, 2025 pm 06:48 PM

Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

How to choose the PyTorch version under CentOS How to choose the PyTorch version under CentOS Apr 14, 2025 pm 02:51 PM

When selecting a PyTorch version under CentOS, the following key factors need to be considered: 1. CUDA version compatibility GPU support: If you have NVIDIA GPU and want to utilize GPU acceleration, you need to choose PyTorch that supports the corresponding CUDA version. You can view the CUDA version supported by running the nvidia-smi command. CPU version: If you don't have a GPU or don't want to use a GPU, you can choose a CPU version of PyTorch. 2. Python version PyTorch

How to operate distributed training of PyTorch on CentOS How to operate distributed training of PyTorch on CentOS Apr 14, 2025 pm 06:36 PM

PyTorch distributed training on CentOS system requires the following steps: PyTorch installation: The premise is that Python and pip are installed in CentOS system. Depending on your CUDA version, get the appropriate installation command from the PyTorch official website. For CPU-only training, you can use the following command: pipinstalltorchtorchvisiontorchaudio If you need GPU support, make sure that the corresponding version of CUDA and cuDNN are installed and use the corresponding PyTorch version for installation. Distributed environment configuration: Distributed training usually requires multiple machines or single-machine multiple GPUs. Place

How to install nginx in centos How to install nginx in centos Apr 14, 2025 pm 08:06 PM

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.

See all articles