#coding=utf8
import smtplib
import mimetypes
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
def SendMail():
msg = MIMEMultipart()
'''不使用Header轉換郵件頭部會亂碼'''
msg['From'] = ("%s<%s>") % (Header('管理員','utf-8'),'[email protected]')
To = ["[email protected]","[email protected]"]
msg['To'] = ','.join(To)
msg['Subject'] = Header('附件郵件','utf-8')
#text: 文本郵件會與html郵件衝突,導致覆蓋(二選一)
txt = MIMEText("啦啦啦德瑪西亞",'plain','utf-8')
msg.attach(txt)
#html + 圖片 html郵件會與文本郵件衝突(二選一)
'''html 也可單獨發送html'''
content = '''<!DOCTYPE html><html><font size="5" color="red">紅色的</font>
<p><font size="3" color="red">This is test Email ~_~!</font></p> <img src="cid:image1"></html>'''
html = MIMEText(content, 'html', 'utf-8')
msg.attach(html)
'''也可以不嵌入到上面的html中,單獨以附件的方式發送圖片'''
file1 = "2407531.jpg"
with open(file1,'rb') as f:
content = f.read()
image = MIMEImage(content)
image.add_header('Content-ID','<image1>')
msg.attach(image)
#附件
file2 = 'APScheduler-2.0.3.tar.gz'
with open(file2,'rb') as f:
content = f.read()
Attachments = MIMEText(content, 'base64', 'utf-8')
Attachments["Content-Type"] = 'application/octet-stream'
Attachments["Content-Disposition"] = 'attachment; filename="APScheduler-2.0.3.tar.gz"'
msg.attach(Attachments)
server = smtplib.SMTP()
#也可以在上一輩初始化的時候連接
server.connect('smtp.163.com')
server.login('[email protected]','password')
#msg['From']:可以爲發件郵箱,也可爲發件郵箱+別名
#To: 可以爲字符串或列表,爲字符串時默認爲單個郵箱,羣發時爲列表
server.sendmail(msg['From'],To,msg.as_string())
print msg.as_string()
server.quit()
if __name__ == "__main__":
SendMail()
python 發送郵件
前陣子改了下郵件系統一些BUG,順便了解下python的郵件模塊
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.