Home Backend Development Python Tutorial How to use the email module smtplib in Python

How to use the email module smtplib in Python

Feb 15, 2017 pm 02:22 PM
python smtplib

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连接
Copy after login

Execute this code, we will receive an email

How to use the email module smtplib in Python

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[&#39;Subject&#39;] = SUBJECT
msg[&#39;FROM&#39;] = FROM
msg[&#39;To&#39;] = TO
try:
  server = smtplib.SMTP()
  server.connect(HOST,&#39;25&#39;)
  server.starttls()
  server.login(&#39;18801457794@139.com&#39;,&#39;123456&#39;)
  server.sendmail(FROM,TO,msg.as_string())
  server.quit()
  print "邮件发送成功"
except Exception,e:
  print "失败:" + str(e)
Copy after login

The result of running the code is as shown in the figure,

How to use the email module smtplib in Python

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,&#39;rb&#39;) #打开文件
  msgImage = MIMEImage(fp.read()) #创建MIMEImage对象,读取图片内容并作为参数
  fp.close() #关闭文件
  msgImage.add_header(&#39;Content-ID&#39;,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(&#39;related&#39;) #创建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[&#39;Subject&#39;] = SUBJECT
msg[&#39;FROM&#39;]=FROM
msg[&#39;To&#39;] = TO
try:
  server = smtplib.SMTP()
  server.connect(HOST,"25")
  server.starttls()
  server.login(&#39;18801457794@139.com&#39;,&#39;123456&#39;)
  server.sendmail(FROM,TO_list,msg.as_string())
  server.quit()
  print "邮件发送成功!"
except Exception,e:
  print "失败:"+ str(e)
Copy after login

The code running effect is as shown in the figure

How to use the email module smtplib in Python

For more related articles on how to use the email module smtplib in python, please pay attention to the PHP Chinese website!

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks 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)

Is the conversion speed fast when converting XML to PDF on mobile phone? Is the conversion speed fast when converting XML to PDF on mobile phone? Apr 02, 2025 pm 10:09 PM

The speed of mobile XML to PDF depends on the following factors: the complexity of XML structure. Mobile hardware configuration conversion method (library, algorithm) code quality optimization methods (select efficient libraries, optimize algorithms, cache data, and utilize multi-threading). Overall, there is no absolute answer and it needs to be optimized according to the specific situation.

How to convert XML files to PDF on your phone? How to convert XML files to PDF on your phone? Apr 02, 2025 pm 10:12 PM

It is impossible to complete XML to PDF conversion directly on your phone with a single application. It is necessary to use cloud services, which can be achieved through two steps: 1. Convert XML to PDF in the cloud, 2. Access or download the converted PDF file on the mobile phone.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Is there a mobile app that can convert XML into PDF? Is there a mobile app that can convert XML into PDF? Apr 02, 2025 pm 09:45 PM

There is no APP that can convert all XML files into PDFs because the XML structure is flexible and diverse. The core of XML to PDF is to convert the data structure into a page layout, which requires parsing XML and generating PDF. Common methods include parsing XML using Python libraries such as ElementTree and generating PDFs using ReportLab library. For complex XML, it may be necessary to use XSLT transformation structures. When optimizing performance, consider using multithreaded or multiprocesses and select the appropriate library.

Recommended XML formatting tool Recommended XML formatting tool Apr 02, 2025 pm 09:03 PM

XML formatting tools can type code according to rules to improve readability and understanding. When selecting a tool, pay attention to customization capabilities, handling of special circumstances, performance and ease of use. Commonly used tool types include online tools, IDE plug-ins, and command-line tools.

How to convert XML to PDF on your phone? How to convert XML to PDF on your phone? Apr 02, 2025 pm 10:18 PM

It is not easy to convert XML to PDF directly on your phone, but it can be achieved with the help of cloud services. It is recommended to use a lightweight mobile app to upload XML files and receive generated PDFs, and convert them with cloud APIs. Cloud APIs use serverless computing services, and choosing the right platform is crucial. Complexity, error handling, security, and optimization strategies need to be considered when handling XML parsing and PDF generation. The entire process requires the front-end app and the back-end API to work together, and it requires some understanding of a variety of technologies.

How to open xml format How to open xml format Apr 02, 2025 pm 09:00 PM

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

How to convert xml into pictures How to convert xml into pictures Apr 03, 2025 am 07:39 AM

XML can be converted to images by using an XSLT converter or image library. XSLT Converter: Use an XSLT processor and stylesheet to convert XML to images. Image Library: Use libraries such as PIL or ImageMagick to create images from XML data, such as drawing shapes and text.

See all articles