Python for sending mail

Source: Internet
Author: User
Tags imap rfc all mail

Today's attempt to use Python, write programs to send mail, the following is the implementation process:

One: Introduction to Mail transfer

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

Two: Python module

1. Smtplib Module

Smtplib. SMTP ([host[, port[, local_hostname[, timeout]])

The SMTP class constructor, which represents the connection to the SMTP server, enables you to send instructions to the SMTP server to perform related operations such as logging in and sending mail. All parameters are optional.

HOST:SMTP Server Host Name

The port of the PORT:SMTP service is 25 by default, and when the SMTP object is created, the Connect method is automatically called to connect to the server at initialization time.

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.

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: 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 mail. 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.

Smtp.quit (): Disconnects from the SMTP server, which is equivalent to sending a "quit" instruction.

2.Python Email Module
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.
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.

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.

Class Email.mime.text.MIMEText (_text)
Use the string _text to generate the body text of the MIME object.

Three: examples

According to the module described above, you can implement the following code to send the message:

(This example uses 163 mailboxes with an SMTP server address of smtp.163.com, port number: 25)

#!/usr/bin/env python  
Import smtplib

from Email.mime.text Import Mimetext
mailto_list=[ [email protected] .com ]            #收件人 (list)
mail_host= "smtp.163.com"
mail_user= "name"                              #用户名

mail_pass= "PWD"
mail_postfix= "Postfix"

def send_mail (to_list,sub,content):

me= "Hello" + "<"+mail_user+" @ "+mail_postfix+ ">"
msg = Mimetext (content,_subtype= ' plain ')
msg[' Subject ' = Sub
Msg[' from '] = Me
Msg[' to '] = ";". Join (to_list) #将收件人列表以 '; ' Delimited
Try
Server = Smtplib. SMTP ()
Server.connect (Mail_host)
Server.login (Mail_user,mail_pass)
Server.sendmail (Me, To_list, msg.as_string ())
Server.close ()
Return True
Except Exception, E:
Print str (e)
Return False
For I in range (100):
If Send_mail (mailto_list, "Hello", "haha!"): #邮件主题:Hello, message content: haha!

Print "done!"
Else
Print "failed!"

Python for sending mail

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.