Two examples of Python-sent messages (Python email attachments can be implemented using the email module)

Source: Internet
Author: User
Tags imap rfc all mail
You can use the Python email module to send messages with attachments.

SMTP (Simple Mail Transfer Protocol)
The Mail delivery agent (mail Transfer AGENT,MTA) program uses the SMTP protocol to send email to the recipient's mail server. The SMTP protocol can only be used to send messages and cannot be used 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 messages. It works in two cases: one is the transfer of e-mail from the client to the server, and the other from one server to another.

POP3 (Post Office Protocol) & IMAP (Internet Message Access Protocol)
The POP protocol and the IMAP protocol are the two most common protocols used for mail reception. These two protocols are supported by almost all mail clients and servers.

The POP3 protocol provides users with a simple, standard way to access mailboxes and get e-mail. e-mail clients that use the POP3 protocol typically work by connecting to the server, getting all the information, and saving the messages on the user's host, removing them from the server, and then disconnecting them. The default TCP port number for the POP3 protocol is 110.

The IMAP protocol also provides a convenient e-mail download service that allows users to read offline. e-mail clients that use the IMAP protocol usually keep the information on the server until the user explicitly deletes it. This feature allows multiple clients to manage one mailbox at a time. The IMAP protocol provides a summary browsing feature that allows users to decide whether to download after reading all the message arrival time, subject, sender, size, and so on. The default TCP port number for the IMAP protocol is 143.

Message Format (RFC 2822)
Each message has two parts: a message header and a message body, separated by a blank line.

Message headers Each field contains two parts: A field name and a field value, separated by a colon. There are two fields to be aware of: the 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, the sender field must be specified, 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 sender field should be used simultaneously.

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 by RFC 2822, the message body is simply a sequence of ASCII-encoded characters.

MIME (Multipurpose Internet Mail Extensions) (RFC 1341)
MIME extends the format of messages to support non-ASCII encoded text, non-text attachments, and message bodies that contain multiple parts (multi-part).

Python Email Module

1. Class Email.message.Message

__getitem__,__setitem__ implement Obj[key] form of access.
Msg.attach (playload): Adds playload to the current MSG.
Msg.set_playload (playload): Sets the message body of the whole MSG object to Playload.
Msg.add_header (_name, _value, **_params): Adds a message header field.
2. Class Email.mime.base.MIMEBase (_maintype, _subtype, **_params)
The base class for all MIME classes, which is a subclass of the Email.message.Message class.

3. Class Email.mime.multipart.MIMEMultipart ()

In the 3.0 version of the email module (Python 2.3-python 2.5), this class is located in email. Mimemultipart.mimemultipart.
This class is a direct subclass of Mimebase, which is used to generate MIME objects that contain multiple parts of the message body.

4. Class Email.mime.text.MIMEText (_text)

Use the string _text to generate the body text of the MIME object.

Code implementation

Copy the Code code as follows:


!/usr/bin/env python
#-*-Coding:utf-8-*-

From Email.mime.multipart import Mimemultipart
From email.mime.base import mimebase
From Email.mime.text import Mimetext

# python 2.3.*: email. Utils email. Encoders
From email.utils import commaspace,formatdate
From email import encoders

Import OS

#server [' name '], server[' user '], server[' passwd ']
def send_mail (server, fro, to, subject, text, files=[]):
Assert type (server) = = Dict
Assert type (TO) = = List
Assert type (files) = = List

msg = Mimemultipart ()
Msg[' from '] = fro
msg[' Subject '] = Subject
msg["to" = Commaspace.join (to) #COMMASPACE = = ', '
msg[' Date ' = FormatDate (localtime=true)
Msg.attach (Mimetext (text))

For file in Files:
Part = mimebase (' Application ', ' Octet-stream ') # ' Octet-stream ': binary data
Part.set_payload (open (file, ' RB '. Read ()))
Encoders.encode_base64 (part)
Part.add_header (' content-disposition ', ' attachment; filename= '%s '% os.path.basename (file))
Msg.attach (part)

Import Smtplib
SMTP = Smtplib. SMTP (server[' name '])
Smtp.login (server[' user '), server[' passwd '])
Smtp.sendmail (fro, To, msg.as_string ())
Smtp.close ()

Use Python's smtplib library for mail delivery

Copy the Code code as follows:


Import Smtplib
Def sendmail ():
Try
Smtp=smtplib. SMTP (HOST)
Smtp.login (User,password) #登录邮箱
Smtp.sendmail (user+ "@" +profix,to,msg) #发送邮件
Smtp.quit ()
print ' Email send success '
Except Exception,e:
Print E
print ' email send failed. '

The message can be sent

And then I learned a little bit about defining msg
There are several class libraries in Python that generate rich msg formats
Summarize a simple mimetext, you can edit many message header information, you can also edit the message format
From email. Mimetext Import Mimetext
Msg=mimetext ("What To send", "format, for example: Html,plain", "encoding, for example: Gb2312,utf-8")
msg[' from ']= ' message displays the sender's name '
msg[' to ']= ' message displays the recipient's name '
msg[' Subject ']= ' mail header '
These can all be set without

  • 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.