天天看點

Python使用SMTP發送郵件執行個體

拿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&copyright=undefined&se=&sme=&tab=0&width=undefined&height=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'郵件發送失敗!')