(Python)利用SMTP傳送郵件進階篇,傳送混合格式郵件
阿新 • • 發佈:2018-12-27
html很簡單,只要MIMEText中的引數改成html即可
附件也不難,難的是加圖片
雖然圖片可以當做附件傳送,但是顯然還需要一個加入正文的功能,方法是用html的img標籤把圖片加入。但是這樣會有個問題,一般的郵箱都會將這種連結遮蔽掉。這個問題有2種解決方法,第一種是先把圖片加入到附件,然後再把圖片加入正文,第二種是利用MIMEMultipart的三層結構。第一種方法就不能把圖片直接加入正文而不加入附件列表,所以我採用第二種。
程式碼:
#coding=utf-8
import smtplib
import json
fromemail.mime.text import MIMEText
from email.mime.image import MIMEImage
fromemail.mime.multipart import MIMEMultipart
host = ''
user = '' #發件人
password = ''
sender = ''
defsend_mail(to_list, subject, content,content_type='plain'):
msg_alt = MIMEMultipart('alternative')
msg_rel = MIMEMultipart('related')
msg = MIMEMultipart ('mixed')
msg_rel.attach(msg_alt)
msg.attach(msg_rel)
msg['from'] = user
msg['to'] = ','.join(to_list) #注意,不是分號
msg['subject'] = subject
if(content_type == 'plain'):
for type,item incontent:
if type == 'text':
text = MIMEText(item,'plain' ,'utf-8')
msg_alt.attach(text)
eliftype == 'attach_path':
attachment = get_attach(item)
if(attachment):
msg.attach(attachment)
else:
#print('type error')
pass
elifcontent_type == 'html':
mailBody = ''
for type,item incontent:
if type == 'html':
mailBody += item
eliftype == 'image_path':
image = get_image(item)
if(image):
con = '<p><img src=cid:'+ item +'></p>'
mailBody = mailBody + con
msg_rel.attach(image)
eliftype == 'attach_path':
attachment = get_attach(item)
if(attachment):
msg.attach(attachment)
else:
#print('type error')
pass
html = MIMEText(mailBody,'html','utf-8')
msg_alt.attach(html)
else:
return False
server = smtplib.SMTP()
#server.set_debuglevel(1)
try:
server.connect(host,25)
except:
print('connect fail')
try:
server.ehlo(user)
server.login(user,password)
print('login ok')
except:
print('login fail')
try:
server.sendmail(sender, to_list, str(msg))
server.close()
return True
exceptOSError:
print('OSError')
return False
except:
print('unexpect error')
return False
#新增圖片內容到正文
defget_image(image_path):
try:
fp = open(image_path,'rb')
except:
return None
image = MIMEImage(fp.read())
fp.close()
image.add_header( 'Content-ID' , '<'+image_path+'>' )
return image
#新增附件
defget_attach(attach_path):
try:
f = open(attach_path,'rb')
att = MIMEText(f.read(),'base64', 'utf-8')
f.close()
exceptFileNotFoundError:
print('FileNotFound')
return None
except:
print('unexpect error')
return None
att['Content-Type'] = 'application/octet-stream'
att['Content-Disposition'] = 'attachment; filename='+attach_path
return att
defanalysis(json_arg):
arg = json.loads(json_arg)
to_list = arg['to_list']
subject = arg['subject']
content = arg['content']
content_type = 'plain'
try:
content_type = arg['content_type']
except:
pass
return
deftest1():
recv = ['']
content = (('text','這不是垃圾郵件啊啊啊啊啊'),('attach_path','1.txt'))
arg1 = {'to_list':recv, 'subject':'test', 'content':content}
json_arg = json.dumps(arg1)
if(analysis(json_arg)):
print('send ok')
else:
print('send fail')
deftest2():
recv = ['']
html = '<a href="http://www.baidu.com">百度連結</a>'
content = (('html' ,'看圖'),('attach_path','1.txt'),('image_path','1.jpg'),('image_path','2.png'),('html',html)) #html的值不一定非要html程式碼,普通字串也行
arg2 = {'to_list':recv, 'subject':'test', 'content':content,'content_type':'html'}
json_arg = json.dumps(arg2)
if(analysis(json_arg)):
print('send ok')
else:
print('send fail')
if __name__ == '__main__':
test1()
test2()
'''
send_mail.py介面說明:
函式analysis(json_arg)只有1個引數,json_arg是json型別,元素有3-4個
4個元素的鍵依次是to_list,subject,content,content_type
(1)to_list是收件人列表,是列表型別,其中每個元素(至少1個元素)都是字串,對應一個郵箱地址
(2)subject是郵件標題,是字串型別
(3)content是元祖型別,每個元素(type,item)是郵件正文中的1個內容,
type是'text'或'html'或'attach_path'或'image_path',對應的item(都是字串)分別代表文字、html程式碼、附件名、圖片名(如果需要的話前面帶上路徑名)
(4)content_type是'plain'或'html',如果是'plain'(可以預設)那麼content是'text'或'attach_path',如果是'html'那麼content是'html'或'attach_path'或'image_path'
'''