search
HomeBackend DevelopmentPython Tutorial详解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/imghwm/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/imghwm/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发送邮件详细解析,希望对大家的学习有所帮助。

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
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!