SMTP(Simple Mail Transfer Protocol)是简单邮件传输协议,它是一组用于由源地址到目的地址的邮件传输规则。

python中对SMTP进行了简单的封装,可以发送纯文本邮件,HTML邮件以及带附件的邮件

python创建SMTP对象语法如下:

import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

参数说明:

  • host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如: runoob.com,这个是可选参数。
  • port: 如果你提供了 host 参数, 你需要指定 SMTP 服务使用的端口号,一般情况下 SMTP 端口号为25。
  • local_hostname: 如果 SMTP 在你的本机上,你只需要指定服务器地址为 localhost 即可。

python SMTP对象使用sendmail方法发送邮件,语法如下:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

参数说明:

  • from_addr: 邮件发送者地址。
  • to_addrs: 字符串列表,邮件发送地址。
  • msg: 发送消息

这里要注意一下第三个参数,msg 是字符串,表示邮件。我们知道邮件一般由标题,发信人,收件人,邮件内容,附件等构成,发送邮件的时候,要注意 msg 的格式。这个格式就是 smtp 协议中定义的格式。

  • email模块:负责构建邮件
  • smtplib模块:负责发送邮件

email模块:支持发送的邮件内容为纯文本,HTML内容,图片,附件。email模块中有几类来针对不同的邮件内容形式,常用如下:

  • MIMEText : (MIME媒体类型)内容形式为纯文本,HTML页面(导入方式 : from email.mime.text import MIMEText)
  • MIMEImage : 内容形式为图片(导入方式 : from email.mime.image import MIMEImage)
  • MIMEMultupart : 多形式组合,可包含文本和附件(导入方式 : from email.mime.multipart import MIMEMultipart)

1.MIMEText语法:

MIMEText(msg,type,chartset)

msg:文本内容

type:文本类型默认为plain(纯文本)

#发送HTML格式的时候,修改为html,但同时要求msg的内容也是html的格式。

chartset:文本编码,中文为“utf-8”

# 构造TEXT格式的消息

  msg = MIMEText("hello.text","plain","utf-8")

  msg["Subject"] = "xxxxx"

  msg["From"] = "xxxx"

  msg["To"] = "xxxx"

#发送以上构造的邮件内容要使用as_string将构造的邮件内容转换为string形式。

  s.sendmail("xxx","xxx",msg.as_string)

2.MIMEImage,MIMEMultipart语法

msg = MIMEMultipart()

#实例化一个文本对象

msg_sub = MIMEText("hello.text","plain","utf-8")

#将text消息添加到MIMEMultipart中,作为邮件正文。

msg.attach(msg_sub)

#图片作为附件

import os

img_datas = open(os.getcwd()+ "/reports/xxxx.png","rb").read()

msg_img = MIMEImage(img_data)

msg_img.add_header('Content-Disposition','attachment', filename = "xxxx.png" )

msg_img.add_header('Content-ID','<0>')

#将图片添加到MIMEMultiplart中,作为附件发送。

msg.attach(mag_img)

~~~~~~~~~~~~~~~~~

下面来看具体代码:

发送文本邮件

# coding=utf-
import smtplib
from email.mime.text import MIMEText
# 发送纯文本格式的邮件
msg = MIMEText('hello,send by python_test...','plain','utf-8')
#发送邮箱地址
sender = 'bmjoker@163.com'
#邮箱授权码,非登陆密码
password = 'xxxxxxx'
#收件箱地址
#receiver = '19xxxxxxx9@qq.com'
mailto_list = ['19xxxxxxx9@qq.com'] #群发邮箱地址 #smtp服务器
smtp_server = 'smtp.163.com'
#发送邮箱地址
msg['From'] = sender
#收件箱地址
#msg['To'] = receiver
msg['To'] =';'.join(mailto_list) #发送多人邮件写法
#主题
msg['Subject'] = 'hello,i just want to test' server = smtplib.SMTP(smtp_server,) # SMTP协议默认端口是25
server.login(sender,password) #ogin()方法用来登录SMTP服务器
server.set_debuglevel() #打印出和SMTP服务器交互的所有信息。
server.sendmail(sender,mailto_list,msg.as_string()) #msg.as_string()把MIMEText对象变成str server.quit() # 第一个参数为发送者,第二个参数为接收者,可以添加多个例如:['hello@163.com','xxx@qq.com',]# 第三个参数为发送的内容
server.quit()

查看和SMTP服务器交互的所有信息:

其中login()用来登陆SMTP服务器,sendmail()用来发送邮件,群发邮件的话,可以传入一个收件人邮箱列表,邮箱的正文是str,使用as_string()把MIMEText对象变成str,password指的不是smtp服务器的登陆密码,是smtp客户端的授权密码:

发送带HTML的邮件:

import smtplib
from email.mime.text import MIMEText
from email.header import Header sender = 'bmjoker@163.com' #发件邮箱
passwd = 'xxxxxxxx' #发送人邮箱授权码
receivers = '19xxxxxxx9@qq.com' #收件邮箱 subject = 'python发邮Html邮件测试' #主题 content = "<html><h1>人生苦短,我是bmjoker</h1></html>"
msg = MIMEText(content,'html','utf-8')
# msg['Subject'] = subject
msg['Subject'] = Header(subject,'utf-8')
# msg['From'] = sender
msg['From'] = Header('hello','utf-8')
# msg['To'] = receivers
msg['To'] = Header('emmmm','utf-8')
try:
s = smtplib.SMTP_SSL('smtp.163.com',)
s.login(sender,passwd)
s.sendmail(sender,receivers,msg.as_string())
print('Send Success') except:
print('Send Failure')

emmm....遇到554/553问题居多,如果失败,请参考smtp退信排错:http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html

另附常见的邮箱服务器(pop3,smtp)地址,端口:

http://www.cnblogs.com/grefr/p/6089079.html

发送带图片的邮件:

import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart sender = 'bmjoker@163.com'
passwd = 'xxxxxxxx'
receivers = '19xxxxxx9@qq.com'
subject = 'python发邮带img的邮件测试' #主题 # 创建一个带附件的实例
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receivers # 创建正文
msg.attach(MIMEText('使用python smtplib模块和email模块自动发送邮件测试','plain','utf-8')) # 创建图片附件
import os
img_file = open(os.getcwd()+"/a4.jpg",'rb').read()
msg_img = MIMEImage(img_file)
msg_img.add_header('Content-Disposition','attachment', filename = "a4.jpg")
msg_img.add_header('Content-ID', '<0>')
msg.attach(msg_img) try:
s = smtplib.SMTP('smtp.163.com',)
s.set_debuglevel() #输出发送邮件详细过程
s.login(sender,passwd)
s.sendmail(sender,receivers,msg.as_string())
print('Send Succese') except:
print('Send Failure')

提示发送成功,不过emmm....

可能TX被APT攻击吓坏了吧....

发送带附件的邮件:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header sender = 'bmjoker@163.com'  #发件邮箱
passwd = 'xxxxxxxxxx'  # 邮箱授权码
receivers = '19xxxxxx9@qq.com'  #收件邮箱 subject = 'python发带附件的邮件测试' #主题
# 创建一个带附件的实例
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = receivers #创建正文,将文本文件添加到MIMEMultipart中
msg.attach(MIMEText('使用python smtplib模块和email模块自动发送邮件测试','plain','utf-8')) #构造附件1,传送当前目录下 文件
att1 = MIMEText(open('testdata.xlsx','rb').read(),'base64','utf-8') # rb以二进制方式读取
# att1["Content-Type"] = 'application/octet-stream'
# filename为附件名称,可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename = "testdata.xlsx" '
#将附件添加到MIMEMultipart中
msg.attach(att1) #构造附件2
att2 = MIMEText(open('db.cfg','rb').read(),'base64','utf-8')
# att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename = "db.cfg" '
#将附件添加到MIMEMultipart中
msg.attach(att2) try:
s = smtplib.SMTP('smtp.qq.com',2)
s.set_debuglevel() #输出发送邮件详细过程
s.login(sender,passwd)
s.sendmail(sender,receivers,msg.as_string())
print('Send Succese') except:
print('Send Failure')

3.python 发送邮件之smtplib模块的更多相关文章

  1. python:利用smtplib模块发送邮件

    自动化测试中,测试报告一般都需要发送给相关的人员,比较有效的一个方法是每次执行完测试用例后,将测试报告(HTML.截图.附件)通过邮件方式发送. 参考代码:send_mail.py 一.python对 ...

  2. python:利用smtplib模块发送邮件详解

    自动化测试中,测试报告一般都需要发送给相关的人员,比较有效的一个方法是每次执行完测试用例后,将测试报告(HTML.截图.附件)通过邮件方式发送. 首先我们要做: 进入163邮箱,点击设置中的pop3/ ...

  3. python之使用smtplib模块发送邮件

    # 使用smtplib模块发送邮件 import smtplib from email.mime.text import MIMEText from email.header import Heade ...

  4. Python发送邮件:smtplib、sendmail

    本地Ubuntu 18.04,本地Python 3.6.5, 阿里云Ubuntu 16.04,阿里云Python 3.5.2, smtplib,sendmail 8.15.2, 今天,打算实现通过电子 ...

  5. python发送邮件(smtplib)

    我们在测试完成后,都会发一份邮件也就是我们的测试报告,那么既然要自动化,是不是也可以通过python帮助我们发送邮件?当然这么强大的python可以帮助你完成这个需求 SMTP SMTP(Simple ...

  6. python发送邮件(yagmail模块)

    import yagmail user = 'xxxx@qq.com' passwd = 'xxxx' # 授权码,不是密码,需要在邮箱中设置,看邮箱类型,有的需要设置 res = yagmail.S ...

  7. python之smtplib模块 发送邮件

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #smtplib模块 发送邮件 import smtplib from email.mime.text imp ...

  8. 解读Python发送邮件

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

  9. python 发送邮件 <QQ+腾讯企业邮箱>

    一.使用QQ邮箱或者腾讯企业邮箱 python 发送邮件属于网络编程方向的,在工作中,我需要经常用邮件来检测我的程序运行状况.使用起来十分方便,这里我就用腾讯企业邮箱作为我的收发邮箱来使用. 使用py ...

随机推荐

  1. sublime text 3设置浏览器快捷键

    一.设置默认浏览器 1,打开sublime 依次选择 tools > build system > new build system... 2,选择你喜欢的浏览器,右键 > 属性 把 ...

  2. 向HDFS中追加内容

    向生成好的hdfs文件中追加内容,但是线上使用的版本是1.0.3,查看官方文档发现,在1.0.4版本以后才支持文件append 以下是向hdfs中追加信息的操作方法 如果你只在某一个driver中追加 ...

  3. 积累 ---- PHP可能会遇到的面试题

    1.白盒测试和黑盒测试的区别 2.Bootstrap是什么 3.OOP是什么意思 4.git和svn的使用 5.常用的git命令 6.lamp开发环境 7.高内聚,低耦合

  4. zookeeper运维(转)

    本文以ZooKeeper3.4.3版本的官方指南为基础:http://zookeeper.apache.org/doc/r3.4.3/zookeeperAdmin.html,补充一些作者运维实践中的要 ...

  5. Eclipse使用EclEmma看单元测试的代码覆盖率

    在开发过程中,我们应该养成编写本地单元测试用例的好习惯,甚至做到测试驱动开发.EclEmma是Eclipse的一个插件,是一款测试用例的代码覆盖率统计工具,能明确到哪一行在测试过程中被调用到了.这里不 ...

  6. 字符串(二)(PHP)

    1.大段文本在PHP中应该如果表示? 答: <?php $str = <<<aaa hello word; fjasdflj fjslad aaa;date_sub() aaa ...

  7. CString 中的SpanIncluding 和SpanExcluding 用法

    SpanIncluding 简单的理解就是提取包含在指定串中的一个子串 MSDN上的备注说:从左边的第一个字符开始查找与给定串相等的字符,如果没有则返回空的串,反之,继续查找,到结束. 例子方便理解 ...

  8. 学习FPGA有必要写SDRAM控制器吗?

    在学习FPGA的过程中,注意是在学习过程中,联系FPGA的使用技巧,强烈建议尝试设计一个SDRAM控制器,不要使用IP核. 学习SDRAM控制器设计,能让你掌握很多知识. 更好的使用状态机去精准控制时 ...

  9. 全文检索引擎Solr系列——Solr核心概念、配置文件

    Document Document是Solr索引(动词,indexing)和搜索的最基本单元,它类似于关系数据库表中的一条记录,可以包含一个或多个字段(Field),每个字段包含一个name和文本值. ...

  10. Java中静态变量、静态代码块、非静态代码块以及静态方法的加载顺序

    在研究单例设计模式的时候,用到了静态变量和静态方法的内容,出于兴趣,这里简单了解一下这四个模块在类初始化的时候的加载顺序. 经过研究发现,它们的加载顺序为: 1.非静态代码块 2.静态变量或者静态代码 ...