Python上使用第三方STMP

来源:互联网 发布:windows日志服务器 编辑:程序博客网 时间:2024/06/14 07:06

菜鸟级别的我,学习了基本的Python语法,今天把SMTP内容整理一下。
python的smtplib提供了一种很方便的途径发送电子邮件。在此前需要了解到电脑上是否已安装了支持SMTP 服务,如:sendmail
我的电脑上没有安装,所以用的是第三方STMP服务发送。用的是QQ邮箱,需要在QQ邮箱里点击设置,开启STMP服务,获得授权码。下面是两个例子:
例1、仅仅发送文本内容:

# -*- coding: utf-8 -*-#借助Python使用QQ邮箱发送邮件import smtplibfrom email.mime.text import MIMEText_user="***@qq.com"#发送者_pwd="***"# 在QQ邮箱中开启SMTP后获得的授权码_to="***@qq.com"#接受者msg=MIMEText("Test")#邮件内容msg["Subject"]="anything u like is ok"#邮件主题msg["From"]=_usermsg["To"]=_totry:    s=smtplib.SMTP_SSL("smtp.qq.com",465)#建立SSL连接 ,SMTP服务器:smtp.qq.com ,SSL端口465    s.login(_user,_pwd)#登录服务器    s.sendmail(_user,_to,msg.as_string())    s.quit()    print "Success!"except smtplib.SMTPException,e:    print "Failed,%s" %e

例2、发送HTML格式的邮件,并附图片

# -*- coding: utf-8 -*-#借助Python使用QQ邮箱发送邮件,附带链接和图片显示import smtplibfrom email.mime.text import MIMETextfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.header import Header_user="***@qq.com"#发送者_pwd="***"# 在QQ邮箱中开启SMTP后获得的授权码_to="***@qq.com"#接受者#msg=MIMEText("Test")#邮件内容msg=MIMEMultipart('related')msg["Subject"]="anything you like is ok"#邮件主题msg["From"]=_usermsg["To"]=_tomsgAlter=MIMEMultipart('alternative')msg.attach(msgAlter)mail_msg="""<p>this is a test for picture...</p><p><a href="http://www.baidu.com"> 度娘一下了</a></p><p>show a pic: </p><p><img src="cid:image1"></p>"""msgAlter.attach(MIMEText(mail_msg,'html','utf-8'))#指定图片为当前目录fp=open('image1.png','rb')msgImage=MIMEImage(fp.read())fp.close()#定义图片ID,在HTML文本中引用msgImage.add_header('Content-ID','<image1>')msg.attach(msgImage)try:    s=smtplib.SMTP_SSL("smtp.qq.com",465)#建立SSL连接 ,SMTP服务器:smtp.qq.com ,SSL端口465    s.login(_user,_pwd)#登录服务器    s.sendmail(_user,_to,msg.as_string())    s.quit()    print "Success!"except smtplib.SMTPException,e:    print "Failed,%s" %e
0 0
原创粉丝点击