Python上使用第三方STMP

菜鸟级别的我,学习了基本的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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值