Python module learning-smtplib mail sending

Source: Internet
Author: User
Document directory
  • SMTP. set_debuglevel (level)
  • SMTP. Connect ([host [, port])
  • Smtp.doc MD (CMD [, argstring])
  • SMTP. Helo ([hostname])
  • SMTP. has_extn (name)
  • SMTP. Verify (address)
  • SMTP. login (user, password)
  • SMTP. Sendmail (from_addr, to_addrs, MSG [, mail_options, rcpt_options])
  • SMTP. Quit ()

In Internet-based applications, applications often need to automatically send emails. For example, the registration system of a website will send an email to confirm registration when the user registers. When the user forgets the login password, it will retrieve the password through the email. The smtplib module is the client implementation of SMTP (Simple Mail Transfer Protocol) in Python. We can use the smtplib module to send emails easily. The following example uses less than 10 lines of code to send an email:# Coding = GBK </P> <p> Import smtplib </P> <p> SMTP = smtplib. SMTP () <br/> SMTP. connect ("smtp.yeah.net", "25") <br/> SMTP. login ('username', 'Password') <br/> SMTP. sendmail ('from @ yeah.net ',' to @ 21cn.com ',' from: from@yeah.net/R/nto: to@21cn.com/R/nsubject: this is a email from Python demo/R/n/R/njust for test ~ _~ ') <Br/> SMTP. Quit ()

This example is simple enough. ^_^! The following describes in detail the classes and methods in the pluplib module.

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.
Methods provided by smtplib. 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.

Smtp.doc MD (CMD [, argstring])

Send commands to the SMTP server. The optional parameter argstring indicates the command parameter. The following example uses the docmd method to send commands to the server to send emails (experiment passed on the smtp.yeah.net email server. Other email servers have not tried ):

Import smtplib, base64, time <br/> username = base64.encodestring ('from '). strip () <br/> Password = base64.encodestring ('Password '). strip () <br/> SMTP = smtplib. SMTP () <br/> SMTP. connect ("smtp.yeah.net: 25") <br/> Print smtp.doc MD ('HELO', 'from') <br/> Print smtp.doc MD ('auth login ') <br/> Print smtp.doc MD (username) <br/> Print smtp.doc MD (password) <br/> Print smtp.doc MD ('mail from: ',' <from@yeah.net> ') <br/> Print smtp.doc MD ('RCPT TO: ',' <from@yeah.net> ') <br/> # The Data command indicates the mail content <br/> Print smtp.doc MD ('data') <br/> Print smtp.doc MD (''' from: from@yeah.net <br/> to: from@yeah.net <br/> subject: Subject <br/> email body <br/>. <br/> ''') <br/> SMTP. quit ()

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. In the preceding example, the MSG value is:

''' From: from@yeah.net <br/> to: to@21cn.com <br/> subject: Test </P> <p> just for test '''

 

This string indicates that the mail sender is "from@yeah.net", the recipient is "to@21cn.com", the mail title is "test", and the mail content is "just for test ". If you are careful, you may have questions: if the content of the email to be sent is complex, including pictures, videos, attachments, and other content, concatenate strings in MIME format, it 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.

Email and Its Related submodules

The emial module is used to process mail messages, including mime and otherRFC 2822. Using these modules to define mail content is very simple. Below are some common classes:

ClassEmail. Mime. multipart. Mimemultipart: a collection of multiple MIME objects.

ClassEmail. Mime. audio. Mimeaudio: MIME audio object.

ClassEmail. Mime. image. Mimeimage: MIME binary file object.

ClassEmail. Mime. Text. Mimetext: MIME Text object.

Looking at the above explanation, I may feel confused. In fact, I have a superficial understanding of SMTP and mime. But most of the time, we only need to use it. The following is a simple example to demonstrate how to use these classes to send emails with attachments:# Coding = GBK <br/> Import smtplib, mimetypes <br/> from email. mime. text import mimetext <br/> from email. mime. multipart import mimemultipart <br/> from email. mime. image import mimeimage </P> <p> MSG = mimemultipart () <br/> MSG ['from'] = "from@yeah.net" <br/> MSG ['to'] = 'to @ 21cn.com' <br/> MSG ['subobject'] = 'email for tesing' </P> <p> # Add email content <br/> TXT = mimetext ("this is the email content ~~ ") <Br/> MSG. attach (txt) </P> <p> # Add a binary attachment <br/> filename = r'e:/pyqt4.rar '<br/> ctype, encoding = mimetypes. guess_type (filename) <br/> If ctype is none or encoding is not none: <br/> ctype = 'application/octet-stream' <br/> maintype, subtype = ctype. split ('/', 1) <br/> att1 = mimeimage (lambda F: (F. read (), F. close () (open (filename, 'rb') [0], _ subtype = subtype) <br/> att1.add _ header ('content-disposition ', 'attachment', filename = filename) <br/> MSG. attach (att1) </P> <p> # send an email <br/> SMTP = smtplib. SMTP () <br/> SMTP. connect ('smtp .yeah.net: 25') <br/> SMTP. login ('from', 'Password') <br/> SMTP. sendmail ('from @ yeah.net ',' to @ 21cn.com ', MSG. as_string () <br/> SMTP. quit () <br/> Print 'email sent successfully'

Is it easy. Simple is beautiful, and the problem is solved with the least code. This is Python. For more information about smtplib, see the python manual smtplib module.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.