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('<html><body><h1 id="Hello">Hello</h1>' +2 '<p>send by <a href="http://www.python.org">Python</a>...</p>' +3 '</body></html>', 'html', 'utf-8')
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['From'] = formataddr(["管理员",'ylemail2012@sina.cn'])13 msg['To'] = formataddr(["Saneri",'349622541@qq.com'])14 msg['Subject'] = "Zabbix报警系统!"15 msg.attach(MIMEText(message, 'plain', 'utf-8'))16 17 #---这是附件部分---18 # 构造附件1,文本类型附件19 att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')20 att1["Content-Type"] = 'application/octet-stream'21 # 这里的filename可以任意写,写什么名字,邮件中显示什么名字22 att1["Content-Disposition"] = 'attachment; filename="test.txt"'23 msg.attach(att1)24 25 # 构造附件2,jpg类型附件26 from email.mime.application import MIMEApplication27 att2 = MIMEApplication(open('001.jpg','rb').read())28 att2.add_header('Content-Disposition', 'attachment', filename="001.jpg")29 msg.attach(att2)30 #构造附件3,pdf类型附件31 att3 = MIMEApplication(open('test.pdf','rb').read())32 att3.add_header('Content-Disposition', 'attachment', filename="test.pdf")33 msg.attach(att3)34 #构造附件4,xlsx类型附件35 att4 = MIMEApplication(open('test.xlsx','rb').read())36 att4.add_header('Content-Disposition', 'attachment', filename="test.xlsx")37 msg.attach(att4)38 #构造附件5,mp3类型附件39 att5 = MIMEApplication(open('test.mp3','rb').read())40 att5.add_header('Content-Disposition', 'attachment', 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('ylemail2012@sina.cn', ['349622541@qq.com',], msg.as_string())51 print u"邮件发送成功!"52 server.quit()53 except smtplib.SMTPException:54 print u"Error: 无法发送邮件"55 if name == 'main':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['From'] = formataddr(["管理员",'ylemail2012@sina.cn'])13 msg['To'] = formataddr(["Saneri",'349622541@qq.com'])14 msg['Subject'] = "Zabbix报警系统!"15 msg.attach(MIMEText('<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!','html','utf-8'))16 17 fp = open('001.jpg', 'rb')18 msgImage = MIMEImage(fp.read())19 fp.close()20 msgImage.add_header('Content-ID', '<image1>')21 msg.attach(msgImage)22 try:23 server = smtplib.SMTP("smtp.sina.com", 25)24 server.login("ylemail2012@sina.cn","password")25 server.sendmail('ylemail2012@sina.cn', ['349622541@qq.com',], msg.as_string())26 print u"邮件发送成功!"27 server.quit()28 except smtplib.SMTPException:29 print u"Error: 无法发送邮件"30 31 if name == 'main':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('alternative')2 msg['From'] = ...3 msg['To'] = ...4 msg['Subject'] = ...5 6 msg.attach(MIMEText('hello', 'plain', 'utf-8'))7 msg.attach(MIMEText('<html><body><h1 id="Hello">Hello</h1></body></html>', 'html', 'utf-8'))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
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!

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
