Python and Smtp__python

Source: Internet
Author: User
Tags base64 imap rfc all mail

SMTP (Simple Mail Transfer Protocol)
The message transfer agent (mail Transfer AGENT,MTA) program uses the SMTP protocol to send e-mail to the recipient's mail server. The SMTP protocol can only be used to send messages and not to receive messages. Most mail-sending servers (outgoing mail server) use the SMTP protocol. The default TCP port number for the SMTP protocol is 25.

An important feature of the SMTP protocol is its ability to relay mail. It works in two cases: one is that e-mail is transferred from the client to the server, and the other is transferred from one server to another server.

POP3 (Post Office Protocol) & IMAP (Internet message Access Protocol)
POP protocols and IMAP protocols are the two most common protocols used for mail reception. Almost all mail clients and servers support both protocols.
The POP3 protocol provides users with a simple, standard way to access mailboxes and obtain e-mail. Email clients using the POP3 protocol typically work by connecting to the server, getting all the information and saving it on the user host, removing the messages from the server, and then disconnecting. The default TCP port number for the POP3 protocol is 110.

The IMAP protocol also provides a convenient mail download service that allows users to read offline. An e-mail client using an IMAP protocol usually keeps the information on the server until the user explicitly deletes it. This feature allows multiple clients to manage a single mailbox at the same time. The IMAP protocol provides a summary browsing feature that allows users to decide whether to download a message after they have read all the time, subject, sender, size, etc. The default TCP port number for the IMAP protocol is 143.
message Format (RFC 2822)
Each message has two parts: the message header and the body of the message, which are separated by a blank line.
The header of each field (field) includes two parts: The field name and the field value, separated by a colon. There are two fields to note: From and Sender fields. The From field indicates the author of the message, and the sender field indicates the sender of the message. If the From field contains more than one author, you must specify the sender field, and if the From field has only one author and the author and sender are the same, then the sender field should not be used, otherwise the From field and the sender field should be used concurrently.
The message body contains the contents of the message, and its type is indicated by the Content-type field of the message header. In the message format defined in RFC 2822, the message body is simply an ASCII-encoded sequence of characters.
MIME (Multipurpose Internet Mail Extensions) (RFC 1341)

MIME extended message format to support non-ASCII encoded text, non-text attachments, and mail bodies that contain multiple parts (multi-part).
  

Let's start with a brief introduction to Python's Smtplib module:

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 landing, 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 host name, and the SMTP host in the example above is "smtp.yeah.net"; Port represents the ports of the SMTP service, the default is 25; If you provided these two parameters when you created the SMTP object, The Connect method is automatically invoked at initialization time to connect to the server.
The Smtplib module also provides SMTP_SSL classes and LMTP classes, which are basically consistent with SMTP.
Smtplib. Methods provided by SMTP:

Smtp.set_debuglevel (level)
Sets whether the is debug mode. The default is false, which is not debug mode, which means that no debugging information is exported.

Smtp.connect ([host[, Port]])
Connects to the specified SMTP server. The parameters represent Smpt hosts and ports, respectively. Note: You can also specify a port number (such as: SMPT.YEAH.NET:25) in the host parameter, so there is no need to give the port parameter.

smtp.docmd (cmd[, argstring])
Send instructions to the SMTP server. An optional parameter argstring a parameter representing the instruction. 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). No other mail server has tried it):
Common instructions are:
HELO identify the user identity to the server
Mail initiate message transfer mail from:
RCPT identifies a single recipient of the message; often after the mail command, there can be multiple RCPT to:
Data after a single or multiple RCPT command indicates that all message recipients have identified and initialized the data transfer to. End
VRFY is used to verify that the specified user/mailbox exists or that the server often prohibits this command for security reasons
EXPN Verify that a given mailbox list exists, and that the expanded mailbox list is often disabled
Help query server What commands are supported
NOOP no action, server should respond OK
QUIT End Session
RSET reset session, current transfer canceled
Mail from specify Sender address
RCPT to specified recipient address
Smtp.helo ([hostname])
Use the "helo" directive to confirm identities 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 tends to block the directive.

smtp.verify (address)
Determines whether the specified mail address exists on the server. For security reasons, the SMTP server tends to block the directive.

smtp.login (user, password)
Log on to the SMTP server. Almost all SMTP servers now have to verify that the user information is legitimate before they are allowed to send mail.

Smtp.sendmail (from_addr, To_addrs, msg[, Mail_options, rcpt_options])
Send the message. Here's the third argument, MSG is a string that represents the message. We know that the mail generally by the title, sender, recipient, email content, attachments, etc. constitute, send the message, pay attention to the format of MSG
  

If you want to carry an attachment in a message, use HTML to write a message, attach a picture, and so on, you need to use the email module and its child modules. Here's a look at email packets, which are used to manage email messages, including MIME and other RFC 2822-based message formats. The main feature of an email packet is that it is a separate module to parse and generate the email information inside it.

A MIME message consists of a message header and a message body, in which the message header and the message body are part of the message. The message header is separated from the message body by a blank line.

Message headers contain important information such as the sender, recipient, subject, Time, MIME version, type of message content, and so on. Each piece of information is called a domain, followed by the domain name ":" and the content of the information composition, can be a row, longer can occupy more than one line. The first line of the field must be written "head", which means that the left side cannot have white space characters (spaces and tabs); the continuation line must begin with a blank character, and the first whitespace character is not intrinsic to the information itself.

The message body contains the contents of the message, and its type is indicated by the "Content-type" field of the message header. The most common types are text/plain (plain text) and text/html (hypertext). The body of the message is divided into segments, each with a segment header and a section body, separated by a blank line between the two parts. There are three common types of multipart: multipart/mixed, multipart/related and multipart/alternative.
Mainly to see Email.mime, in the mail to carry accessories, pictures, audio, the main use of the module. Typically, you create a Message object structure by parsing a file or a piece of text, or you can build a message structure from scratch, in fact, you can append a new message object to an existing message structure. You can create an object structure by creating an instance of the message, and then append the attachment and header information to the structure. The email package provides subclasses that make the operation easy.

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.

Here is the code that sends the message in plain text with smpt:

Import Smtplib from
email.mime.text import Mimetext to
email.header import header from
email.utils import Commaspace,formatdate


sender = ' xxxxxx@qq.com '
receiver = ' xxxxxx@qq.com ' subject
= ' Hahahaha
' SmtpServer = ' smtp.qq.com '
username = ' xxxxxx@qq.com '
password = ' xxxxxx '

msg = Mimetext ("You ' re I baby!", ' Plain ', ' utf-8 ')
msg[' Subject '] = Header (Subject, ' utf-8 ') #不写这个Header也是对的 msg[' Subject '].append (' Gaolee ')
, ' Utf-8 ')
msg[' from '] =sender# the sender who does not write the message does not display the equivalent of anonymous
msg[' to ' = receiver
#msg [' to '] = Commaspace.join (receiver) #以逗号分割receiver
#msg [' Date ']=formatdate (localtime=true)
smtp = Smtplib. SMTP (' smtp.qq.com ')
#smtp. Connect (' smtp.163.com ')
smtp.set_debuglevel (1) #打印整个过程中的信息
Smtp.login ( Username, password) #登录
smtp.sendmail (sender, receiver, msg.as_string ())
smtp.quit ()

Here is an explanation of the header's purpose (excerpted from the official document):


The role of Formatdata:

The above content can also be implemented directly with DoCmd:

Import smtplib
Import base64

sender= ' upc_dip@163.com '
receiver= '
acprime@163.com ' username= Base64.encodestring (b ' upc_dip@163.com ')
password=base64.encodestring (b ' upc_cs ')

smtp=smtplib. SMTP (' smtp.163.com ')
smtp.set_debuglevel (1)
smtp.docmd (' EHLO server ')
smtp.docmd (' AUTH LOGIN '
) Smtp.send (username)
smtp.send (password)
smtp.docmd (' MAIL from:<%s> '% sender)
smtp.docmd (' RCPT to:<%s> '% receiver)
smtp.docmd (' DATA ')
smtp.send (' test ')
smtp.send ('. '
) Smtp.quit ()

Note that username and password are going to use base64 encoding.

send a message in HTML text form:

msg = Mimetext ("

As you can see from the above, it can be changed by Mimetext parameters to distinguish the different message bodies.

mimeimage send picture mail:

F=open (' 12072113.JPG ', ' RB ')
Msgimage=mimeimage (F.read ())
f.close ()
msgimage[' from ']=sender
msgimage[' to ']=receiver
msgimage[' Subject ']=header (' Image ')

smtp=smtplib. SMTP (' smtp.163.com ')
smtp.login (Username,password)
Smtp.sendmail (sender,receiver,msgimage.as_string ( ))
Smtp.quit ()

So if I want to embed images in HTML, which is to relate them, how to:

Msgroot=mimemultipart (' related ')
msgroot[' from ']=sender
msgroot[' to ']=receiver
msgroot[' Subject ' Header (' Image ')

msgtext=mimetext (' <b>some <i>HTML</i> text</b> and an image.<br> <br>good! ', ' html ', ' Utf-8 ' Msgroot.attach
(msgtext)

f=open (' 12072113. JPG ', ' RB ')
Msgimage=mimeimage (F.read ())
msgimage.add_header (' Content-id ', ' <image>
') Msgroot.attach (msgimage)
f.close ()

smtp=smtplib. SMTP (' smtp.163.com ')
smtp.login (Username,password)
Smtp.sendmail (sender,receiver,msgroot.as_string () )
Smtp.quit ()

to send a message with an attachment:
The steps are as follows:
1. Construct the Mimemultipart object as the root container
2. Constructs the Mimetext object as the message displays the content and attaches to the root container
3. Constructs the Mimebase object as the file attachment content and attaches to the root container
A. Read the contents of the file and format it
B. Setting up attachment headers
4. Set Root Container properties
5. Fully formatted text
6. Send mail with SMTP

Import smtplib from Email.mime.text import mimetext to Email.header Import header from email.utils import commaspace,for Matdate from email.mime.image import mimeimage to Email.mime.multipart import mimemultipart,mimebase from email import e Ncoders import OS import mimetypes mailserver= ' smtp.163.com ' sender = ' upc_dip@163.com ' receiver = ' acprime@163.com ' subj ECT = ' hahahaha ' smtpserver = ' smtp.163.com ' username = ' upc_dip@163.com ' password = ' upc_cs ' file= '
Etup.1398305031.exe ' # constructs Mimemultipart object as root container Msgroot=mimemultipart () msgroot[' from ']=sender msgroot[' to ']=receiver msgroot[' Subject ']=header (' Image ') # constructs the Mimetext object as the message display and attaches to the root container text=mimetext ("This's My Downloads", ' plain ', ' Utf-8 ') Msgroot.attach (text) #测试识别文件类型: Mimetypes.guess_type (file_name) # ctype,encoding value: # rar file None None (INI file, CSV  Pieces, apk files) # txt text/plain None # py Text/x-python None # gif image/gif None # png image/x-png none # jpg Image/pjpeg None # PDF Application/pdf None # docApplication/msword None # Zip application/x-zip-compressed none data=open (file, ' RB ') Ctype,encoding=mimetypes.guess_ Type (file) If CType is None or encoding are not none:ctype= ' Application/octet-stream ' maintype,subtype=ctype.split ('/' , 1) # constructs the Mimebase object as the file attachment content and attaches to the root container msg=mimebase (maintype,subtype) msg.set_payload (Data.read ()) Msg.add_header ('
Content-disposition ', ' attachment ', Filename=os.path.basename (file)) Data.close () encoders.encode_base64 (msg) Msgroot.attach (msg) smtp=smtplib. SMTP (mailserver) smtp.login (Username,password) Smtp.sendmail (sender,receiver,msgroot.as_string ()) Smtp.quit ()

Or like the following:

ATT = mimetext (open (' h:\\python\\1.jpg ', ' RB '). Read (), ' base64 ', ' Utf-8 ')    
att["content-type"] = ' application/ Octet-stream '    
att["content-disposition"] = ' attachment filename= ' 1.jpg '    
Msgroot.attach (ATT)   

Here are a few things to note:
The 1.Message object consists of two parts: header and payload (I understand it should be the content to carry) so set_payload is setting the load
2.
That means Mimeimage and mimeaudio, others need to encode themselves.

If you want to send a group of emails, you actually write receiver a list .

At first I didn't quite understand the difference between Mimemultipart and other

Class Email.mime.multipart.MIMEMultipart (_subtype= ' mixed ', Boundary=none, _subparts=none, **_params)

Module:email.mime.multipart

A Subclass of Mimebase, this is a intermediate base class for MIME messages that are Tipart. Optional _subtype defaults to mixed, but can is used to specify the subtype of the. A Content-type header of Multipart/_subtype would be added to the Message object. A Mime-version header would also be added.

Class Email.mime.text.MIMEText (_text, _subtype= ' plain ', _charset=none)

Module:email.mime.text

A Subclass of Mimenonmultipart, the Mimetext class is used to create MIME objects of major e-text. The _text is the string for the payload. _subtype is the minor type and defaults to plain. _charset is the character set of the text and is passed as a argument to the Mimenonmultipart constructor; It defaults to Us-ascii if the string contains only ASCII code points, and Utf-8 otherwise.

In fact, Mimemultipart is like a collection where you can add something else that you want to add.

You can also add audio, and so on, as described in Python documents
Email.message (Introduction to the message sent)

There are a few more questions that I have just begun to wonder:
1. When adding attachments, you need to set your own headers, then how to set, what content
2. What is the parameter when constructing the Mimebase object (in fact, which is the annotation in the above code, which indicates what type of attachment it is)
MIME protocol Analysis
Liaoche's official website (SMTP send mail)
MIME protocol (contains a more comprehensive MIME type)

Related Article

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.