Table of Contents
4.发送邮件附件:邮件附件是图片
5.发送群邮件:同时发送给多人
Home Web Front-end HTML Tutorial 解读Python发送邮件_html/css_WEB-ITnose

解读Python发送邮件_html/css_WEB-ITnose

Jun 21, 2016 am 09:00 AM

解读Python发送邮件

Python发送邮件需要smtplib和email两个模块。也正是由于我们在实际工作中可以导入这些模块,才使得处理工作中的任务变得更加的简单。今天,就来好好学习一下使用Python发送邮件吧。

SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。

Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。

1.邮件正文是文本的格式

 1 # -*- coding: UTF-8 -*- 2  3 from email.mime.multipart import MIMEMultipart 4 from email.mime.text import MIMEText 5 import smtplib 6 import sys 7 import csv 8 import xlrd 9 from pyExcelerator import *10 import os11 import xlwt12 from xlutils.copy import copy13 import pyExcelerator14 import datetime15 import time16 17 reload(sys)18 sys.setdefaultencoding("utf-8")19 20 mailto_list = [""]  # 邮件接收方的邮件地址21 mail_host = "smtp.exmail.qq.com"    # 邮件传送协议服务器22 mail_user = ""  # 邮件发送方的邮箱账号23 mail_pass = ""  # 邮件发送方的邮箱密码24 25 def send_mail(to_list, sub, content):26     me = "天才白痴梦"+"<"+mail_user+">"27     msg = MIMEText(content, _subtype='plain', _charset='utf-8')28     msg['Subject'] = sub    # 邮件主题29     msg['From'] = me30     msg['To'] = ";".join(to_list)31     try:32         server = smtplib.SMTP()33         server.connect(mail_host)34         server.login(mail_user, mail_pass)35         server.sendmail(me, to_list, msg.as_string())36         server.close()37         return True38     except Exception, e:39         print str(e)40         return False41 42 if __name__ == '__main__':43     sub = "天才白痴梦"44     content = '...'45     if send_mail(mailto_list, sub, content):46         print "发送成功"47     else:48         print "发送失败"
Copy after login

2.邮件正文是表格的格式:由于是表格,所以我们选择HTML来实现表格的功能,邮件上面显示的就是HTML实现的内容了。

 1 # -*- coding: UTF-8 -*- 2  3 from email.mime.multipart import MIMEMultipart 4 from email.mime.text import MIMEText 5 import smtplib 6 import sys 7 import csv 8 import xlrd 9 from pyExcelerator import *10 import os11 import xlwt12 from xlutils.copy import copy13 import pyExcelerator14 import datetime15 import time16 17 reload(sys)18 sys.setdefaultencoding("utf-8")19 20 mailto_list = [""]  # 邮件接收方的邮件地址21 mail_host = "smtp.exmail.qq.com"    # 邮件传送协议服务器22 mail_user = ""  # 邮件发送方的邮箱账号23 mail_pass = ""  # 邮件发送方的邮箱密码24 25 def send_mail(to_list, sub, content):26     me = "天才白痴梦"+"<"+mail_user+">"27     # 和上面的代码不同的就是,这里我们选择的是html 的格式28     msg = MIMEText(content, _subtype='html', _charset='utf-8')29     msg['Subject'] = sub    # 邮件主题30     msg['From'] = me31     msg['To'] = ";".join(to_list)32     try:33         server = smtplib.SMTP()34         server.connect(mail_host)35         server.login(mail_user, mail_pass)36         server.sendmail(me, to_list, msg.as_string())37         server.close()38         return True39     except Exception, e:40         print str(e)41         return False42 43 if __name__ == '__main__':44     sub = "天才白痴梦"45     html = '<html></html>'46     if send_mail(mailto_list, sub, html):47         print "发送成功"48     else:49         print "发送失败"
Copy after login

3.邮件正文是图片的格式:要把图片嵌入到邮件正文中,我们只需按照发送附件的方式,先把邮件作为附件添加进去,然后,在HTML中通过引用src="cid:0"就可以把附件作为图片嵌入了。如果有多个图片,给它们依次编号,然后引用不同的cid:x即可。

 1 def send_mail(to_list, sub, content): 2     me = "天才白痴梦"+"<"+mail_user+">" 3  4     msg = MIMEMultipart() 5     msg['Subject'] = sub    # 邮件主题 6     msg['From'] = me 7     msg['To'] = ";".join(to_list) 8  9     txt = MIMEText("天才白痴梦", _subtype='plain', _charset='utf8')10     msg.attach(txt)11 12     # <b>:黑体  <i>:斜体13     msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<img src="/static/imghw/default1.png"  data-src="cid:image1"  class="lazy"  alt="" />good!', 'html', 'utf-8')14     msg.attach(msgText)15 16     file1 = "F:\\1.jpg"17     image = MIMEImage(open(file1, 'rb').read())18     image.add_header('Content-ID', '<image1>')19     msg.attach(image)20 21     try:22         server = smtplib.SMTP()23         server.connect(mail_host)24         server.login(mail_user, mail_pass)25         server.sendmail(me, to_list, msg.as_string())26         server.close()27         return True28     except Exception, e:29         print str(e)30         return False31 32 if __name__ == '__main__':33     sub = "天才白痴梦"34     html = '<html></html>'35     if send_mail(mailto_list, sub, html):36         print "发送成功"37     else:38         print "发送失败"
Copy after login

4.发送邮件附件:邮件附件是图片

 1 def send_mail(to_list, sub, content): 2     me = "天才白痴梦"+"<"+mail_user+">" 3  4     msg = MIMEMultipart() 5     msg['Subject'] = sub    # 邮件主题 6     msg['From'] = me 7     msg['To'] = ";".join(to_list) 8  9     txt = MIMEText("天才白痴梦", _subtype='plain', _charset='utf8')10     msg.attach(txt)11 12     # # <b>:黑体  <i>:斜体13     # msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<img src="/static/imghw/default1.png"  data-src="cid:image1"  class="lazy"  alt="" />good!', 'html', 'utf-8')14     # msg.attach(msgText)15     #16     # file1 = "F:\\1.jpg"17     # image = MIMEImage(open(file1, 'rb').read())18     # image.add_header('Content-ID', '<image1>')19     # msg.attach(image)20 21     att = MIMEText(open('F:\\1.jpg', 'rb').read(), 'base64', 'utf-8')22     att["Content-Type"] = 'application/octet-stream'23     att["Content-Disposition"] = 'attachment; filename="1.jpg"'24     msg.attach(att)25 26     try:27         server = smtplib.SMTP()28         server.connect(mail_host)29         server.login(mail_user, mail_pass)30         server.sendmail(me, to_list, msg.as_string())31         server.close()32         return True33     except Exception, e:34         print str(e)35         return False
Copy after login

5.发送群邮件:同时发送给多人

1 mailto_list = [""]  # 邮件接收方的邮件地址
Copy after login

上面这一行代码是邮件接收方的邮件地址,如果我们需要给多人发送邮件的话,就只需要把对方的邮件帐号绑在这一个列表里就ok了。

加密SMTP

使用标准的25端口连接SMTP服务器时,使用的是明文传输,发送邮件的整个过程可能会被窃听。要更安全地发送邮件,可以加密SMTP会话,实际上就是先创建SSL安全连接,然后再使用SMTP协议发送邮件。

方法:只需要在创建SMTP对象后,立刻调用starttls()方法,就创建了安全连接。

1 smtp_server = 'smtp.qq.com'2 smtp_port = 25    # 默认端口号为253 server = smtplib.SMTP(smtp_server, smtp_port)4 server.starttls()5 # 剩下的代码和前面的一模一样:6 server.set_debuglevel(1)     # 打印出和SMTP服务器交互的所有信息
Copy after login
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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Is HTML easy to learn for beginners? Is HTML easy to learn for beginners? Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

HTML, CSS, and JavaScript: Essential Tools for Web Developers HTML, CSS, and JavaScript: Essential Tools for Web Developers Apr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

HTML: The Structure, CSS: The Style, JavaScript: The Behavior HTML: The Structure, CSS: The Style, JavaScript: The Behavior Apr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web Design The Future of HTML: Evolution and Trends in Web Design Apr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

The Future of HTML, CSS, and JavaScript: Web Development Trends The Future of HTML, CSS, and JavaScript: Web Development Trends Apr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML vs. CSS vs. JavaScript: A Comparative Overview HTML vs. CSS vs. JavaScript: A Comparative Overview Apr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

See all articles