search
HomeBackend DevelopmentPython TutorialDetailed explanation of Python SMTP mail module

SMTP is a protocol for sending emails. Python has built-in support for SMTP and can send plain text emails, HTML emails and emails with attachments.

Python supports SMTP with two modules: smtplib and email. Email is responsible for constructing emails, and smtplib is responsible for sending emails.

Example:

1. Use Python to send emails in plain text format and html format.

 email.mime.text  
  email.utils 
 msg = MIMEText(message, , ) 
   msg[] = formataddr([,])          
   msg[] = formataddr([,])               
   msg[] =                              
   server = smtplib.SMTP(, 25                                    
   server.login(,                  
   server.sendmail(, [          
   u                
   u   ==      cpu = 100    
  disk = 500     mem = 50     
  i  range(1         
  cpu > 90            
 alert = u           
 disk > 90             
 alert = u          
 mem > 80            
  alert = u            
  email(alert)
#Python发送HTML格式的邮件与发送纯文本消息的邮件不同之处就是将MIMEText中_subtype设置为html
1  msg = MIMEText(&#39;<html><body><h1 id="Hello">Hello</h1>&#39; +2     
&#39;<p>send by <a href="http://www.python.org">Python</a>...</p>&#39; +3     
&#39;</body></html>&#39;, &#39;html&#39;, &#39;utf-8&#39;)

2.Python to send emails with attachments.

To send an email with an attachment, you must first create a MIMEMultipart() instance, then construct the attachment. If there are multiple attachments, they can be constructed in sequence, and finally send using smtplib.smtp.

 1 #!/usr/bin/env python 2 #coding:utf-8 3  4 import smtplib 5 from email.mime.text import MIMEText 6 from email.utils import formataddr 7 from email.mime.multipart import MIMEMultipart 8  9 def email(message):10 11     msg = MIMEMultipart()12     msg[&#39;From&#39;] = formataddr(["管理员",&#39;ylemail2012@sina.cn&#39;])13     msg[&#39;To&#39;] = formataddr(["Saneri",&#39;349622541@qq.com&#39;])14     msg[&#39;Subject&#39;] = "Zabbix报警系统!"15     msg.attach(MIMEText(message, &#39;plain&#39;, &#39;utf-8&#39;))16 17     #---这是附件部分---18     # 构造附件1,文本类型附件19     att1 = MIMEText(open(&#39;test.txt&#39;, &#39;rb&#39;).read(), &#39;base64&#39;, &#39;utf-8&#39;)20     att1["Content-Type"] = &#39;application/octet-stream&#39;21     # 这里的filename可以任意写,写什么名字,邮件中显示什么名字22     att1["Content-Disposition"] = &#39;attachment; filename="test.txt"&#39;23     msg.attach(att1)24 25     # 构造附件2,jpg类型附件26     from email.mime.application import MIMEApplication27     att2 = MIMEApplication(open(&#39;001.jpg&#39;,&#39;rb&#39;).read())28     att2.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename="001.jpg")29     msg.attach(att2)30     #构造附件3,pdf类型附件31     att3 = MIMEApplication(open(&#39;test.pdf&#39;,&#39;rb&#39;).read())32     att3.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename="test.pdf")33     msg.attach(att3)34     #构造附件4,xlsx类型附件35     att4 = MIMEApplication(open(&#39;test.xlsx&#39;,&#39;rb&#39;).read())36     att4.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename="test.xlsx")37     msg.attach(att4)38     #构造附件5,mp3类型附件39     att5 = MIMEApplication(open(&#39;test.mp3&#39;,&#39;rb&#39;).read())40     att5.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename="test.mp3")41     msg.attach(att5)42 43     try:44         server = smtplib.SMTP("smtp.sina.com", 25)45         #set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息46         #server.set_debuglevel(1)47         #login()方法用来登录SMTP服务器48         server.login("ylemail2012@sina.cn","password")49         #sendmail()方法就是发邮件,由于可以一次发给多个人,所以传入一个list,邮件正文是一个str,as_string()把MIMEText对象变成str50         server.sendmail(&#39;ylemail2012@sina.cn&#39;, [&#39;349622541@qq.com&#39;,], msg.as_string())51         print u"邮件发送成功!"52         server.quit()53     except smtplib.SMTPException:54         print u"Error: 无法发送邮件"55 if name == &#39;main&#39;:56     cpu = 10057     disk = 50058     mem = 5059     for i in range(1):60         if cpu > 90:61             alert = u"CPU出问题!"62             email(alert)63         if disk > 90:64             alert = u"硬盘出问题!"65             email(alert)66         if mem > 80:67             alert = u"内存出问题!"68             email(alert)

3.Add pictures in HTML text

In the HTML text of the email, it is invalid for general email service providers to add external links. Examples of correctly adding breakthroughs are as follows Display:

 1 #!/usr/bin/env python 2 #coding:utf-8 3  4 import smtplib 5 from email.mime.multipart import MIMEMultipart 6 from email.mime.text import MIMEText 7 from email.mime.image import MIMEImage 8 from email.utils import formataddr 9 10 def email():11     msg = MIMEMultipart()12     msg[&#39;From&#39;] = formataddr(["管理员",&#39;ylemail2012@sina.cn&#39;])13     msg[&#39;To&#39;] = formataddr(["Saneri",&#39;349622541@qq.com&#39;])14     msg[&#39;Subject&#39;] = "Zabbix报警系统!"15     msg.attach(MIMEText(&#39;<b>Some <i>HTML</i> text</b> and an image.<br><img  src="/static/imghwm/default1.png"  data-src="cid:image1"  class="lazy"   alt="Detailed explanation of Python SMTP mail module" ><br>good!&#39;,&#39;html&#39;,&#39;utf-8&#39;))16 17     fp = open(&#39;001.jpg&#39;, &#39;rb&#39;)18     msgImage = MIMEImage(fp.read())19     fp.close()20     msgImage.add_header(&#39;Content-ID&#39;, &#39;<image1>&#39;)21     msg.attach(msgImage)22     try:23         server = smtplib.SMTP("smtp.sina.com", 25)24         server.login("ylemail2012@sina.cn","password")25         server.sendmail(&#39;ylemail2012@sina.cn&#39;, [&#39;349622541@qq.com&#39;,], msg.as_string())26         print u"邮件发送成功!"27         server.quit()28     except smtplib.SMTPException:29         print u"Error: 无法发送邮件"30 31 if name == &#39;main&#39;:32     email()

4. Supports both HTML and Plain formats

If we send an HTML email, the recipient can browse the email content normally through a browser or software such as Outlook, but , what if the device used by the recipient is too old and cannot view HTML emails?

The method is to attach a plain text while sending HTML. If the recipient cannot view the email in HTML format, it can automatically downgrade to view the plain text email.

Use MIMEMultipart to combine HTML and Plain. Please note that the specified subtype is alternative:

1 msg = MIMEMultipart(&#39;alternative&#39;)2 msg[&#39;From&#39;] = ...3 msg[&#39;To&#39;] = ...4 msg[&#39;Subject&#39;] = ...5 6 msg.attach(MIMEText(&#39;hello&#39;, &#39;plain&#39;, &#39;utf-8&#39;))7 msg.attach(MIMEText(&#39;<html><body><h1 id="Hello">Hello</h1></body></html>&#39;, &#39;html&#39;, &#39;utf-8&#39;))8 # 正常发送msg对象...

[Related recommendations]

1. Detailed introduction to the example of using Python to send emails using SMTP

2. Summary of the code for using Python to send emails using SMTP

3 . c#Call qq mailbox smtp to send email modified version code

4. Python uses SMTP to send email

5. php smtp send Email

6. Share the example of using Python to implement SMTP to send emails with pictures and texts

7. The python smtplib module uses the python smtplib module to send SSL/TLS secure emails.

The above is the detailed content of Detailed explanation of Python SMTP mail module. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

How do you debug shebang-related issues?How do you debug shebang-related issues?Apr 30, 2025 am 12:17 AM

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

How do you remove elements from a Python array?How do you remove elements from a Python array?Apr 30, 2025 am 12:16 AM

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

What data types can be stored in a Python list?What data types can be stored in a Python list?Apr 30, 2025 am 12:07 AM

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

What are some common operations that can be performed on Python lists?What are some common operations that can be performed on Python lists?Apr 30, 2025 am 12:01 AM

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor