Implement a simple tutorial with Python to send a mail program with attachments

  • 2020-05-07 19:57:30
  • OfStack

The basic idea is to use MIMEMultipart to indicate that the message is made up of multiple parts, and then attach parts. If it is an attachment, add_header adds the declaration of the attachment.
In python, the inheritance relationship of these objects in MIME is as follows.
MIMEBase
      |-- MIMENonMultipart
              |-- MIMEApplication
              |-- MIMEAudio
              |-- MIMEImage
              |-- MIMEMessage
              |-- MIMEText
      |-- MIMEMultipart
1 generally speaking, MIMEBase is not used, but its inherited classes are used directly. MIMEMultipart has the attach method, while MIMENonMultipart does not and can only be attach.
There are many types of MIME, this is a little troublesome, if the attachment is a picture format, I will use MIMEImage, if it is audio, I will use MIMEAudio, if it is word, excel, I do not know which type of MIME to use, I have to go to google to check.
The laziest way to do this is to use MIMEApplication for any type of attachment. The default subtype of MIMEApplication is application/ octet-stream.
application/ octet-stream says, "this is a binary file, I hope you know what to do with it." then the client, such as qq mailbox, receives this statement and guesses based on the file extension.

Here is the code.
Assume the current directory have foo. xlsx/foo jpg/foo pdf/foo mp3 these four files.
 


import smtplib 
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email.mime.application import MIMEApplication 
_user = "sigeken@qq.com" 
_pwd = "***" 
_to  = "402363522@qq.com" 
  
# As the name suggests Multipart It's just divided into parts  
msg = MIMEMultipart() 
msg["Subject"] = "don't panic" 
msg["From"]  = _user 
msg["To"]   = _to 
  
#--- This is the text part --- 
part = MIMEText(" All is fair in disguise ") 
msg.attach(part) 
  
#--- This is the attachment --- 
#xlsx Type of attachment  
part = MIMEApplication(open('foo.xlsx','rb').read()) 
part.add_header('Content-Disposition', 'attachment', filename="foo.xlsx") 
msg.attach(part) 
  
#jpg Type of attachment  
part = MIMEApplication(open('foo.jpg','rb').read()) 
part.add_header('Content-Disposition', 'attachment', filename="foo.jpg") 
msg.attach(part) 
  
#pdf Type of attachment  
part = MIMEApplication(open('foo.pdf','rb').read()) 
part.add_header('Content-Disposition', 'attachment', filename="foo.pdf") 
msg.attach(part) 
  
#mp3 Type of attachment  
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)# The connection smtp Mail server , Port default is 25 
s.login(_user, _pwd)# Login server  
s.sendmail(_user, _to, msg.as_string())# Send E-mail  
s.close()


Related articles: