详解Python发送邮件实例
Python发送邮件需要smtplib和email两个模块。也正是由于我们在实际工作中可以导入这些模块,才使得处理工作中的任务变得更加的简单。今天,就来好好学习一下使用Python发送邮件吧。
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。
Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。
1.邮件正文是文本的格式
# -*- coding: UTF-8 -*- from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib import sys import csv import xlrd from pyExcelerator import * import os import xlwt from xlutils.copy import copy import pyExcelerator import datetime import time reload(sys) sys.setdefaultencoding("utf-8") mailto_list = [""] # 邮件接收方的邮件地址 mail_host = "smtp.exmail.qq.com" # 邮件传送协议服务器 mail_user = "" # 邮件发送方的邮箱账号 mail_pass = "" # 邮件发送方的邮箱密码 def send_mail(to_list, sub, content): me = "天才白痴梦"+"<"+mail_user+">" msg = MIMEText(content, _subtype='plain', _charset='utf-8') msg['Subject'] = sub # 邮件主题 msg['From'] = me msg['To'] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user, mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': sub = "天才白痴梦" content = '...' if send_mail(mailto_list, sub, content): print "发送成功" else: print "发送失败"
2.邮件正文是表格的格式:由于是表格,所以我们选择HTML来实现表格的功能,邮件上面显示的就是HTML实现的内容了。
# -*- coding: UTF-8 -*- from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import smtplib import sys import csv import xlrd from pyExcelerator import * import os import xlwt from xlutils.copy import copy import pyExcelerator import datetime import time reload(sys) sys.setdefaultencoding("utf-8") mailto_list = [""] # 邮件接收方的邮件地址 mail_host = "smtp.exmail.qq.com" # 邮件传送协议服务器 mail_user = "" # 邮件发送方的邮箱账号 mail_pass = "" # 邮件发送方的邮箱密码 def send_mail(to_list, sub, content): me = "天才白痴梦"+"<"+mail_user+">" # 和上面的代码不同的就是,这里我们选择的是html 的格式 msg = MIMEText(content, _subtype='html', _charset='utf-8') msg['Subject'] = sub # 邮件主题 msg['From'] = me msg['To'] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user, mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': sub = "天才白痴梦" html = '<html></html>' if send_mail(mailto_list, sub, html): print "发送成功" else: print "发送失败"
3.邮件正文是图片的格式:要把图片嵌入到邮件正文中,我们只需按照发送附件的方式,先把邮件作为附件添加进去,然后,在HTML中通过引用src="cid:0"就可以把附件作为图片嵌入了。如果有多个图片,给它们依次编号,然后引用不同的cid:x即可。
def send_mail(to_list, sub, content): me = "天才白痴梦"+"<"+mail_user+">" msg = MIMEMultipart() msg['Subject'] = sub # 邮件主题 msg['From'] = me msg['To'] = ";".join(to_list) txt = MIMEText("天才白痴梦", _subtype='plain', _charset='utf8') msg.attach(txt) # <b>:黑体 <i>:斜体 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') msg.attach(msgText) file1 = "F:\\1.jpg" image = MIMEImage(open(file1, 'rb').read()) image.add_header('Content-ID', '<image1>') msg.attach(image) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user, mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': sub = "天才白痴梦" html = '<html></html>' if send_mail(mailto_list, sub, html): print "发送成功" else: print "发送失败"
4.发送邮件附件:邮件附件是图片
def send_mail(to_list, sub, content): me = "天才白痴梦"+"<"+mail_user+">" msg = MIMEMultipart() msg['Subject'] = sub # 邮件主题 msg['From'] = me msg['To'] = ";".join(to_list) txt = MIMEText("天才白痴梦", _subtype='plain', _charset='utf8') msg.attach(txt) # # <b>:黑体 <i>:斜体 # 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') # msg.attach(msgText) # # file1 = "F:\\1.jpg" # image = MIMEImage(open(file1, 'rb').read()) # image.add_header('Content-ID', '<image1>') # msg.attach(image) att = MIMEText(open('F:\\1.jpg', 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="1.jpg"' msg.attach(att) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user, mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False
5.发送群邮件:同时发送给多人
mailto_list = [""] # 邮件接收方的邮件地址
上面这一行代码是邮件接收方的邮件地址,如果我们需要给多人发送邮件的话,就只需要把对方的邮件帐号绑在这一个列表里就ok了。
加密SMTP
使用标准的25端口连接SMTP服务器时,使用的是明文传输,发送邮件的整个过程可能会被窃听。要更安全地发送邮件,可以加密SMTP会话,实际上就是先创建SSL安全连接,然后再使用SMTP协议发送邮件。
方法:只需要在创建SMTP对象后,立刻调用starttls()方法,就创建了安全连接。
smtp_server = 'smtp.qq.com' smtp_port = 25 # 默认端口号为25 server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() # 剩下的代码和前面的一模一样: server.set_debuglevel(1) # 打印出和SMTP服务器交互的所有信息
以上就是关于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

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



VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

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.

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.

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.

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.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.
