The basic idea is to use Mimemultipart to indicate that the message is composed of several parts and then attach the various parts. If it is an attachment, the Add_header adds a statement to the attachment.
In Python, the inheritance relationships of these MIME objects are as follows.
Mimebase
|--Mimenonmultipart
|--Mimeapplication
|--Mimeaudio
|--Mimeimage
|--MimeMessage
|--Mimetext
|--Mimemultipart
In general, Mimebase is not used, but it is used directly by its inheriting classes. Mimemultipart has attach method, and Mimenonmultipart is not, can only be attach.
There are many types of mime, this slightly troublesome, if the attachment is a picture format, I want to use mimeimage, if it is audio, to use Mimeaudio, if it is Word, Excel, I do not know what kind of mime type, to Google to check.
The most lazy way is, no matter what type of attachment, use the mimeapplication,mimeapplication default subtype is Application/octet-stream.
Application/octet-stream that "This is a binary file, I hope you know how to deal with", and then the client, such as QQ mailbox, after receiving this statement, will be based on the file name extension to guess.
The code below.
Suppose there are foo.xlsx/foo.jpg/foo.pdf/foo.mp3 these 4 files in the current directory.
Import smtplib from Email.mime.multipart import Mimemultipart to Email.mime.text import Mimetext from Email.mime.app Lication import Mimeapplication _user = "sigeken@qq.com" _PWD = "* * *" _to = "402363522@qq.com" #如名字所示Multipart就是分多 Part msg = Mimemultipart () msg["Subject"] = "don ' t Panic" msg["from"] = _user msg["to"] = _to #---This is the literal part---par t = Mimetext ("disguise, Unscrupulous") Msg.attach (part) #---This is the attachment section---#xlsx类型附件 parts = mimeapplication (open (' foo.xlsx ', ' RB '). Rea D ()) Part.add_header (' content-disposition ', ' attachment ', filename= "foo.xlsx") Msg.attach (part) #jpg类型附件 part = MIM EApplication (Open (' foo.jpg ', ' RB '). Read ()) Part.add_header (' content-disposition ', ' attachment ', filename= "foo.jpg" Msg.attach (part) #pdf类型附件 part = mimeapplication (open (' foo.pdf ', ' RB '). Read ()) Part.add_header (' Content-dispositio
n ', ' attachment ', filename= "Foo.pdf") Msg.attach (part) #mp3类型附件 part = mimeapplication (open (' Foo.mp3 ', ' RB '). Read ()) Part.add_header (' Content-disposItion ', ' attachment ', filename= "Foo.mp3") Msg.attach (part) s = smtplib. SMTP ("smtp.qq.com", timeout=30) #连接smtp邮件服务器, the port defaults to S.login (_user, _pwd) #登陆服务器 s.sendmail (_user, _to, msg.as_string (
) #发送邮件 S.close ()