3.python 发送邮件之smtplib模块

 

 

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

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

python建立SMTP对象语法以下:服务器

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

参数说明:app

  • 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])

参数说明:ui

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

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

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

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

  • 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语法:debug

MIMEText(msg,type,chartset)

msg:文本内容code

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-8 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,25) # SMTP协议默认端口是25 server.login(sender,password) #ogin()方法用来登陆SMTP服务器 server.set_debuglevel(1) #打印出和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',25) 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',25) s.set_debuglevel(1) #输出发送邮件详细过程 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',25) s.set_debuglevel(1) #输出发送邮件详细过程 s.login(sender,passwd) s.sendmail(sender,receivers,msg.as_string()) print('Send Succese') except: print('Send Failure')
相关文章
相关标签/搜索