Objective
Recently, some small partners, in the mailbox thing, small made up to toss a bit! summed up some dry goods, share with you! Come on, hold your thighs, I'm going to drive!
The basic idea is to use Mimemultipart to indicate that the message is made up of multiple parts, and then attach each part. If it is an attachment, Add_header joins the declaration of the attachment.
In Python, the following are the inheritance relationships for MIME objects.
Mimebase
|--Mimenonmultipart
|--mimeapplication
|--Mimeaudio
|--Mimeimage
|--MimeMessage
|--Mimetext
|--Mimemultipart
In general, Mimebase is not used, but it's inherited classes are used directly. Mimemultipart has attach method, and Mimenonmultipart not, can only be attach.
MIME has a lot of types, 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 which MIME type to use, Google to check.
The most lazy way is to use the mimeapplication,mimeapplication default subtype, regardless of the type of attachment, 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.
Nonsense not much to say, on the code:
#coding =utf-8
Import Smtplib
From Email.mime.text import Mimetext
From email.mime.application import mimeapplication
From Email.mime.multipart import Mimemultipart
_user = "9759***[email protected]"
_pwd = "VAZ*****YZABEBF" #服务器授权码
_to = "224***[email protected]"
msg = Mimemultipart ()
msg["Subject"] = "Test It" #邮件标题
Msg["from"] = _user
Msg["to"] = _to
Text section
Part = Mimetext ("Hello")
Msg.attach (part)
Accessories section
XLSX type Attachment
Part = mimeapplication (open (' D:\Tyrone.xlsx ', ' RB '). Read ())
Part.add_header (' content-disposition ', ' attachment ', filename= "tyrone.xlsx") #这边的filename随便写, completely look at your mood, but the suffix format must be unified
Msg.attach (part)
JPG type attachment (PNG type and JPG)
Part = mimeapplication (open (' D:\Tyrone.jpg ', ' RB '). Read ())
Part.add_header (' content-disposition ', ' attachment ', filename= "tyrone.jpg")
Msg.attach (part)
PDF Type Attachments
Part = mimeapplication (open (' D:\Tyrone.pdf ', ' RB '). Read ())
Part.add_header (' content-disposition ', ' attachment ', filename= "Tyrone.pdf")
Msg.attach (part)
MP3 Type attachment
Part = mimeapplication (open (' D:\Tyrone.mp3 ', ' RB '). Read ())
Part.add_header (' content-disposition ', ' attachment ', filename= "Tyrone.mp3")
Msg.attach (part)
Try
s = smtplib. Smtp_ssl ("smtp.qq.com", 465) #发件邮箱的服务器以及端口
S.login (_user, _pwd)
S.sendmail (user, _to, msg.asstring ())
S.quit ()
Print "Perfect!"
Except Smtplib. Smtpexception,e:
Print "Failed! "
Selenium+python Automation 22-Send various types of attachment messages