python smtplib邮件模块

Posted on Posted in python
Tips: 本文创建于2016年6月22日,已超过 2 年,内容或图片可能已经失效!

几个邮件例子,包括文本、html、图片和附件

环境为python3,期间用python2实验过,花费了很久时间,解决蛋疼的编码问题,后来想想没必要。

简单的方法,不用中文

最后一个例子,是python2解决中文的一个方法

文本

#!/usr/bin/env python    
import smtplib    
import string    
    
HOST = 'smtp.qq.com'    #定义smtp主机    
SUBJECT = 'Test email from python'  #定义邮件主题    
TO = 'honghe.liu@mhealth365.com'    #定义邮件收件人,如果是多人 TO = 一个列表 ,类似to = to.split(',')  
FROM = '352517144@qq.com'   #定义邮件发件人    
text = 'python rules them all'  #邮件内容    
# 下面的 TO 是个字符串,真实用需要转换,类似 to = ','.join(to)
BODY = "\r\n".join(("From: %s" % FROM,"To: %s" % TO,"Subject: %s" % SUBJECT,"",text))   #主体内容    
server = smtplib.SMTP_SSL()     #创建SMTP()对象,这里用的ssl如果不用,就是smtplib.SMTP()    
server.set_debuglevel(1) #开启debug
server.connect(HOST,"465")      #连接    
#server.starttls()  #这句不用ssl时可以加上    
server.login(FROM,"passwd") #邮箱账号登录校验    
server.sendmail(FROM,[TO],BODY)     #邮件发送    
server.quit()   #断开  

html


#!/usr/bin/env python  
#-*- coding: UTF-8 -*-  
import smtplib  
from email.mime.text import MIMEText  
  
HOST = 'smtp.qq.com'  
SUBJECT = '官网流量数据报表'  
TO = 'honghe.liu@mhealth365.com'  # 多人,是个列表
FROM = '352517144@qq.com'  
msg = MIMEText(""" 
<ul> 
<li>a</li> 
<li>b</li> 
<li>c</li> 
</ul> 
""","html","utf-8")  
msg['Subject'] = SUBJECT  
msg['From'] = "你从哪里来<"+FROM+">"  
msg['To'] = "你到哪里去<"+TO+">"  # 字符串
try:  
    server = smtplib.SMTP_SSL()  
    server.connect(HOST,"465")  
    server.login(FROM,"passwd")  
    server.sendmail(FROM, TO,msg.as_string())  
    server.quit()  
    print("邮件发送成功")  
except Exception as e:  
    print("失败:{}".format(str(e)))  

带图片


#!/usr/bin/env python  
#-*- coding: UTF-8 -*-  
import smtplib  
from email.mime.multipart import MIMEMultipart  
from email.mime.text import MIMEText  
from email.mime.image import MIMEImage  
  
HOST = 'smtp.qq.com'  
SUBJECT = "主题"  
TO = 'honghe.liu@mhealth365.com'  
FROM = '352517144@qq.com'  
  
def addimg(src,imgid):  
    """添加图片函数 
     
    src 图片路径 imgid 图片id"""  
    fp = open(src, 'rb')    #打开文件  
    msgImage = MIMEImage(fp.read())     #创建MIMEImage对象,读取图片内容作为参数  
    fp.close()  #关闭文件  
    msgImage.add_header("Content-ID", imgid)    #指定图片文件的Content-ID,<img>  
    return msgImage     #返回msgImage对象  
  
msg = MIMEMultipart('related')  #创建MIMEMultipart对象,采用related定义内嵌资源的邮件体  
  
msgtext = MIMEText(""" 
<img src="cid:io" /> 
<img src="cid:key_hit" /> 
<img src="cid:men" /> 
<img src="cid:swap" /> 
""","html","utf-8")  
  
msg.attach(msgtext)     #MIMEMultipart 对象附加MIMEText的内容  
msg.attach(addimg("img/io.png","io"))     
msg.attach(addimg("img/key_hit.png","key_hit"))  
msg.attach(addimg("img/mem.png","men"))  
msg.attach(addimg("img/swap.png","swap"))  
  
msg['Subject'] = SUBJECT  
msg['From'] = FROM  
msg['To'] = TO  
  
server = smtplib.SMTP_SSL()  
server.connect(HOST,"465")  
server.login(FROM,"passwd")  
server.sendmail(FROM, TO, msg.as_string())  
server.quit()  
print("发送邮件成功")  

附件

#!/usr/bin/env python  
#-*- coding: UTF-8 -*-  
import smtplib  
from email.mime.multipart import MIMEMultipart  
from email.mime.text import MIMEText  
from email.mime.image import MIMEImage  
  
HOST = 'smtp.qq.com'  
SUBJECT = "主题"  
TO = 'honghe.liu@mhealth365.com'  
FROM = '352517144@qq.com'  
  
def addimg(src,imgid):  
    """添加图片函数 
     
    src 图片路径 imgid 图片id"""  
    fp = open(src, 'rb')  
    msgImage = MIMEImage(fp.read())  
    fp.close()  
    msgImage.add_header("Content-ID", imgid)  
    return msgImage  
  
msg = MIMEMultipart('related')  
  
msgtext = MIMEText("<font color=red>图片</font><br /><img src=\"cid:io\" border=\"1\" /><br>详情附件","html","utf-8")  
  
msg.attach(msgtext)  
msg.attach(addimg("img/io.png","io"))  
  
attach = MIMEText(open("doc/123.xls","rb").read(), "base64","utf-8")  
attach["Content-Type"] = "application/octet-stream"  
attach["Content-Disposition"] = 'attachment; filename="123.xls"'  
msg.attach(attach)  #附件1  
  
attach1 = MIMEText(open("doc/1234.xls","rb").read(), "base64","utf-8")  
attach1["Content-Type"] = "application/octet-stream"  
attach1["Content-Disposition"] = 'attachment; filename="1234.xls"'  
msg.attach(attach1) #附件2  
  
msg['Subject'] = SUBJECT  
msg['From'] = FROM  
msg['To'] = TO  
  
server = smtplib.SMTP_SSL()  
server.connect(HOST,"465")  
server.login(FROM,"passwd")  
server.sendmail(FROM, TO, msg.as_string())  
server.quit()  
print("发送邮件成功")  

python2 中文

#!/usr/bin/env python  
#-*- coding: UTF-8 -*-  
import smtplib  
from email import encoders  
from email.mime.text import MIMEText  
from email.header import Header  
from email.utils import parseaddr, formataddr  
import sys  
  
if len(sys.argv) != 2:  
    print '1'  
    sys.exit(1)  
try:  
    message = sys.argv[1]  
    if 2 == len(message.split('/')):  
    email_name = message.split('/')[0]  
    code = message.split('/')[1]  
    else:  
        print 'args ERR'  
        sys.exit(1)  
except Exception:  
    e = None  
    sys.exit(2)  
  
def _format_addr(s):  
    name, addr = parseaddr(s)  
    return formataddr(( \  
        Header(name, 'utf-8').encode(), \  
        addr.encode('utf-8') if isinstance(addr, unicode) else addr))  
  
msg = MIMEText("您在掌上心电邮箱注册的验证码是: <span style='border-bottom-width: 1px; font-weight: bold; color: #ff9900; border-bottom-style: dashed; border-bottom-color: rgb(204, 204, 204); z-index: 1; position: static;' >%s</span> , 请在5分钟内完成注册认证。" % code ,'html', 'utf-8')  
FROM = 'noreply@example.com'  
msg['From'] = _format_addr(u'掌上心电 <%s>' % FROM)  
TO = email_name  
msg['To'] = _format_addr(u'<%s>' % TO)  
msg['Subject']= Header(u'掌上心电邮箱注册的验证','utf-8').encode()  
  
HOST = 'smtp.sina.com'  
server = smtplib.SMTP()  
server.connect(HOST,"25")  
server.login(FROM,"passwd")  
server.sendmail(FROM,[TO],msg.as_string())  
server.quit()  
» 转载请注明来源:若我若鱼 » python smtplib邮件模块

Leave a Reply

Your email address will not be published. Required fields are marked *

14 − 8 =