這篇文章主要介紹了如何使用Python發(fā)送HTML格式的郵件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
創(chuàng)新互聯(lián)公司專注于企業(yè)營銷型網(wǎng)站、網(wǎng)站重做改版、安平網(wǎng)站定制設(shè)計(jì)、自適應(yīng)品牌網(wǎng)站建設(shè)、H5頁面制作、商城網(wǎng)站建設(shè)、集團(tuán)公司官網(wǎng)建設(shè)、外貿(mào)網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計(jì)等建站業(yè)務(wù),價(jià)格優(yōu)惠性價(jià)比高,為安平等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。發(fā)送html格式的和普通文本格式差不多,只是MIMEText(content,"html","utf-8"))與MIMEText(content,"plain","utf-8"))格式的區(qū)別,格式改一下就行了
Python發(fā)送HTML格式的郵件與發(fā)送純文本消息的郵件不同之處就是將MIMEText中_subtype設(shè)置為html。具體代碼如下:
#"-*- coding: utf-8 -*-" import smtplib from email.mime.text import MIMEText mail_user = raw_input("請輸入你的163郵箱: ") mail_password = raw_input("請輸入郵箱授權(quán)碼: ") mail_from = raw_input("來自: ") mail_sub = raw_input("郵件主題: ") mail_content = raw_input("郵件內(nèi)容: ") #例如: html格式的: "" msg=MIMEText(content,"html","utf-8") msg['Subject']=sub msg['From']=me to_list = map(None, raw_input("發(fā)送給: ").split(' ')) msg['To']=",".join(to_list) try: server=smtplib.SMTP() server.connect(mail_host) server.login(mail_user,mail_password) server.sendmail(me,to_list,msg.as_string()) server.close() return True except Exception,e: print str(e) return False if sendmail(mail_sub, mail_content): print "done!" else: print "falsed!" #第二種方法: #!/usr/bin/python #-*- coding: utf-8 -*- from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib mailer_name=raw_input("from: ") mail_user=raw_input("163 email address: ") mail_pass=raw_input("郵箱授權(quán)碼: ") mail_content=raw_input("content: ") #郵件內(nèi)容是html格式的 mail_host="smtp.163.com" mail_postfix="163.com" def send_mail(sub,content): me=mailer_name +"<"+mail_user+">" msg=MIMEText(content,"html","utf-8") msg['Subject']=sub msg['From']=me to_list = map(None,raw_input("mail_to: ").split(" "))#可以群發(fā) msg['To']=",".join(to_list) try: server=smtplib.SMTP() server.connect(mail_host) server.login(mail_user,mail_pass) server.sendmail(me,to_list,msg.as_string()) server.close() return True except Exception,e: print str(e) return False if send_mail("郵件",mail_content): print "done!" else: print "failed!"