菜鸟级别的我,学习了基本的Python语法,今天把SMTP内容整理一下。
python的smtplib提供了一种很方便的途径发送电子邮件。在此前需要了解到电脑上是否已安装了支持SMTP 服务,如:sendmail
我的电脑上没有安装,所以用的是第三方STMP服务发送。用的是QQ邮箱,需要在QQ邮箱里点击设置,开启STMP服务,获得授权码。下面是两个例子:
例1、仅仅发送文本内容:
# -*- coding: utf-8 -*-
#借助Python使用QQ邮箱发送邮件
import smtplib
from 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"]=_user
msg["To"]=_to
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
例2、发送HTML格式的邮件,并附图片
# -*- coding: utf-8 -*-
#借助Python使用QQ邮箱发送邮件,附带链接和图片显示
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from 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"]=_user
msg["To"]=_to
msgAlter=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