python初级实战-----关于邮件发送问题
python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用。smtplib模块主要负责发送邮件,email模块主要负责构造邮件。
smtplib模块主要负责发送邮件:是一个发送邮件的动作,连接邮箱服务器,登录邮箱,发送邮件(有发件人,收信人,邮件内容)。
email模块主要负责构造邮件:指的是邮箱页面显示的一些构造,如发件人,收件人,主题,正文,附件等。
1.smtplib模块
smtplib使用较为简单。以下是最基本的语法。
导入及使用方法如下:
import smtplib smtp = smtplib.SMTP()
smtp.connect('smtp.163.com,25')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
说明:
1)smtplib.SMTP():实例化SMTP()
2)smtp.connect(host,port): host:指定连接的邮箱服务器。常用邮箱的smtp服务器地址如下:
新浪邮箱:smtp.sina.com,新浪VIP:smtp.vip.sina.com,搜狐邮箱:smtp.sohu.com,126邮箱:smtp.126.com,139邮箱:smtp.139.com,163网易邮箱:smtp.163.com。
port:指定连接服务器的端口号,默认为25.
3)smtp.login(user,password):
user:登录邮箱的用户名。password:登录邮箱的密码,需要在网页版的网易邮箱中设置授权码,该授权码即为客户端密码。
4)sendmail(from_addr,to_addrs,msg,...):
from_addr:邮件发送者地址; to_addrs:邮件接收者地址。字符串列表['接收地址1','接收地址2','接收地址3',...]或'接收地址'
5)msg:发送消息:邮件内容。一般是msg.as_string():as_string()是将msg(MIMEText对象或者MIMEMultipart对象)变为str。
6)quit():用于结束SMTP会话。
2.email模块
email模块下有mime包,mime英文全称为“Multipurpose Internet Mail Extensions”,即多用途互联网邮件扩展,是目前互联网电子邮件普遍遵循的邮件技术规范。
该mime包下常用的有三个模块:text,image,multpart。
导入方法如下:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
构造一个邮件对象就是一个Message
对象,如果构造一个MIMEText
对象,就表示一个文本邮件对象,如果构造一个MIMEImage
对象,就表示一个作为附件的图片,要把多个对象组合起来,就用MIMEMultipart
对象,而MIMEBase
可以表示任何对象。它们的继承关系如下:
Message
+- MIMEBase #表示任何对象
+- MIMEMultipart
+- MIMENonMultipart #把多个对象组合起来
+- MIMEMessage
+- MIMEText #文本
+- MIMEImage #作为附件的图片
2.1 multpart说明
常见的multipart类型有三种:multipart/alternative, multipart/related和multipart/mixed。
邮件类型为"multipart/alternative"的邮件包括纯文本正文(text/plain)和超文本正文(text/html)。
邮件类型为"multipart/related"的邮件正文中包括图片,声音等内嵌资源。
邮件类型为"multipart/mixed"的邮件包含附件。向上兼容,如果一个邮件有纯文本正文,超文本正文,内嵌资源,附件,则选择mixed类型。
msg = MIMEMultipart('mixed')
我们必须把Subject,From,To添加到MIMEText对象或者MIMEMultipart对象中,邮件中才会显示主题,发件人,收件人。
msg = MIMEMultipart('mixed')
msg['Subject'] = '这是一个标题'
msg['From'] = 'XXX@163.com <XXX@163.com>'
msg['To'] = 'XXX@126.com'
2.2 发送文本邮件
邮件发送程序为了防止有些邮件阅读软件不能显示处理HTML格式的数据,通常都会用两类型分别为"text/plain"和"text/html"
构造MIMEText对象时,第一个参数是邮件正文,第二个参数是MIME的subtype,最后一定要用utf-8编码保证多语言兼容性。
以上的构造的文本添加到MIMEMultipart('mixed')中
创建一个普通文本:
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"
text_plain = MIMEText(text, 'plain', 'utf-8')
msg.attach(text_plain)
仅发送文本邮件:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText # 设置smtplib所需的参数
smtpserver = 'smtp.163.com'
username = 'xxxxxx@163.com'
password = 'xxxxxmima'
sender = 'xxxxxx@163.com'
receiver=['11111111@qq.com']
# 收件人为多个收件人
#receiver = ['11111111@qq.com', '22222@qq.com'] # 构造邮件对象MIMEMultipart对象
msg = MIMEMultipart('mixed')
msg['Subject'] = '这个是邮件主题'
msg['From'] = 'xxxxxx@163.com <xxxxxx@163.com>'
msg['To'] = '11111111@qq.com'
# 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
#msg['To'] = ";".join(receiver) # 构造文字内容
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"
text_plain = MIMEText(text, 'plain', 'utf-8')
msg.attach(text_plain) # 调用smtplib模块发送邮件
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
2.3 发送超文本附件
内容格式:
html = """
<html>
<body>
<p>
Here is the <a href="http://www.sohu.com">link</a> you wanted.
</p>
</body>
</html>
"""
text_html = MIMEText(html,'html', 'utf-8')
text_html["Content-Disposition"] = 'attachment; filename="baidu.html"'
msg.attach(text_html)
2.4 发送图片
添加图片:
# 构造图片链接
sendimagefile = open(r'D:\0.jpg', 'rb').read()
image = MIMEImage(sendimagefile)
image.add_header('Content-ID', '<image1>')
image["Content-Disposition"] = 'attachment; filename="testimage.png"'
msg.attach(image)
仅发送图片附件:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage # 设置smtplib所需的参数
smtpserver = 'smtp.163.com'
username = 'xxxxxx@163.com'
password = 'xxxxxmima'
sender = 'xxxxxx@163.com'
receiver=['11111111@qq.com']
# 收件人为多个收件人
#receiver = ['11111111@qq.com', '22222@qq.com'] # 构造邮件对象MIMEMultipart对象
msg = MIMEMultipart('mixed')
msg['Subject'] = '这个是邮件主题'
msg['From'] = 'xxxxxx@163.com <xxxxxx@163.com>'
msg['To'] = '11111111@qq.com'
# 收件人为多个收件人,通过join将列表转换为以;为间隔的字符串
#msg['To'] = ";".join(receiver) # 构造图片链接
sendimagefile = open(r'D:\0.jpg', 'rb').read()
image = MIMEImage(sendimagefile)
image.add_header('Content-ID', '<image1>')
image["Content-Disposition"] = 'attachment; filename="testimage.png"'
msg.attach(image) # 调用smtplib模块发送邮件
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
2.5发送附件
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage # 设置smtplib所需的参数
smtpserver = 'smtp.163.com'
username = 'xxxxxx@163.com'
password = 'xxxxxmima'
sender = 'xxxxxx@163.com'
receiver = ['11111111@qq.com', '22222@qq.com'] # 构造邮件对象MIMEMultipart对象
msg = MIMEMultipart('mixed')
msg['Subject'] = '一个附件'
msg['From'] = 'xxxxxx@163.com <xxxxxx@163.com>'
msg['To'] = ";".join(receiver) # 构造附件
sendfile = open(r'D:\111.txt', 'rb').read()
text_att = MIMEText(sendfile, 'base64', 'utf-8')
text_att["Content-Type"] = 'application/octet-stream'
# 以下附件可以重命名成aaa.txt
text_att["Content-Disposition"] = 'attachment; filename="aaa.txt"'
msg.attach(text_att) # 发送邮件
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
2.6 文字,html,图片,附件实现实例
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage # 设置smtplib所需的参数
smtpserver = 'smtp.163.com'
username = 'xxxxxx@163.com'
password = 'xxxxxmima'
sender = 'xxxxxx@163.com'
receiver = ['11111111@qq.com', '22222@qq.com'] # 构造邮件对象MIMEMultipart对象
msg = MIMEMultipart('mixed')
msg['Subject'] = '一个测试邮件'
msg['From'] = 'xxxxxx@163.com <xxxxxx@163.com>'
msg['To'] = ";".join(receiver) # 构造文字内容
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.baidu.com"
text_plain = MIMEText(text, 'plain', 'utf-8')
msg.attach(text_plain) # 构造图片链接
sendimagefile = open(r'D:\0.jpg', 'rb').read()
image = MIMEImage(sendimagefile)
image.add_header('Content-ID', '<image1>')
image["Content-Disposition"] = 'attachment; filename="testimage.png"'
msg.attach(image) # 构造html
html = """
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.baidu.com">link</a> you wanted.<br>
</p>
</body>
</html>
"""
text_html = MIMEText(html, 'html', 'utf-8')
text_html["Content-Disposition"] = 'attachment; filename="texthtml.html"'
msg.attach(text_html) # 构造附件
sendfile = open(r'D:\111.txt', 'rb').read()
text_att = MIMEText(sendfile, 'base64', 'utf-8')
text_att["Content-Type"] = 'application/octet-stream'
# 以下附件可以重命名成aaa.txt
text_att["Content-Disposition"] = 'attachment; filename="aaa.txt"'
msg.attach(text_att) # 发送邮件
try:
smtp = smtplib.SMTP()
smtp.connect('smtp.163.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
3、定义一个发件函数,方便使用时调用
from email.mime.text import MIMEText
from email.header import Header
import smtplib def send_mail(to_addr, message):
# 构建收发件信息
from_addr = '1129719492@qq.com' # 发件邮箱
password = 'xxxxxx' # 邮箱密码
smtp_server = 'smtp.qq.com' # SMTP服务器,以qq为例 # 构建邮件信息
msg = MIMEText(message, 'plain', 'utf-8') # plain表示纯文本文件,utf-8为了保证兼容性,
# msg需要有‘Subject’、'From'、'To'三个键值对,其中'Subject'对应的是邮件的标题,'From'是发件人,'To'是收件人
msg['Subject'] = Header("一封测试邮件", 'utf-8')
msg['From'] = Header(from_addr) # 收件信息中发件人名,可以自定义不必与发件人一样
msg['To'] = Header(to_addr) # 收件信息中收件人名,可以自定义不必与收件人一样 try:
server = smtplib.SMTP(smtp_server, 25) # 第二个参数为默认端口为25,有些邮件有特殊端口
print('开始登录')
server.login(from_addr, password) # 登录邮箱
print('登录成功')
print("邮件开始发送")
server.sendmail(from_addr, to_addr, msg.as_string()) # 将msg转化成string发出
server.quit()
print("邮件发送成功")
except smtplib.SMTPException as e:
print("邮件发送失败", e)
python初级实战-----关于邮件发送问题的更多相关文章
- Python 原生2种 邮件发送(发送验证码) 的方法
import smtplib from email.mime.text import MIMEText # 第三方 SMTP 服务 mail_host = "smtp.sina.cn&quo ...
- python系统监控及邮件发送
python系统监控及邮件发送 #psutil模块是一个跨平台库,能轻松实现获取系统运行的进程和系统利用率 import psutil ...
- python定时利用QQ邮件发送天气预报
大致介绍 好久没有写博客了,正好今天有时间把前几天写的利用python定时发送QQ邮件记录一下 1.首先利用request库去请求数据,天气预报使用的是和风天气的API(www.heweather.c ...
- Spring Boot实战系列-----------邮件发送
快速导航 添加Maven依赖 配置文件增加邮箱相关配置 Service.Test项目代码构建 五种邮件发送类型讲解 文本邮件 html邮件 附件邮件 html内嵌图片邮件 模板邮件 问题汇总 添加ma ...
- Python编写的Linux邮件发送工具
之前有用过Linux自带的mail工具来定时发送邮件,但是要装mailx还有配mail.rc,这还比较正常,关键是到了ubantu下这工具用起来真是操蛋,如果哪天其他的unix like操作系统也有需 ...
- python初级实战-----主机在线情况监控web
背景 公司有600多台服务器,打算写一个小程序,能一眼看见哪些服务器不在线. 大体思路是: 1.把所有服务器ip存进数据库,ping命令判断服务器是否在线 2.更新数据库中ip的状态 3.简单的web ...
- Python应用-完成简单邮件发送功能
项目中有时候需要用脚本来自动发送邮件,而用Python来发送邮件十分的方便,代码如下: #!/usr/bin/python #coding:utf-8 import smtplib from emai ...
- centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本)
centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本) ##################### sendmail.py begin ######## ...
- python 项目实战之Django 邮件发送
发送邮件¶ 虽然 Python 借助 smtplib 模块简化了发送邮件的流程,但是 Django 在其基础上提供了更简化的支持.这些封装意在加快邮件发送,方便在开发时测试发送邮件,在不支持 SMTP ...
随机推荐
- commons工具类 FilenameUtils FileUtils
首先要导入conmmon.jar包 FileUtils类 package cn.lijun.demo2; import java.io.File; import java.io.IOException ...
- CodeForces160D 最小生成树 + dfs
https://cn.vjudge.net/problem/26727/origin 题目大意: 给一个带权的无向图,保证没有自环和重边. 由于最小生成树不唯一,因此你需要确定每一条边是以下三种情况哪 ...
- 解决phpmyadmin 遇见的问题
1.phpmyadmin4.8.3 上传到网站目录后提示解决phpmyadmin mysqli_real_connect(): (HY000/2002): No such file or direct ...
- 检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件时失 败,原因是出现以下错误: 80080005
.Net MVC项目,在下载一个Excel的时候总是报错. 解决办法: 在服务器中,运行dcomcnfg打开组件服务, 依次展开"组件服务"->"计算机" ...
- springmvc上传图片《2》
创建springboot项目 编写配置 server: port: 8082 spring: application: name: upload-service servlet: multipart: ...
- 使用git遇到的一些问题
上传github时忽略.DS_Store方法 这个文件在mac中是管理文件夹的位置之类的信息,所以并没有必要上传到git中,这个时候就需要用git.gitignore文件来忽略此类文件. 在默认情况下 ...
- Sql Server 游标例子笔记
create PROCEDURE total_mySaleDuty as BEGIN DECLARE @a int,@error int DECLARE @b int,@errorb int DECL ...
- java和c#通过esb服务互调用组件
场景:java和c#写的服务.站点,互相任意调用.实现一切即服务. 解决方案:使用这种轻量级的esb架构,通过tcp通信解决通信传输问题,总线服务解决服务地址问题,契约解决数据交互问题.由于组件封装了 ...
- .net 数据绑定gridview 和Repeater 序号,Container.ItemIndex
gridview <asp:TemplateColumn HeaderText="编号"> <ItemTemplate> &l ...
- 使用JMeter进行一次简单的带json数据的post请求测试,json可配置参数
配置: 1.新建一个线程组: 然后设置线程数.运行时间.重复次数. 2.新建Http请求: 设置服务器域名,路径,方法,编码格式,数据内容. 可以在函数助手中,编辑所需要的变量,比如本例中的随机生成电 ...