The previous blog demonstrates how to send simple emails. This article demonstrates how to send various types of attachments.
The basic idea is to use mimemultipart to indicate that the email is composed of multiple parts and attach each part. If it is an attachment, add_header is added to the declaration of the attachment.
In python, the inheritance relationships of mime objects are as follows.
Mimebase
| -- Mimenonmultipart
| -- Mimeapplication
| -- Mimeaudio
| -- Mimeimage
| -- Mimemessage
| -- Mimetext
| -- Mimemultipart
Generally, mimebase is not used, but its inheritance class is directly used. The mimemultipart has the attach method, while the mimenonmultipart does not. It can only be attach.
Mime has many types. This is a little tricky. If the attachment is in the image format, I want to use mimeimage. If it is audio, I want to use mimeaudio. If it is word or Excel, I don't know which MIME type to use. Google should check it.
The lazy way isNo matter what type of attachments, mimeapplication is used. The default subtype of mimeapplication is application/octet-stream.
Application/octet-stream indicates "this is a binary file and you want to know how to handle it". Then, the client, such as QQ mail, guesses Based on the file extension after receiving this declaration.
The code below.
Assume that there are four files, foo.xlsx/foo.jpg/foo.pdf.
Import smtplibfrom email. mime. multipart import mimemultipartfrom email. mime. text import mimetextfrom email. mime. application import mimeapplication_user = "sigeken@qq.com" _ Pwd = "***" _ to = "402363522@qq.com" # As shown in the name, multipart is divided into multiple parts MSG = mimemultipart () MSG ["subject"] = "Don't panic" MSG ["from"] = _ usermsg ["to"] = _ to # --- this is the text part --- part = mimetext ("disguise, ") MSG. attach (Part) # --- this is the attachment part --- # XLSX type attachment part = mimeapplication(open('foo.xlsx ', 'rb '). read () part. add_header ('content-disposition', 'attachment', filename = "foo.xlsx") MSG. attach (Part) # JPG attachment part = mimeapplication(open('foo.jpg ', 'rb '). read () part. add_header ('content-disposition', 'attachment ', filename = "foo.jpg") MSG. attach (Part) # PDF attachment part = mimeapplication(open('fooket', 'rb '). read () part. add_header ('content-disposition', 'attachment', filename = "footings") MSG. attach (Part) # MP3 attachment part = mimeapplication(open('fooket', 'rb '). read () part. add_header ('content-disposition', 'attachment', filename = "footings") MSG. attach (Part) S = smtplib. SMTP ("smtp.qq.com", timeout = 30) # connect to the SMTP mail server. The default port is 25s. login (_ User, _ PWD) # log on to the server S. sendmail (_ User, _ to, MSG. as_string () # Send email S. close ()