How to use the email module smtplib in Python
Smptp class definition: smtplib.SMTP(host[,port[,local_hostname[,,timeout]]]), as the constructor of SMTP, its function is to establish a connection with the smtp server. After the connection is successful, you can send a request to the server Send related requests, such as login, verification, sending, exit, etc. The host parameter is the remote SMTP host address, such as stmp.163.com; port is the connection port, the default is 25; local_hostname is used to send HELO/EHLO instructions at the local FQDN (complete domain name), and timeout is the connection or attempt to connect in the majority seconds timeout, the SMTP class has the following methods:
SMTP.connect([host[,port]]) method, method to connect to the remote SMTP host, host is the remote host address, port is the remote host SMTP port, the default is 25 , or you can directly use the host:port format, for example: SMTP.connect("smtp.163.com","25').
SMTP.login(user,password) method, verification method of remote SMTP host , the parameters are user name and password, such as SMTP.login("18801457794@139.com",'123456').
SMTP.sendmail(from_addr,to_addrs,msg[,mail_options,rcpt_options]) method to implement the mail Send function, the parameters are sender, recipient, and email content, for example: SMTP.sendmail("python@163.com",'404408853@qq.com',body), where the body content is defined as follows:
"""From:python@163.com
To:404408853@qq.com
Subject:test mail
test mail body"""
SMTP.starttls([keyfile[,certfile] ]) method, enable TLS (secure transmission) mode, all SMTP instructions are encrypted transmission, for example, when using gmail's stmp server, you need to enable this to send emails normally
SMTP.quit() method, port smtp server connection
Let’s learn how python sends emails through examples
[root@localhost smtplib]# cat simple1.py #!/usr/bin/env python # -*- coding: utf-8 -*- import smtplib import string HOST = "smtp.139.com" #定义smtp主机 SUBJECT = "test" #定义邮件主题 TO = "404408853@qq.com" #定义邮件收件人 FROM = "18801457794@139.com" #定义邮件发件人 text = "python test mail" #邮件的内容 BODY=string.join(( #组装sendmail方法的邮件主体内容,各段以"\r\n"进行分隔 "From:%s" %FROM, "To:%s" %TO, "Subject:%s"%SUBJECT, "", text ),"\r\n") server = smtplib.SMTP() #创建一个SMTP对象 server.connect(HOST,"25") #通过connect方法连接smtp主机 server.starttls() #启动安全传输模式 server.login("18801457794@139.com","123456") #邮件账户登录校验 server.sendmail(FROM,TO,BODY) #邮件发送 server.quit() #断开smtp连接
Execute this code, we will receive an email
Implementing data report emails in HTML format
Plain text email content can no longer meet our diverse needs. This example introduces email.mime The MIMETex class is used to support emails in HTML format, supporting all HTML elements, including tables, pictures, animations, CSS styles, forms, etc. This example uses HTML tables to customize perfect business traffic reports. The implementation code is as follows:
#!/usr/bin/env python #coding:utf-8 import smtplib from email.mime.text import MIMEText #导入MIMEText类 HOST = "smtp.139.com" SUBJECT = u"官网流量数据报表" TO = "404408853@qq.com" FROM = "18801457794@139.com" msg = MIMEText(""" <table width="800" border="0" cellspacing="0" cellpadding="4"> <tr> <td bgcolor="#CECFAD" height="20" style="font-size:14px">*官网数据<a href="monitor.domain.com">更多</a></td> </tr> <td bgcolor="#EFEBDE" height="100" style="font-size:13px"> 1)日访问量:<font color=read>152433</font>访问次数:23651 页面浏览量:45123 点击数:545122 数据流量:504Mb<br> 2)状态码消息<br> 500:105 404;3264 503;214<br> 3)访客浏览器信息<br> IE:50% firefox:10% chrome:30% other:10%<br> 4)页面信息<br> /index.php 42153<br> /view.php 21451<br> </td> </tr> </table>""","html","utf-8") msg['Subject'] = SUBJECT msg['FROM'] = FROM msg['To'] = TO try: server = smtplib.SMTP() server.connect(HOST,'25') server.starttls() server.login('18801457794@139.com','123456') server.sendmail(FROM,TO,msg.as_string()) server.quit() print "邮件发送成功" except Exception,e: print "失败:" + str(e)
The result of running the code is as shown in the figure,
Example 2: Implementing server performance report email in graphic and text format
When requesting email content containing image data, you need to reference the MIMEImage class. If the email body consists of multiple MIME objects, you need to reference the MIMEMultipart class for encapsulation. This example uses the combination of MIMEText and MIMEImage classes to customize the server performance report email in graphic and text format. The implementation code is as follows
#!/usr/bin/env python #coding: utf-8 import smtplib,string from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage HOST ="smtp.139.com" #定义smtp主机 SUBJECT = "金美美平台系统状态报表" #定义邮件主题 TO = "404408853@qq.com,302803690@qq.com" #定义邮件收件人 FROM = "18801457794@139.com" #定义邮件发件人 TO_list = TO.split(TO) def addimg(src,imgid): #添加图片函数,参数1:图片路径,参数2:图片ID fp = open(src,'rb') #打开文件 msgImage = MIMEImage(fp.read()) #创建MIMEImage对象,读取图片内容并作为参数 fp.close() #关闭文件 msgImage.add_header('Content-ID',imgid) #指定图片文件的Content-ID,<img src="/static/imghw/default1.png" data-src="cid:io" class="lazy" alt="How to use the email module smtplib in Python" >标签src用到 return msgImage #返回msgImage对象 msg = MIMEMultipart('related') #创建MIMEMultipart对象,采用related定义内嵌资源的邮件体 msgtext = MIMEText(""" <table width="600" border="0" cellspacing="0" cellspacing="4"> <tr bgcolor="#CECFAD" height="20" style="font-size:14px"> <td colspan=2>以下是211.157.111.41系统状态图</td> </tr> <tr bgcolor="#EFEBDE" height="100" style="font-size:13px"> <td> <img src="/static/imghw/default1.png" data-src="cid:io" class="lazy" alt="How to use the email module smtplib in Python" ></td><td> <img src="/static/imghw/default1.png" data-src="cid:load" class="lazy" alt="How to use the email module smtplib in Python" ></td> </tr> <tr bgcolor="#EFEBDE" height="100" style="font-size:13px"> <td> <img src="/static/imghw/default1.png" data-src="cid:mem" class="lazy" alt="How to use the email module smtplib in Python" ></td><td> <img src="/static/imghw/default1.png" data-src="cid:disk" class="lazy" alt="How to use the email module smtplib in Python" ></td> </tr> </table>""","html","utf-8") #<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/013/ee183c867153973c3cb90e0d0c7a55cb-2.jpg" class="lazy" alt="How to use the email module smtplib in Python" >标签的src属性是通过Content-ID来引用的 msg.attach(msgtext) #MIMEMultipart对象附加MIMEText的内容 msg.attach(addimg("img/bytes_io.png","io")) #使用MIMEMultipart对象附加MIMEImage的内容 msg.attach(addimg("img/os_load.png","load")) msg.attach(addimg("img/os_mem.png","mem")) msg.attach(addimg("img/os_disk.png","disk")) msg['Subject'] = SUBJECT msg['FROM']=FROM msg['To'] = TO try: server = smtplib.SMTP() server.connect(HOST,"25") server.starttls() server.login('18801457794@139.com','123456') server.sendmail(FROM,TO_list,msg.as_string()) server.quit() print "邮件发送成功!" except Exception,e: print "失败:"+ str(e)
The code running effect is as shown in the figure
For more related articles on how to use the email module smtplib in python, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.
