拿qq邮箱做实验,先做准备工作,登录qq邮箱—>账户---->开启POP3/SMTP服务 (具体百度),你会拿到你的授权码,
接下来上代码:
#coding:utf-8
import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
#创建含附件的邮件
# 第三方 SMTP 服务
mail_host="smtp.qq.com" #设置服务器
mail_user="********@qq.com" #你的邮箱名
mail_pass="***********" #输入授权码,不含空格
subject = '告诉你个秘密'
mail_content='''住在老王隔壁的我:
不信你点开链接看看
<p><a href="http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=2018%E6%90%9E%E7%AC%91%E6%95%B4%E4%BA%BA%E5%B8%A6%E5%AD%97%E5%9B%BE%E7%89%87&step_word=&hs=0&pn=3&spn=0&di=24442370371&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=4053266476%2C2688843883&os=1284511358%2C3205201523&simid=0%2C0&adpicid=0&lpn=0&ln=1661&fr=&fmq=1555400651535_R&fm=rs1&ic=undefined&s=undefined&hd=undefined&latest=undefined©right=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=%E6%90%9E%E7%AC%91%E5%9B%BE%E7%89%87&objurl=http%3A%2F%2Fimg.tukexw.com%2Fimg%2F46a20594097b3a63.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Frtv_z%26e3Bp7hjxo_z%26e3Bv54AzdH3FrAzdH3Fr24jrj422u2ug2juojg2njij52wj5jr2djkjg2sjhur2n181g27jxjg2z1yjAzdH3F&gsm=0&rpstart=0&rpnum=0&islist=&querylist=&force=undefined">这是我拍到的</a></p>
<p><img src="cid:image1"></p>'''
sender = '*********@qq.com'#发件人,你的邮箱
receivers = ['**************@qq.com','**************@qq.com','**************@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
message = MIMEMultipart()
message['From'] = Header("隔壁老王", 'utf-8')
message['To'] = Header("住在老王隔壁的你", 'utf-8')
message['Subject'] = Header(subject, 'utf-8')
message.attach(MIMEText(mail_content, 'html', 'utf-8'))#邮件正文内容
# 构造附件1,传送当前目录下的 test.txt 文件
att1 = MIMEText(open('D:/workspace/python/wanxiao.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="hahaha.txt"'
message.attach(att1)
# 指定图片为当前目录
fp = open('D:/workspace/python/text.jpg', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
message.attach(msgImage)
smtpObj = smtplib.SMTP_SSL(mail_host, 465)
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
smtpObj.quit()
print (u"邮件发送成功")
# try:
#
# except smtplib.SMTPException:
# print(u'邮件发送失败!')