Send emails in Python and send emails in python
It is quite interesting to use Python to send emails. python provides us with such a module to conveniently send emails.
1. SMTP is similar to HTTP. There are some related information in the header, such as content-type and encoding. Message is a base class. You can use dictionary ing to read and set the values of the options in the head. MIMEText, MIMEImage, MIMEAudio, and other MIME types are inherited from MIMEBase, and MIMEBase is inherited from Message. None of them define their own methods, and they all use Message. MIMEMultipart can be used to add multiple MIME files through attach. So use it to add attachments
2. Different types of attachment files are different. The header contains the Content-Disposition option, which allows you to set the file type. To upload different file types, let python identify the file type through mimestypes. guess_type ()
3. When reading a binary file, the open mode should be "rb", because it may have the same bytes as the EOF encoding. In this way, python finds the end of the file and stops reading.
4. lambda: Define a function at any time to avoid the definition of many single-row functions.
See the code below.
_ Author _ = 'mrchen' import smtplib, mimetypesfrom email. mime. text import MIMETextfrom email. mime. multipart import MIMEMultipartfrom email. mime. image import MIMEImagemsg = MIMEMultipart ('alternative ') msg ['from'] = "xxxxxxxx@163.com" msg ['to'] = 'xxxxxxxx @ qq.com 'msg ['subobject'] = 'email for testing' # add mail content text = MIMEText ('content ') msg. attach (text) # Add a binary attachment fileName = r'c: \ Users \ a \ Pictures \ lovewallpaper \ 001.jpg '# select your own file fileType, encoding = mimetypes. guess_type (fileName) if fileType is None or encoding is not None: fileType = 'application/octet-stream' print (fileType, encoding) maintype, subtype = fileType. split ('/', 1) att1 = MIMEImage (lambda f: (f. read (), f. close () (open (fileName, 'rb') [0], _ subtype = subtype) # Remove the path from the sent file name, there is no need for others to see their own file path att1.add _ header ('content-disposition', 'attachment ', filename = fileName [fileName. rfind ('\') + 1:]) msg. attach (att1) server = smtplib. SMTP () server. connect ('smtp .163.com ') # The smtp server address of the 163 mailbox is server. login ('xxxxxxxx @ 163.com ', 'xxxxxxxxxx') # enter the email user name and password server. set_debuglevel (1) server. sendmail ('xxxxxxxx @ 163.com ', 'xxxxxxxx @ qq.com', msg. as_string () server. quit () print ('sent successfully ')
Which of the following functions are available in the SMTP class?
Smtplib. SMTP ([host [, port [, local_hostname [, timeout])
SMTP constructor indicates the connection to the SMTP server. Through this connection, we can send commands to the smtp server to execute relevant operations (such as login and email sending ). This class provides many methods, which will be described below. All its parameters are optional. The host parameter indicates the smtp server host name. In the preceding example, the smtp host is "smtp.yeah.net"; port indicates the smtp service port. The default value is 25; if the two parameters are provided when an SMTP object is created, the connect method is automatically called during initialization to connect to the server.
The smtplib module also provides SMTP_SSL and LMTP classes, which are basically the same as SMTP.
SMTP. set_debuglevel (level)
Set whether to use the debugging mode. The default value is False, that is, non-debug mode, indicating that no debugging information is output.
SMTP. connect ([host [, port])
Connect to the specified smtp server. The parameters represent the smpt host and port respectively. Note: You can also specify the port number (for example, smpt.yeah.net: 25) in the host parameter so that the port parameter is unnecessary. The default port number is 25.
SMTP.doc md (cmd [, argstring])
Send commands to the smtp server. The optional parameter argstring indicates the command parameter.
SMTP. helo ([hostname])
Use the "helo" command to confirm the identity of the server. It is equivalent to telling the smtp server "who I am ".
SMTP. has_extn (name)
Determines whether the specified name exists in the server email list. For security reasons, smtp servers often block this command.
SMTP. verify (address)
Determines whether the specified email address exists on the server. For security reasons, smtp servers often block this command.
SMTP. login (user, password)
Log on to the smtp server. Currently, almost all smtp servers must verify that the user information is valid before sending emails.
SMTP. sendmail (from_addr, to_addrs, msg [, mail_options, rcpt_options])
Send an email. Note that the third parameter, msg is a string, indicating the mail. We know that an email generally consists of the title, sender, recipient, email content, attachments, etc. When sending an email, pay attention to the msg Format. This format is defined in the smtp protocol.
If the content of the email to be sent is complex and contains images, videos, attachments, and other content, splicing strings in MIME format will be very troublesome. Don't worry. python has taken this into consideration. It provides us with an email module that can easily send emails with images, videos, attachments, and other complex content. After introducing the smtplib module, I will briefly introduce the basic use of the email module.
SMTP. quit ()
Disconnecting the smtp server is equivalent to sending the "quit" command.
The following describes the email module.
The emial module is used to process mail messages, including MIME and other RFC 2822-based message documents. Using these modules to define mail content is very simple. Below are some common classes:
Class email. mime. multipart. MIMEMultipart: a collection of multiple MIME objects.
Class email. mime. audio. MIMEAudio: MIME audio object.
Class email. mime. image. MIMEImage: MIME binary file object.
Class email. mime. text. MIMEText: MIME text object.
Supplement:
To put it down, the MIME (Multipurpose Internet Mail Extensions) multi-purpose Internet Mail extended type is a type of method that allows an application to open a file with a certain extension, when a file with the extension is accessed, the browser automatically opens the file with the specified application. It is used to specify custom client file names and open media files.
When the output result is sent to the browser, the browser must start the local application to process the output document. This can be done through multiple types of MIME (multi-function Internet Mail Extension protocol. In HTTP, the MIME Type is defined in the Content-Type header.
For example, you need to transfer a Microsoft Excel file to the client. The MIME type is "application/vnd. ms-excel ". In most cases, this file is then transmitted to Execl for processing (assuming we set Execl to an application that handles special MIME types ). In ASP, the method for setting the MIME type is through the ContentType attribute of the Response object.
Multimedia file format MIME
In the earliest HTTP protocol, there was no additional data type information. All transmitted data was interpreted by the client program as HTML documents in the hypertext markup language. to support multimedia data types, the MIME data type information appended to the document is used in the HTTP protocol to identify the data type.
MIME is a multi-purpose Internet Mail Extension designed to attach multimedia data to an email so that the email client can process it based on its type. However, when it is supported by the HTTP protocol, its meaning becomes more significant. It makes HTTP transmitted not only plain text, but also rich and colorful.
Each MIME type consists of two parts. The front part is a large data type, such as audio, image, and so on. The latter part defines a specific type.
Common MIME types
Hypertext markup language text .html, .html text/html
Common text. txt text/plain
RTF text. rtfapplication/rtf
GIF image. gif image/gif
JPEG image .ipeg,.jpg image/jpeg
Au audio file. au audio/basic
MIDI music files mid,. midiaudio/midi, audio/x-midi
RealAudio music file. ra,. ramaudio/x-pn-realaudio
MPEG file. mpg,. mpegvideo/mpeg
AVI file. avivideo/x-msvideo
GZIP file. gzapplication/x-gzip
TAR file. tarapplication/x-tar
How can I send emails through python?
Generally, it is better to have an smtp server. For example, if you register an email address in 163, you can use smtplib to send the email address. The following is an example:
#-*-Coding: utf8 -*-
Import smtplib
Import email
Import mimetypes
From email. MIMEMultipart import MIMEMultipart
From email. mime. text import MIMEText
Mail_host = "smtp.163.com"
Mail_user = "yourusername"
Mail_pass = "yourpassword"
Mail_postfix = "mail.163.com"
Def sendmail (to_list, sub, con ):
"Send email
"""
# Translation
Me = mail_user + "<" + mail_user + "@" + mail_postfix + ">"
Msg = MIMEMultipart ('related ')
Msg ['subobject'] = email. Header. Header (sub, 'utf-8 ')
Msg ['from'] = me
Msg ['to'] = ";". join (to_list)
Msg. preamble = 'this is a multi-part message in MIME format .'
MsgAlternative = MIMEMultipart ('alternative ')
MsgText = MIMEText (con, 'plain ', 'utf-8 ')
MsgAlternative. attach (msgText)
Msg. attach (msgAlternative)
Try:
S = smtplib. SMTP ()
S. connect (mail_host)
S. login (mail_user, mail_pass)
S. sendmail (me, to_list, msg. as_string ())
S. quit ()
Except t Exception, e:
Return False
Return True
If _ name _ = '_ main __':
If sendmail (['test @ test.com '], "test", "test "):
Print "Success! "
Else:
Print "Fail! "
If it is not directly sent by the email system, it is usually thrown as a spam, so let's do it .... Remaining full text>
How does python send emails?
It should be about the security authentication protocol. Try to combine it. I tried Netease's mailbox a long time ago. The verification method at that time, remember 2 + 3. I forgot the details. It seems that the smtp library was weak at the time, and the message package program was written by myself. You can also decode Chinese titles by yourself.