In Internet-based applications, programs often need to send e-mails automatically. For example, a website registration system will send an email to confirm the registration when the user registers, and when the user forgets the login password, the password is retrieved by mail. The Smtplib module is a client implementation of the SMTP (Simple Mail Transfer Protocol) in Python. We can use the Smtplib module to easily send emails. The following example uses less than 10 lines of code to send an e-mail message:
- #coding =gbk
-
- import smtplib
-
- smtp = smtplib. SMTP ()
- smtp.connect (
- smtp.login (
- smtp.sendmail ( [email Protected] ', ' From: [email protected]/r/nto: [email protected]/r/nsubject: this is a email from python demo/r/n/r/njust for test ~_~ ')
- smtp.quit ()
This example is simple enough, ^_^! The classes and methods in the Stmplib module are described in detail below.
Smtplib. SMTP ([host[, port[, local_hostname[, timeout]])
The SMTP class constructor, which represents the connection to the SMTP server through which we can send instructions to the SMTP server to perform related operations such as logging in and sending mail. This class provides a number of methods, which are described below. All of its parameters are optional, where the host parameter represents the SMTP server hostname, the SMTP host in the example above is "smtp.yeah.net", the port represents the SMTP service, the default is 25, and if both parameters are provided when the SMTP object is created, The Connect method is called automatically at initialization time to connect to the server.
The Smtplib module also provides the Smtp_ssl class and the Lmtp class, and their operation is basically consistent with SMTP.
Smtplib. Methods that are provided by SMTP:
Smtp.set_debuglevel (Level)
Sets whether to debug mode. The default is false, which is non-debug mode, which means that no debug information is output.
Smtp.connect ([host[, Port]])
Connect to the specified SMTP server. The parameters represent Smpt hosts and ports, respectively. Note: You can also specify the port number (for example: SMPT.YEAH.NET:25) in the host parameter, so there is no need to give the port parameter.
Smtp.docmd (cmd[, argstring])
Sends instructions to the SMTP server. An optional parameter, argstring, represents the parameters of the directive. The following example simply sends instructions to the server by calling the DoCmd method to send the message (test pass on the Smtp.yeah.net mail server). Other mail servers have not tried):
- Import Smtplib, Base64, time
- UserName = base64.encodestring (' from '). Strip ()
- Password = base64.encodestring (' password '). Strip ()
- SMTP = Smtplib. SMTP ()
- Smtp.connect ("smtp.yeah.net:25")
- Print smtp.docmd (' helo ', ' from ')
- Print smtp.docmd (' auth login ')
- Print Smtp.docmd (userName)
- Print smtp.docmd (password)
- Print smtp.docmd (' mail from: ', ' <[email protected]> ')
- Print smtp.docmd (' rcpt to: ', ' <[email protected]> ')
- #data instruction indicates the contents of the message
- Print smtp.docmd (' data ')
- Print Smtp.docmd ("" from: [email protected]
- To: [Email protected]
- Subject:subject
- Email body
- .
- ‘‘‘)
- Smtp.quit ()
Smtp.helo ([hostname])
Use the "helo" directive to confirm the identity to the server. The equivalent of telling the SMTP server "who I am".
Smtp.has_extn (name)
Determines whether the specified name exists in the server mailing list. For security reasons, the SMTP server often blocks the directive.
Smtp.verify (Address)
Determines whether the specified e-mail address exists on the server. For security reasons, the SMTP server often blocks the directive.
Smtp.login (user, password)
Log on to the SMTP server. Almost all SMTP servers now have to allow messages to be sent after verifying that the user information is legitimate.
Smtp.sendmail (From_addr, To_addrs, msg[, Mail_options, Rcpt_options])
Send the message. Notice here that the third parameter, MSG, is a string that represents the message. We know that the mail is generally composed of the title, sender, recipient, mail content, attachments, etc., when sending mail, pay attention to the format of MSG. This format is the format defined in the SMTP protocol. In the above example, the value of MSG is:
- "From: [email protected]
- To: [Email protected]
- Subject:test
- Just for Test '
The meaning of this string means that the message sender is "[email protected]", the recipient is "[email protected]", the message is titled "Test" and the message is "just for test". Careful you may wonder: if the message to be sent is complex, including images, videos, attachments, etc., stitching strings in MIME format will be a hassle. Don't worry, Python has taken this into account, providing us with an email module that makes it easy to send messages with complex content like images, videos, attachments, and more. After the introduction of the Smtplib module, I will briefly introduce the basic use of the email module.
Smtp.quit ()
Disconnecting from the SMTP server is equivalent to sending a "quit" instruction.
e-mail and its related sub-modules
The Emial module is used to process mail messages, including MIME and other RFC 2822 -based message documents. Using these modules to define the contents of the message is very simple. Here 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 the text object.
Look at the above explanations may feel foggy, in fact, my understanding of SMTP, MIME is also very superficial. But most of the time, we just have to use it. Here's a simple example that shows how to use these classes to send messages with attachments:
#coding =GBK
- Import Smtplib, Mimetypes
- From Email.mime.text import Mimetext
- From Email.mime.multipart import Mimemultipart
- From Email.mime.image import mimeimage
- msg = Mimemultipart ()
- msg[' from '] = "[email protected]"
- msg[' to '] = ' [email protected] '
- msg[' Subject ' = ' email for tesing '
- #添加邮件内容
- txt = mimetext ("This is the message content ~ ~")
- Msg.attach (TXT)
- #添加二进制附件
- FileName = r' E:/pyqt4.rar '
- CType, encoding = Mimetypes.guess_type (fileName)
- If CType is none or encoding are not none:
- CType = ' Application/octet-stream '
- MainType, subtype = ctype.split ('/', 1)
- ATT1 = Mimeimage ((Lambda F: (F.read (), F.close ())) (Open (FileName, ' RB ')) [0], _subtype = subtype)
- Att1.add_header (' content-disposition ', ' attachment ', filename = filename)
- Msg.attach (ATT1)
- #发送邮件
- SMTP = Smtplib. SMTP ()
- Smtp.connect (' smtp.yeah.net:25 ')
- Smtp.login (' from ', ' password ')
- Smtp.sendmail (' [email protected] ', ' [email protected] ', msg.as_string ())
- Smtp.quit ()
- Print ' mail sent successfully '
is not very simple. Simple is beauty, with the least code to solve the problem, this is Python. For more information on Smtplib, please refer to the Python manual smtplib module.
Send the code for a simple message without attachments:
1 Import Smtplib
2 from Email.mime.text import Mimetext
3 from email. Mimemultipart Import Mimemultipart
4
5 def sendsimplemail (warning):
6 msg = mimetext (warning)
7 msg[' Subject ' = ' python first mail '
8 msg[' from '] = '[email protected]‘
9 Try:
SMTP = Smtplib. SMTP ()
Smtp.connect (R ' smtp.163.com ')
Smtp.login ('[email protected]', ' password ')
Smtp.sendmail ('[email protected]', [' [email protected] ', msg.as_string ())
Smtp.close ()
Except Exception, E:
Print E
17
if __name__ = = ' __main__ ':
Sendsimplemail (warning = "This is a warning!!!")
Python Mail send