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. Git 的 cherry-pick 功能

    简而言之,cherry-pick就是从不同的分支中捡出一个单独的commit,并把它和你当前的分支合并.如果你以并行方式在处理两个或以上分支,你可能会发现一个在全部分支中都有的bug.如果你在一个分支 ...

  2. devops 几个方便的工具

    1. fake API      [canned](https://github.com/sideshowcoder/canned  )    fake API.      [wiremock](ht ...

  3. PADS Logic 脚本的 Fields 一个对象记录

    PADS Logic 脚本的 Fields 一个对象记录 PADS Laogic 有一个非常棒的脚本功能,可以导出所以元件. 我目前是把脚本绑定到 Ctrl+S 上,在保存时自动导出 txt 文件,方 ...

  4. Oracle查询脚本优化

    发现生产环境的Oracle数据库cpu使用率上升超过70%,其中一条查询语句达到每秒调用40多次.现在我们来观摩下该语句: select t.id,t.level,t.policy, t.type,t ...

  5. EM64T和64位是不是一个概念啊?他们有什么区别啊,怎么区分啊?

    首先我们要解决什么是64位这个问题.究竟什么是64位处理器呢?64 bit是相对于32 Bit而言的,这个位数指的是CPU GPRs(General-Purpose Registers,通用寄存器)数 ...

  6. Python 列表笔记

    列表解析 squares = []for i in range(1,11): square = i**2 squares.append(square)print squares ########## ...

  7. java代码====实现按钮点击改变颜色=======

    总结: package com.a.b; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event ...

  8. Java-Runoob:Java 条件语句

    ylbtech-Java-Runoob:Java 条件语句 1.返回顶部 1. Java 条件语句 - if...else 一个 if 语句包含一个布尔表达式和一条或多条语句. 语法 if 语句的语法 ...

  9. MFC 菜单栏杂记

    1.关于为毛要使用detach()函数 CMenu menu; menu.LoadMenu(IDR_MAINFRAME); SetMenu(&menu); menu.Detach(); //如 ...

  10. java的IO流初探

    DEMO代码: /* * 文件IO流的简单演示 */ package com.IO; import java.io.*; public class Demo_IO_1 { /** * @param a ...